Updating code to use generics

This commit is contained in:
Patrick Gotthard 2014-04-13 11:15:01 +02:00
parent 05dd80dd82
commit 0f30ab14ee
53 changed files with 1050 additions and 993 deletions

View file

@ -16,7 +16,6 @@
package org.rometools.propono.atom.client; package org.rometools.propono.atom.client;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -36,12 +35,15 @@ import com.sun.syndication.feed.atom.Entry;
import com.sun.syndication.io.impl.Atom10Parser; import com.sun.syndication.io.impl.Atom10Parser;
/** /**
* This class models an Atom Publising Protocol Service Document. It extends the common {@link com.sun.syndication.propono.atom.common.Collection} class to add * This class models an Atom Publising Protocol Service Document. It extends the common
* a <code>getEntry()</code> method and to return {@link com.sun.syndication.propono.atom.client.ClientWorkspace} objects instead of common * {@link com.sun.syndication.propono.atom.common.Collection} class to add a <code>getEntry()</code>
* {@link com.sun.syndication.propono.atom.common.Workspace}s. * method and to return {@link com.sun.syndication.propono.atom.client.ClientWorkspace} objects
* instead of common {@link com.sun.syndication.propono.atom.common.Workspace}s.
*/ */
public class ClientAtomService extends AtomService { public class ClientAtomService extends AtomService {
private static Log logger = LogFactory.getLog(ClientAtomService.class);
private static final Log LOGGER = LogFactory.getLog(ClientAtomService.class);
private String uri = null; private String uri = null;
private HttpClient httpClient = null; private HttpClient httpClient = null;
private AuthStrategy authStrategy = null; private AuthStrategy authStrategy = null;
@ -103,13 +105,13 @@ public class ClientAtomService extends AtomService {
httpClient.executeMethod(method); httpClient.executeMethod(method);
final SAXBuilder builder = new SAXBuilder(); final SAXBuilder builder = new SAXBuilder();
String doc = method.getResponseBodyAsString(); final String doc = method.getResponseBodyAsString();
logger.debug(doc); LOGGER.debug(doc);
return builder.build(method.getResponseBodyAsStream()); return builder.build(method.getResponseBodyAsStream());
} catch (final Throwable t) { } catch (final Throwable t) {
final String msg = "ERROR retrieving Atom Service Document, code: " + code; final String msg = "ERROR retrieving Atom Service Document, code: " + code;
logger.debug(msg, t); LOGGER.debug(msg, t);
throw new ProponoException(msg, t); throw new ProponoException(msg, t);
} finally { } finally {
if (method != null) { if (method != null) {
@ -121,10 +123,8 @@ public class ClientAtomService extends AtomService {
/** Deserialize an Atom service XML document into an object */ /** Deserialize an Atom service XML document into an object */
private void parseAtomServiceDocument(final Document document) throws ProponoException { private void parseAtomServiceDocument(final Document document) throws ProponoException {
final Element root = document.getRootElement(); final Element root = document.getRootElement();
final List spaces = root.getChildren("workspace", AtomService.ATOM_PROTOCOL); final List<Element> spaces = root.getChildren("workspace", AtomService.ATOM_PROTOCOL);
final Iterator iter = spaces.iterator(); for (final Element e : spaces) {
while (iter.hasNext()) {
final Element e = (Element) iter.next();
addWorkspace(new ClientWorkspace(e, this, uri)); addWorkspace(new ClientWorkspace(e, this, uri));
} }
} }
@ -135,4 +135,5 @@ public class ClientAtomService extends AtomService {
HttpClient getHttpClient() { HttpClient getHttpClient() {
return httpClient; return httpClient;
} }
} }

View file

@ -17,7 +17,6 @@ package org.rometools.propono.atom.client;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -26,8 +25,6 @@ import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom2.Element; import org.jdom2.Element;
import org.rometools.propono.atom.common.AtomService; import org.rometools.propono.atom.common.AtomService;
import org.rometools.propono.atom.common.Categories; import org.rometools.propono.atom.common.Categories;
@ -39,16 +36,15 @@ import com.sun.syndication.feed.atom.Entry;
import com.sun.syndication.io.impl.Atom10Parser; import com.sun.syndication.io.impl.Atom10Parser;
/** /**
* Models an Atom collection, extends Collection and adds methods for adding, retrieving, updateing and deleting entries. * Models an Atom collection, extends Collection and adds methods for adding, retrieving, updateing
* and deleting entries.
*/ */
public class ClientCollection extends Collection { public class ClientCollection extends Collection {
static final Log logger = LogFactory.getLog(ClientCollection.class);
private final List categories = new ArrayList();
private HttpClient httpClient = null;
private AuthStrategy authStrategy = null;
private final boolean writable = true; private final boolean writable = true;
private HttpClient httpClient = null;
private AuthStrategy authStrategy = null;
private ClientWorkspace workspace = null; private ClientWorkspace workspace = null;
private ClientAtomService service = null; private ClientAtomService service = null;
@ -85,14 +81,16 @@ public class ClientCollection extends Collection {
} }
/** /**
* Get iterator over entries in this collection. Entries returned are considered to be partial entries cannot be saved/updated. * Get iterator over entries in this collection. Entries returned are considered to be partial
* entries cannot be saved/updated.
*/ */
public Iterator getEntries() throws ProponoException { public Iterator<ClientEntry> getEntries() throws ProponoException {
return new EntryIterator(this); return new EntryIterator(this);
} }
/** /**
* Get full entry specified by entry edit URI. Note that entry may or may not be associated with this collection. * Get full entry specified by entry edit URI. Note that entry may or may not be associated with
* this collection.
* *
* @return ClientEntry or ClientMediaEntry specified by URI. * @return ClientEntry or ClientMediaEntry specified by URI.
*/ */
@ -144,8 +142,9 @@ public class ClientCollection extends Collection {
} }
/** /**
* Create new media entry assocaited with collection, but do not save. server. Depending on the Atom server, you may or may not be able to persist the * Create new media entry assocaited with collection, but do not save. server. Depending on the
* properties of the entry that is returned. * Atom server, you may or may not be able to persist the properties of the entry that is
* returned.
* *
* @param title Title to used for uploaded file. * @param title Title to used for uploaded file.
* @param slug String to be used in file-name of stored file * @param slug String to be used in file-name of stored file
@ -161,8 +160,9 @@ public class ClientCollection extends Collection {
} }
/** /**
* Create new media entry assocaited with collection, but do not save. server. Depending on the Atom server, you may or may not be able to. persist the * Create new media entry assocaited with collection, but do not save. server. Depending on the
* properties of the entry that is returned. * Atom server, you may or may not be able to. persist the properties of the entry that is
* returned.
* *
* @param title Title to used for uploaded file. * @param title Title to used for uploaded file.
* @param slug String to be used in file-name of stored file * @param slug String to be used in file-name of stored file
@ -178,7 +178,8 @@ public class ClientCollection extends Collection {
} }
/** /**
* Save to collection a new entry that was created by a createEntry() or createMediaEntry() and save it to the server. * Save to collection a new entry that was created by a createEntry() or createMediaEntry() and
* save it to the server.
* *
* @param entry Entry to be saved. * @param entry Entry to be saved.
* @throws ProponoException on error, if collection is not writable or if entry is partial. * @throws ProponoException on error, if collection is not writable or if entry is partial.
@ -206,20 +207,19 @@ public class ClientCollection extends Collection {
} }
} }
final List acceptElems = element.getChildren("accept", AtomService.ATOM_PROTOCOL); final List<Element> acceptElems = element.getChildren("accept", AtomService.ATOM_PROTOCOL);
if (acceptElems != null && acceptElems.size() > 0) { if (acceptElems != null && acceptElems.size() > 0) {
for (final Iterator it = acceptElems.iterator(); it.hasNext();) { for (final Element acceptElem : acceptElems) {
final Element acceptElem = (Element) it.next();
addAccept(acceptElem.getTextTrim()); addAccept(acceptElem.getTextTrim());
} }
} }
// Loop to parse <app:categories> element to Categories objects // Loop to parse <app:categories> element to Categories objects
final List catsElems = element.getChildren("categories", AtomService.ATOM_PROTOCOL); final List<Element> catsElems = element.getChildren("categories", AtomService.ATOM_PROTOCOL);
for (final Iterator catsIter = catsElems.iterator(); catsIter.hasNext();) { for (final Element catsElem : catsElems) {
final Element catsElem = (Element) catsIter.next();
final Categories cats = new ClientCategories(catsElem, this); final Categories cats = new ClientCategories(catsElem, this);
addCategories(cats); addCategories(cats);
} }
} }
} }

View file

@ -20,6 +20,7 @@ import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -42,27 +43,26 @@ import com.sun.syndication.feed.atom.Entry;
import com.sun.syndication.feed.atom.Link; import com.sun.syndication.feed.atom.Link;
import com.sun.syndication.io.impl.Atom10Generator; import com.sun.syndication.io.impl.Atom10Generator;
import com.sun.syndication.io.impl.Atom10Parser; import com.sun.syndication.io.impl.Atom10Parser;
import java.util.Date;
/** /**
* Client implementation of Atom entry, extends ROME Entry to add methods for easily getting/setting content, updating and removing the entry from the server. * Client implementation of Atom entry, extends ROME Entry to add methods for easily getting/setting
* content, updating and removing the entry from the server.
*/ */
public class ClientEntry extends Entry { public class ClientEntry extends Entry {
private static final Log logger = LogFactory.getLog(ClientEntry.class);
boolean partial = false; private static final long serialVersionUID = 1L;
private static final Log LOGGER = LogFactory.getLog(ClientEntry.class);
private ClientAtomService service = null; private ClientAtomService service = null;
private ClientCollection collection = null; private ClientCollection collection = null;
protected boolean partial = false;
public ClientEntry(final ClientAtomService service, final ClientCollection collection) { public ClientEntry(final ClientAtomService service, final ClientCollection collection) {
super();
this.service = service; this.service = service;
this.collection = collection; this.collection = collection;
} }
public ClientEntry(final ClientAtomService service, final ClientCollection collection, final Entry entry, final boolean partial) throws ProponoException { public ClientEntry(final ClientAtomService service, final ClientCollection collection, final Entry entry, final boolean partial) throws ProponoException {
super();
this.service = service; this.service = service;
this.collection = collection; this.collection = collection;
this.partial = partial; this.partial = partial;
@ -77,28 +77,31 @@ public class ClientEntry extends Entry {
* Set content of entry. * Set content of entry.
* *
* @param contentString content string. * @param contentString content string.
* @param type Must be "text" for plain text, "html" for escaped HTML, "xhtml" for XHTML or a valid MIME content-type. * @param type Must be "text" for plain text, "html" for escaped HTML, "xhtml" for XHTML or a
* valid MIME content-type.
*/ */
public void setContent(final String contentString, final String type) { public void setContent(final String contentString, final String type) {
final Content newContent = new Content(); final Content newContent = new Content();
newContent.setType(type == null ? Content.HTML : type); newContent.setType(type == null ? Content.HTML : type);
newContent.setValue(contentString); newContent.setValue(contentString);
final ArrayList contents = new ArrayList(); final ArrayList<Content> contents = new ArrayList<Content>();
contents.add(newContent); contents.add(newContent);
setContents(contents); setContents(contents);
} }
/** /**
* Convenience method to set first content object in content collection. Atom 1.0 allows only one content element per entry. * Convenience method to set first content object in content collection. Atom 1.0 allows only
* one content element per entry.
*/ */
public void setContent(final Content c) { public void setContent(final Content c) {
final ArrayList contents = new ArrayList(); final ArrayList<Content> contents = new ArrayList<Content>();
contents.add(c); contents.add(c);
setContents(contents); setContents(contents);
} }
/** /**
* Convenience method to get first content object in content collection. Atom 1.0 allows only one content element per entry. * Convenience method to get first content object in content collection. Atom 1.0 allows only
* one content element per entry.
*/ */
public Content getContent() { public Content getContent() {
if (getContents() != null && getContents().size() > 0) { if (getContents() != null && getContents().size() > 0) {
@ -123,9 +126,11 @@ public class ClientEntry extends Entry {
} }
/** /**
* Update entry by posting new representation of entry to server. Note that you should not attempt to update entries that you get from iterating over a * Update entry by posting new representation of entry to server. Note that you should not
* collection they may be "partial" entries. If you want to update an entry, you must get it via one of the <code>getEntry()</code> methods in * attempt to update entries that you get from iterating over a collection they may be "partial"
* {@link com.sun.syndication.propono.atom.common.Collection} or {@link com.sun.syndication.propono.atom.common.AtomService}. * entries. If you want to update an entry, you must get it via one of the
* <code>getEntry()</code> methods in {@link com.sun.syndication.propono.atom.common.Collection}
* or {@link com.sun.syndication.propono.atom.common.AtomService}.
* *
* @throws ProponoException If entry is a "partial" entry. * @throws ProponoException If entry is a "partial" entry.
*/ */
@ -149,7 +154,7 @@ public class ClientEntry extends Entry {
} catch (final Exception e) { } catch (final Exception e) {
final String msg = "ERROR: updating entry, HTTP code: " + code; final String msg = "ERROR: updating entry, HTTP code: " + code;
logger.debug(msg, e); LOGGER.debug(msg, e);
throw new ProponoException(msg, e); throw new ProponoException(msg, e);
} finally { } finally {
method.releaseConnection(); method.releaseConnection();
@ -216,16 +221,16 @@ public class ClientEntry extends Entry {
} catch (final Exception e) { } catch (final Exception e) {
final String msg = "ERROR: saving entry, HTTP code: " + code; final String msg = "ERROR: saving entry, HTTP code: " + code;
logger.debug(msg, e); LOGGER.debug(msg, e);
throw new ProponoException(msg, e); throw new ProponoException(msg, e);
} finally { } finally {
method.releaseConnection(); method.releaseConnection();
} }
final Header locationHeader = method.getResponseHeader("Location"); final Header locationHeader = method.getResponseHeader("Location");
if (locationHeader == null) { if (locationHeader == null) {
logger.warn("WARNING added entry, but no location header returned"); LOGGER.warn("WARNING added entry, but no location header returned");
} else if (getEditURI() == null) { } else if (getEditURI() == null) {
final List links = getOtherLinks(); final List<Link> links = getOtherLinks();
final Link link = new Link(); final Link link = new Link();
link.setHref(locationHeader.getValue()); link.setHref(locationHeader.getValue());
link.setRel("edit"); link.setRel("edit");
@ -252,7 +257,7 @@ public class ClientEntry extends Entry {
} }
@Override @Override
public void setCreated(Date d) { public void setCreated(final Date d) {
// protected against null created property (an old Atom 0.3 property) // protected against null created property (an old Atom 0.3 property)
if (d != null) { if (d != null) {
super.setCreated(d); super.setCreated(d);

View file

@ -47,10 +47,13 @@ import com.sun.syndication.io.impl.Atom10Generator;
import com.sun.syndication.io.impl.Atom10Parser; import com.sun.syndication.io.impl.Atom10Parser;
/** /**
* Client implementation of Atom media-link entry, an Atom entry that provides meta-data for a media file (e.g. uploaded image or audio file). * Client implementation of Atom media-link entry, an Atom entry that provides meta-data for a media
* file (e.g. uploaded image or audio file).
*/ */
public class ClientMediaEntry extends ClientEntry { public class ClientMediaEntry extends ClientEntry {
private static final Log logger = LogFactory.getLog(ClientMediaEntry.class);
private static final long serialVersionUID = 1L;
private static final Log LOGGER = LogFactory.getLog(ClientMediaEntry.class);
private String slug = null; private String slug = null;
private byte[] bytes; private byte[] bytes;
@ -76,7 +79,7 @@ public class ClientMediaEntry extends ClientEntry {
setSlug(slug); setSlug(slug);
final Content content = new Content(); final Content content = new Content();
content.setType(contentType); content.setType(contentType);
final List contents = new ArrayList(); final List<Content> contents = new ArrayList<Content>();
contents.add(content); contents.add(content);
setContents(contents); setContents(contents);
} }
@ -89,7 +92,7 @@ public class ClientMediaEntry extends ClientEntry {
setSlug(slug); setSlug(slug);
final Content content = new Content(); final Content content = new Content();
content.setType(contentType); content.setType(contentType);
final List contents = new ArrayList(); final List<Content> contents = new ArrayList<Content>();
contents.add(content); contents.add(content);
setContents(contents); setContents(contents);
} }
@ -104,7 +107,8 @@ public class ClientMediaEntry extends ClientEntry {
} }
/** /**
* Set media resource data as a byte array, don't try this if you have already set the data as an InputStream. * Set media resource data as a byte array, don't try this if you have already set the data as
* an InputStream.
*/ */
public void setBytes(final byte[] bytes) { public void setBytes(final byte[] bytes) {
if (inputStream != null) { if (inputStream != null) {
@ -123,7 +127,8 @@ public class ClientMediaEntry extends ClientEntry {
} }
/** /**
* Set media resource data as an input stream, don't try this if you have already set the data as a byte array. * Set media resource data as an input stream, don't try this if you have already set the data
* as a byte array.
*/ */
public void setInputStream(final InputStream inputStream) { public void setInputStream(final InputStream inputStream) {
if (bytes != null) { if (bytes != null) {
@ -133,7 +138,8 @@ public class ClientMediaEntry extends ClientEntry {
} }
/** /**
* Get media link URI for editing the media resource associated with this entry via HTTP PUT or DELETE. * Get media link URI for editing the media resource associated with this entry via HTTP PUT or
* DELETE.
*/ */
public String getMediaLinkURI() { public String getMediaLinkURI() {
for (int i = 0; i < getOtherLinks().size(); i++) { for (int i = 0; i < getOtherLinks().size(); i++) {
@ -146,7 +152,8 @@ public class ClientMediaEntry extends ClientEntry {
} }
/** /**
* Get media resource as an InputStream, should work regardless of whether you set the media resource data as an InputStream or as a byte array. * Get media resource as an InputStream, should work regardless of whether you set the media
* resource data as an InputStream or as a byte array.
*/ */
public InputStream getAsStream() throws ProponoException { public InputStream getAsStream() throws ProponoException {
if (getContents() != null && getContents().size() > 0) { if (getContents() != null && getContents().size() > 0) {
@ -237,8 +244,6 @@ public class ClientMediaEntry extends ClientEntry {
setCollection(col); setCollection(col);
final EntityEnclosingMethod method = new PostMethod(col.getHrefResolved()); final EntityEnclosingMethod method = new PostMethod(col.getHrefResolved());
getCollection().addAuthentication(method); getCollection().addAuthentication(method);
final StringWriter sw = new StringWriter();
final boolean error = false;
try { try {
final Content c = getContents().get(0); final Content c = getContents().get(0);
if (inputStream != null) { if (inputStream != null) {
@ -274,9 +279,9 @@ public class ClientMediaEntry extends ClientEntry {
} }
final Header locationHeader = method.getResponseHeader("Location"); final Header locationHeader = method.getResponseHeader("Location");
if (locationHeader == null) { if (locationHeader == null) {
logger.warn("WARNING added entry, but no location header returned"); LOGGER.warn("WARNING added entry, but no location header returned");
} else if (getEditURI() == null) { } else if (getEditURI() == null) {
final List links = getOtherLinks(); final List<Link> links = getOtherLinks();
final Link link = new Link(); final Link link = new Link();
link.setHref(locationHeader.getValue()); link.setHref(locationHeader.getValue());
link.setRel("edit"); link.setRel("edit");

View file

@ -15,7 +15,6 @@
*/ */
package org.rometools.propono.atom.client; package org.rometools.propono.atom.client;
import java.util.Iterator;
import java.util.List; import java.util.List;
import org.jdom2.Element; import org.jdom2.Element;
@ -24,10 +23,13 @@ import org.rometools.propono.atom.common.Workspace;
import org.rometools.propono.utils.ProponoException; import org.rometools.propono.utils.ProponoException;
/** /**
* Represents Atom protocol workspace on client-side. It extends the common {@link com.sun.syndication.propono.atom.common.Workspace} to return * Represents Atom protocol workspace on client-side. It extends the common
* {@link com.sun.syndication.propono.atom.client.ClientCollection} objects instead of common {@link com.sun.syndication.propono.atom.common.Collection}s. * {@link com.sun.syndication.propono.atom.common.Workspace} to return
* {@link com.sun.syndication.propono.atom.client.ClientCollection} objects instead of common
* {@link com.sun.syndication.propono.atom.common.Collection}s.
*/ */
public class ClientWorkspace extends Workspace { public class ClientWorkspace extends Workspace {
private ClientAtomService atomService = null; private ClientAtomService atomService = null;
ClientWorkspace(final Element e, final ClientAtomService atomService, final String baseURI) throws ProponoException { ClientWorkspace(final Element e, final ClientAtomService atomService, final String baseURI) throws ProponoException {
@ -50,11 +52,10 @@ public class ClientWorkspace extends Workspace {
if (titleElem.getAttribute("type", AtomService.ATOM_FORMAT) != null) { if (titleElem.getAttribute("type", AtomService.ATOM_FORMAT) != null) {
setTitleType(titleElem.getAttribute("type", AtomService.ATOM_FORMAT).getValue()); setTitleType(titleElem.getAttribute("type", AtomService.ATOM_FORMAT).getValue());
} }
final List collections = element.getChildren("collection", AtomService.ATOM_PROTOCOL); final List<Element> collections = element.getChildren("collection", AtomService.ATOM_PROTOCOL);
final Iterator iter = collections.iterator(); for (final Element e : collections) {
while (iter.hasNext()) {
final Element e = (Element) iter.next();
addCollection(new ClientCollection(e, this, baseURI)); addCollection(new ClientCollection(e, this, baseURI));
} }
} }
} }

View file

@ -34,16 +34,15 @@ import com.sun.syndication.io.WireFeedInput;
/** /**
* Enables iteration over entries in Atom protocol collection. * Enables iteration over entries in Atom protocol collection.
*/ */
public class EntryIterator implements Iterator { public class EntryIterator implements Iterator<ClientEntry> {
static final Log logger = LogFactory.getLog(EntryIterator.class);
private static final Log LOGGER = LogFactory.getLog(EntryIterator.class);
private final ClientCollection collection; private final ClientCollection collection;
int maxEntries = 20; private Iterator<Entry> members = null;
int offset = 0; private Feed col = null;
Iterator members = null; private final String collectionURI;
Feed col = null; private String nextURI;
String collectionURI;
String nextURI;
EntryIterator(final ClientCollection collection) throws ProponoException { EntryIterator(final ClientCollection collection) throws ProponoException {
this.collection = collection; this.collection = collection;
@ -61,7 +60,7 @@ public class EntryIterator implements Iterator {
try { try {
getNextEntries(); getNextEntries();
} catch (final Exception ignored) { } catch (final Exception ignored) {
logger.error("ERROR getting next entries", ignored); LOGGER.error("ERROR getting next entries", ignored);
} }
} }
return members.hasNext(); return members.hasNext();
@ -71,9 +70,9 @@ public class EntryIterator implements Iterator {
* Get next entry in collection. * Get next entry in collection.
*/ */
@Override @Override
public Object next() { public ClientEntry next() {
if (hasNext()) { if (hasNext()) {
final Entry romeEntry = (Entry) members.next(); final Entry romeEntry = members.next();
try { try {
if (!romeEntry.isMediaEntry()) { if (!romeEntry.isMediaEntry()) {
return new ClientEntry(null, collection, romeEntry, true); return new ClientEntry(null, collection, romeEntry, true);
@ -113,18 +112,17 @@ public class EntryIterator implements Iterator {
colGet.releaseConnection(); colGet.releaseConnection();
} }
members = col.getEntries().iterator(); members = col.getEntries().iterator();
offset += col.getEntries().size(); col.getEntries().size();
nextURI = null; nextURI = null;
final List altLinks = col.getOtherLinks(); final List<Link> altLinks = col.getOtherLinks();
if (altLinks != null) { if (altLinks != null) {
final Iterator iter = altLinks.iterator(); for (final Link link : altLinks) {
while (iter.hasNext()) {
final Link link = (Link) iter.next();
if ("next".equals(link.getRel())) { if ("next".equals(link.getRel())) {
nextURI = link.getHref(); nextURI = link.getHref();
} }
} }
} }
} }
} }

View file

@ -18,7 +18,6 @@ package org.rometools.propono.atom.client;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
@ -68,7 +67,8 @@ public class OAuthStrategy implements AuthStrategy {
private String tokenSecret = null; private String tokenSecret = null;
/** /**
* Create OAuth authentcation strategy and negotiate with services to obtain access token to be used in subsequent calls. * Create OAuth authentcation strategy and negotiate with services to obtain access token to be
* used in subsequent calls.
* *
* @param username Username to be used in authentication * @param username Username to be used in authentication
* @param key Consumer key * @param key Consumer key
@ -112,19 +112,19 @@ public class OAuthStrategy implements AuthStrategy {
// add OAuth name/values to request query string // add OAuth name/values to request query string
// wish we didn't have to parse them apart first, ugh // wish we didn't have to parse them apart first, ugh
List originalqlist = null; List<NameValuePair> originalqlist = null;
if (method.getQueryString() != null) { if (method.getQueryString() != null) {
String qstring = method.getQueryString().trim(); String qstring = method.getQueryString().trim();
qstring = qstring.startsWith("?") ? qstring.substring(1) : qstring; qstring = qstring.startsWith("?") ? qstring.substring(1) : qstring;
originalqlist = new ParameterParser().parse(qstring, '&'); originalqlist = new ParameterParser().parse(qstring, '&');
} else { } else {
originalqlist = new ArrayList(); originalqlist = new ArrayList<NameValuePair>();
} }
// put query string into hashmap form to please OAuth.net classes // put query string into hashmap form to please OAuth.net classes
final Map params = new HashMap(); final Map<String, String> params = new HashMap<String, String>();
for (final Iterator it = originalqlist.iterator(); it.hasNext();) { for (final Object element : originalqlist) {
final NameValuePair pair = (NameValuePair) it.next(); final NameValuePair pair = (NameValuePair) element;
params.put(pair.getName(), pair.getValue()); params.put(pair.getName(), pair.getValue());
} }
@ -165,10 +165,7 @@ public class OAuthStrategy implements AuthStrategy {
final HttpMethodBase method; final HttpMethodBase method;
final String content; final String content;
Map<String, String> params = new HashMap<String, String>(); final Map<String, String> params = new HashMap<String, String>();
if (params == null) {
params = new HashMap<String, String>();
}
params.put("oauth_version", "1.0"); params.put("oauth_version", "1.0");
if (username != null) { if (username != null) {
params.put("xoauth_requestor_id", username); params.put("xoauth_requestor_id", username);
@ -259,35 +256,37 @@ public class OAuthStrategy implements AuthStrategy {
} }
} }
// TODO review switch without 'default'
switch (state) { switch (state) {
case UNAUTHORIZED: case UNAUTHORIZED:
if (token != null && secret != null) { if (token != null && secret != null) {
requestToken = token; requestToken = token;
tokenSecret = secret; tokenSecret = secret;
state = State.REQUEST_TOKEN; state = State.REQUEST_TOKEN;
} else { } else {
throw new ProponoException("ERROR: requestToken or tokenSecret is null"); throw new ProponoException("ERROR: requestToken or tokenSecret is null");
} }
break; break;
case REQUEST_TOKEN: case REQUEST_TOKEN:
if (method.getStatusCode() == 200) { if (method.getStatusCode() == 200) {
state = State.AUTHORIZED; state = State.AUTHORIZED;
} else { } else {
throw new ProponoException("ERROR: authorization returned code: " + method.getStatusCode()); throw new ProponoException("ERROR: authorization returned code: " + method.getStatusCode());
} }
break; break;
case AUTHORIZED: case AUTHORIZED:
if (token != null && secret != null) { if (token != null && secret != null) {
accessToken = token; accessToken = token;
tokenSecret = secret; tokenSecret = secret;
state = State.ACCESS_TOKEN; state = State.ACCESS_TOKEN;
} else { } else {
throw new ProponoException("ERROR: accessToken or tokenSecret is null"); throw new ProponoException("ERROR: accessToken or tokenSecret is null");
} }
break; break;
} }
} }
} }

View file

@ -18,7 +18,6 @@
package org.rometools.propono.atom.common; package org.rometools.propono.atom.common;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import org.jdom2.Document; import org.jdom2.Document;
@ -27,12 +26,12 @@ import org.jdom2.Namespace;
import org.rometools.propono.utils.ProponoException; import org.rometools.propono.utils.ProponoException;
/** /**
* Models an Atom Publishing Protocol Service Document. Is able to read a Service document from a JDOM Document and to write Service document out as a JDOM * Models an Atom Publishing Protocol Service Document. Is able to read a Service document from a
* Document. * JDOM Document and to write Service document out as a JDOM Document.
*/ */
public class AtomService { public class AtomService {
private List workspaces = new ArrayList(); private List<Workspace> workspaces = new ArrayList<Workspace>();
/** Namespace for Atom Syndication Format */ /** Namespace for Atom Syndication Format */
public static Namespace ATOM_FORMAT = Namespace.getNamespace("atom", "http://www.w3.org/2005/Atom"); public static Namespace ATOM_FORMAT = Namespace.getNamespace("atom", "http://www.w3.org/2005/Atom");
@ -56,14 +55,14 @@ public class AtomService {
/** /**
* Get Workspaces available from service. * Get Workspaces available from service.
*/ */
public List getWorkspaces() { public List<Workspace> getWorkspaces() {
return workspaces; return workspaces;
} }
/** /**
* Set Workspaces of service. * Set Workspaces of service.
*/ */
public void setWorkspaces(final List workspaces) { public void setWorkspaces(final List<Workspace> workspaces) {
this.workspaces = workspaces; this.workspaces = workspaces;
} }
@ -74,8 +73,8 @@ public class AtomService {
* @return Matching Workspace or null if none found. * @return Matching Workspace or null if none found.
*/ */
public Workspace findWorkspace(final String title) { public Workspace findWorkspace(final String title) {
for (final Iterator it = workspaces.iterator(); it.hasNext();) { for (final Object element : workspaces) {
final Workspace ws = (Workspace) it.next(); final Workspace ws = (Workspace) element;
if (title.equals(ws.getTitle())) { if (title.equals(ws.getTitle())) {
return ws; return ws;
} }
@ -89,10 +88,8 @@ public class AtomService {
public static AtomService documentToService(final Document document) throws ProponoException { public static AtomService documentToService(final Document document) throws ProponoException {
final AtomService service = new AtomService(); final AtomService service = new AtomService();
final Element root = document.getRootElement(); final Element root = document.getRootElement();
final List spaces = root.getChildren("workspace", ATOM_PROTOCOL); final List<Element> spaces = root.getChildren("workspace", ATOM_PROTOCOL);
final Iterator iter = spaces.iterator(); for (final Element e : spaces) {
while (iter.hasNext()) {
final Element e = (Element) iter.next();
service.addWorkspace(Workspace.elementToWorkspace(e)); service.addWorkspace(Workspace.elementToWorkspace(e));
} }
return service; return service;
@ -107,9 +104,8 @@ public class AtomService {
final Document doc = new Document(); final Document doc = new Document();
final Element root = new Element("service", ATOM_PROTOCOL); final Element root = new Element("service", ATOM_PROTOCOL);
doc.setRootElement(root); doc.setRootElement(root);
final Iterator iter = service.getWorkspaces().iterator(); final List<Workspace> spaces = service.getWorkspaces();
while (iter.hasNext()) { for (final Workspace space : spaces) {
final Workspace space = (Workspace) iter.next();
root.addContent(space.workspaceToElement()); root.addContent(space.workspaceToElement());
} }
return doc; return doc;

View file

@ -18,7 +18,6 @@
package org.rometools.propono.atom.common; package org.rometools.propono.atom.common;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import org.jdom2.Element; import org.jdom2.Element;
@ -27,10 +26,12 @@ import com.sun.syndication.feed.atom.Category;
import com.sun.syndication.io.impl.Atom10Parser; import com.sun.syndication.io.impl.Atom10Parser;
/** /**
* Models an Atom protocol Categories element, which may contain ROME Atom {@link com.sun.syndication.feed.atom.Category} elements. * Models an Atom protocol Categories element, which may contain ROME Atom
* {@link com.sun.syndication.feed.atom.Category} elements.
*/ */
public class Categories { public class Categories {
private final List categories = new ArrayList(); // of Category objects
private final List<Category> categories = new ArrayList<Category>();
private String baseURI = null; private String baseURI = null;
private Element categoriesElement = null; private Element categoriesElement = null;
private String href = null; private String href = null;
@ -57,7 +58,7 @@ public class Categories {
* *
* @return List of ROME Atom {@link com.sun.syndication.feed.atom.Category} * @return List of ROME Atom {@link com.sun.syndication.feed.atom.Category}
*/ */
public List getCategories() { public List<Category> getCategories() {
return categories; return categories;
} }
@ -112,8 +113,8 @@ public class Categories {
catsElem.setAttribute("href", cats.getHref(), AtomService.ATOM_PROTOCOL); catsElem.setAttribute("href", cats.getHref(), AtomService.ATOM_PROTOCOL);
} else { } else {
// Loop to create <atom:category> elements // Loop to create <atom:category> elements
for (final Iterator catIter = cats.getCategories().iterator(); catIter.hasNext();) { for (final Object element : cats.getCategories()) {
final Category cat = (Category) catIter.next(); final Category cat = (Category) element;
final Element catElem = new Element("category", AtomService.ATOM_FORMAT); final Element catElem = new Element("category", AtomService.ATOM_FORMAT);
catElem.setAttribute("term", cat.getTerm(), AtomService.ATOM_FORMAT); catElem.setAttribute("term", cat.getTerm(), AtomService.ATOM_FORMAT);
if (cat.getScheme() != null) { // optional if (cat.getScheme() != null) { // optional
@ -129,21 +130,24 @@ public class Categories {
} }
protected void parseCategoriesElement(final Element catsElem) { protected void parseCategoriesElement(final Element catsElem) {
if (catsElem.getAttribute("href", AtomService.ATOM_PROTOCOL) != null) { if (catsElem.getAttribute("href", AtomService.ATOM_PROTOCOL) != null) {
setHref(catsElem.getAttribute("href", AtomService.ATOM_PROTOCOL).getValue()); setHref(catsElem.getAttribute("href", AtomService.ATOM_PROTOCOL).getValue());
} }
if (catsElem.getAttribute("fixed", AtomService.ATOM_PROTOCOL) != null) { if (catsElem.getAttribute("fixed", AtomService.ATOM_PROTOCOL) != null) {
if ("yes".equals(catsElem.getAttribute("fixed", AtomService.ATOM_PROTOCOL).getValue())) { if ("yes".equals(catsElem.getAttribute("fixed", AtomService.ATOM_PROTOCOL).getValue())) {
setFixed(true); setFixed(true);
} }
} }
if (catsElem.getAttribute("scheme", AtomService.ATOM_PROTOCOL) != null) { if (catsElem.getAttribute("scheme", AtomService.ATOM_PROTOCOL) != null) {
setScheme(catsElem.getAttribute("scheme", AtomService.ATOM_PROTOCOL).getValue()); setScheme(catsElem.getAttribute("scheme", AtomService.ATOM_PROTOCOL).getValue());
} }
// Loop to parse <atom:category> elemenents to Category objects // Loop to parse <atom:category> elemenents to Category objects
final List catElems = catsElem.getChildren("category", AtomService.ATOM_FORMAT); final List<Element> catElems = catsElem.getChildren("category", AtomService.ATOM_FORMAT);
for (final Iterator catIter = catElems.iterator(); catIter.hasNext();) { for (final Element catElem : catElems) {
final Element catElem = (Element) catIter.next();
final Category cat = new Category(); final Category cat = new Category();
cat.setTerm(catElem.getAttributeValue("term", AtomService.ATOM_FORMAT)); cat.setTerm(catElem.getAttributeValue("term", AtomService.ATOM_FORMAT));
cat.setLabel(catElem.getAttributeValue("label", AtomService.ATOM_FORMAT)); cat.setLabel(catElem.getAttributeValue("label", AtomService.ATOM_FORMAT));
@ -151,4 +155,5 @@ public class Categories {
addCategory(cat); addCategory(cat);
} }
} }
} }

View file

@ -18,7 +18,6 @@
package org.rometools.propono.atom.common; package org.rometools.propono.atom.common;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import org.jdom2.Element; import org.jdom2.Element;
@ -33,14 +32,14 @@ public class Collection {
public static final String ENTRY_TYPE = "application/atom+xml;type=entry"; public static final String ENTRY_TYPE = "application/atom+xml;type=entry";
private final List<Categories> categories = new ArrayList<Categories>();
private Element collectionElement = null; private Element collectionElement = null;
private String baseURI = null; private String baseURI = null;
private String title = null; private String title = null;
private String titleType = null; // may be TEXT, HTML, XHTML private String titleType = null; // may be TEXT, HTML, XHTML
private List accepts = new ArrayList(); // of Strings private List<String> accepts = new ArrayList<String>();
private final String listTemplate = null;
private String href = null; private String href = null;
private final List categories = new ArrayList(); // of Categories objects
/** /**
* Collection MUST have title and href. * Collection MUST have title and href.
@ -71,7 +70,7 @@ public class Collection {
/** /**
* List of content-type ranges accepted by collection. * List of content-type ranges accepted by collection.
*/ */
public List getAccepts() { public List<String> getAccepts() {
return accepts; return accepts;
} }
@ -79,7 +78,7 @@ public class Collection {
accepts.add(accept); accepts.add(accept);
} }
public void setAccepts(final List accepts) { public void setAccepts(final List<String> accepts) {
this.accepts = accepts; this.accepts = accepts;
} }
@ -153,7 +152,7 @@ public class Collection {
* *
* @return Collection of {@link com.sun.syndication.propono.atom.common.Categories} objects. * @return Collection of {@link com.sun.syndication.propono.atom.common.Categories} objects.
*/ */
public List getCategories() { public List<Categories> getCategories() {
return categories; return categories;
} }
@ -161,8 +160,8 @@ public class Collection {
* Returns true if contentType is accepted by collection. * Returns true if contentType is accepted by collection.
*/ */
public boolean accepts(final String ct) { public boolean accepts(final String ct) {
for (final Iterator it = accepts.iterator(); it.hasNext();) { for (final Object element : accepts) {
final String accept = (String) it.next(); final String accept = (String) element;
if (accept != null && accept.trim().equals("*/*")) { if (accept != null && accept.trim().equals("*/*")) {
return true; return true;
} }
@ -175,7 +174,7 @@ public class Collection {
} else if (entry && entryType.equals(accept)) { } else if (entry && entryType.equals(accept)) {
return true; return true;
} else { } else {
final String[] rules = (String[]) accepts.toArray(new String[accepts.size()]); final String[] rules = accepts.toArray(new String[accepts.size()]);
for (final String rule2 : rules) { for (final String rule2 : rules) {
String rule = rule2.trim(); String rule = rule2.trim();
if (rule.equals(ct)) { if (rule.equals(ct)) {
@ -210,13 +209,13 @@ public class Collection {
element.addContent(titleElem); element.addContent(titleElem);
// Loop to create <app:categories> elements // Loop to create <app:categories> elements
for (final Iterator it = collection.getCategories().iterator(); it.hasNext();) { for (final Object element2 : collection.getCategories()) {
final Categories cats = (Categories) it.next(); final Categories cats = (Categories) element2;
element.addContent(cats.categoriesToElement()); element.addContent(cats.categoriesToElement());
} }
for (final Iterator it = collection.getAccepts().iterator(); it.hasNext();) { for (final Object element2 : collection.getAccepts()) {
final String range = (String) it.next(); final String range = (String) element2;
final Element acceptElem = new Element("accept", AtomService.ATOM_PROTOCOL); final Element acceptElem = new Element("accept", AtomService.ATOM_PROTOCOL);
acceptElem.setText(range); acceptElem.setText(range);
element.addContent(acceptElem); element.addContent(acceptElem);
@ -241,20 +240,19 @@ public class Collection {
} }
} }
final List acceptElems = element.getChildren("accept", AtomService.ATOM_PROTOCOL); final List<Element> acceptElems = element.getChildren("accept", AtomService.ATOM_PROTOCOL);
if (acceptElems != null && acceptElems.size() > 0) { if (acceptElems != null && acceptElems.size() > 0) {
for (final Iterator it = acceptElems.iterator(); it.hasNext();) { for (final Element acceptElem : acceptElems) {
final Element acceptElem = (Element) it.next();
addAccept(acceptElem.getTextTrim()); addAccept(acceptElem.getTextTrim());
} }
} }
// Loop to parse <app:categories> element to Categories objects // Loop to parse <app:categories> element to Categories objects
final List catsElems = element.getChildren("categories", AtomService.ATOM_PROTOCOL); final List<Element> catsElems = element.getChildren("categories", AtomService.ATOM_PROTOCOL);
for (final Iterator catsIter = catsElems.iterator(); catsIter.hasNext();) { for (final Element catsElem : catsElems) {
final Element catsElem = (Element) catsIter.next();
final Categories cats = new Categories(catsElem, baseURI); final Categories cats = new Categories(catsElem, baseURI);
addCategories(cats); addCategories(cats);
} }
} }
} }

View file

@ -18,7 +18,6 @@
package org.rometools.propono.atom.common; package org.rometools.propono.atom.common;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import org.jdom2.Element; import org.jdom2.Element;
@ -28,9 +27,10 @@ import org.rometools.propono.utils.ProponoException;
* Models an Atom workspace. * Models an Atom workspace.
*/ */
public class Workspace { public class Workspace {
private String title = null; private String title = null;
private String titleType = null; // may be TEXT, HTML, XHTML private String titleType = null; // may be TEXT, HTML, XHTML
private final List collections = new ArrayList(); private final List<Collection> collections = new ArrayList<Collection>();
/** /**
* Collection MUST have title. * Collection MUST have title.
@ -48,7 +48,7 @@ public class Workspace {
} }
/** Iterate over collections in workspace */ /** Iterate over collections in workspace */
public List getCollections() { public List<Collection> getCollections() {
return collections; return collections;
} }
@ -93,8 +93,8 @@ public class Workspace {
* @return First Collection that matches title and/or content-type. * @return First Collection that matches title and/or content-type.
*/ */
public Collection findCollection(final String title, final String contentType) { public Collection findCollection(final String title, final String contentType) {
for (final Iterator it = collections.iterator(); it.hasNext();) { for (final Object element : collections) {
final Collection col = (Collection) it.next(); final Collection col = (Collection) element;
if (title != null && col.accepts(contentType)) { if (title != null && col.accepts(contentType)) {
return col; return col;
} else if (col.accepts(contentType)) { } else if (col.accepts(contentType)) {
@ -124,11 +124,10 @@ public class Workspace {
} }
element.addContent(titleElem); element.addContent(titleElem);
final Iterator iter = space.getCollections().iterator(); for (final Collection col : space.getCollections()) {
while (iter.hasNext()) {
final Collection col = (Collection) iter.next();
element.addContent(col.collectionToElement()); element.addContent(col.collectionToElement());
} }
return element; return element;
} }
@ -139,11 +138,10 @@ public class Workspace {
if (titleElem.getAttribute("type", AtomService.ATOM_FORMAT) != null) { if (titleElem.getAttribute("type", AtomService.ATOM_FORMAT) != null) {
setTitleType(titleElem.getAttribute("type", AtomService.ATOM_FORMAT).getValue()); setTitleType(titleElem.getAttribute("type", AtomService.ATOM_FORMAT).getValue());
} }
final List collections = element.getChildren("collection", AtomService.ATOM_PROTOCOL); final List<Element> collections = element.getChildren("collection", AtomService.ATOM_PROTOCOL);
final Iterator iter = collections.iterator(); for (final Element e : collections) {
while (iter.hasNext()) {
final Element e = (Element) iter.next();
addCollection(new Collection(e)); addCollection(new Collection(e));
} }
} }
} }

View file

@ -36,6 +36,7 @@ import com.sun.syndication.io.ModuleGenerator;
* Creates JDOM representation for APP Extension Module. * Creates JDOM representation for APP Extension Module.
*/ */
public class AppModuleGenerator implements ModuleGenerator { public class AppModuleGenerator implements ModuleGenerator {
private static final Namespace APP_NS = Namespace.getNamespace("app", AppModule.URI); private static final Namespace APP_NS = Namespace.getNamespace("app", AppModule.URI);
@Override @Override
@ -43,17 +44,17 @@ public class AppModuleGenerator implements ModuleGenerator {
return AppModule.URI; return AppModule.URI;
} }
private static final Set NAMESPACES; private static final Set<Namespace> NAMESPACES;
static { static {
final Set nss = new HashSet(); final Set<Namespace> nss = new HashSet<Namespace>();
nss.add(APP_NS); nss.add(APP_NS);
NAMESPACES = Collections.unmodifiableSet(nss); NAMESPACES = Collections.unmodifiableSet(nss);
} }
/** Get namespaces associated with this module */ /** Get namespaces associated with this module */
@Override @Override
public Set getNamespaces() { public Set<Namespace> getNamespaces() {
return NAMESPACES; return NAMESPACES;
} }

View file

@ -29,6 +29,9 @@ import com.sun.syndication.feed.module.ModuleImpl;
* Bean representation of APP module. * Bean representation of APP module.
*/ */
public class AppModuleImpl extends ModuleImpl implements AppModule { public class AppModuleImpl extends ModuleImpl implements AppModule {
private static final long serialVersionUID = 1L;
private boolean draft = false; private boolean draft = false;
private Date edited = null; private Date edited = null;
@ -62,7 +65,7 @@ public class AppModuleImpl extends ModuleImpl implements AppModule {
/** Get interface class of module */ /** Get interface class of module */
@Override @Override
public Class getInterface() { public Class<AppModule> getInterface() {
return AppModule.class; return AppModule.class;
} }
@ -73,4 +76,5 @@ public class AppModuleImpl extends ModuleImpl implements AppModule {
setDraft(m.getDraft()); setDraft(m.getDraft());
setEdited(m.getEdited()); setEdited(m.getEdited());
} }
} }

View file

@ -22,9 +22,13 @@ package org.rometools.propono.atom.server;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
/** /**
* Exception thrown by {@link com.sun.syndication.propono.atom.server.AtomHandler} and extended by other Propono Atom exception classes. * Exception thrown by {@link com.sun.syndication.propono.atom.server.AtomHandler} and extended by
* other Propono Atom exception classes.
*/ */
public class AtomException extends Exception { public class AtomException extends Exception {
private static final long serialVersionUID = 1L;
/** Construct new exception */ /** Construct new exception */
public AtomException() { public AtomException() {
super(); super();

View file

@ -73,7 +73,7 @@ public abstract class AtomHandlerFactory {
public static AtomHandlerFactory newInstance() { public static AtomHandlerFactory newInstance() {
try { try {
return (AtomHandlerFactory) FactoryFinder.find(DEFAULT_PROPERTY_NAME, FALLBACK_IMPL_NAME); return (AtomHandlerFactory) FactoryFinder.find(DEFAULT_PROPERTY_NAME, FALLBACK_IMPL_NAME);
} catch (final FactoryFinder.ConfigurationError e) { } catch (final ConfigurationError e) {
log.error("ERROR: finding factory", e); log.error("ERROR: finding factory", e);
throw new FactoryConfigurationError(e.getException(), e.getMessage()); throw new FactoryConfigurationError(e.getException(), e.getMessage());
} }

View file

@ -22,9 +22,13 @@ package org.rometools.propono.atom.server;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
/** /**
* Exception to be thrown by <code>AtomHandler</code> implementations in the case that a user is not authorized to access a resource. * Exception to be thrown by <code>AtomHandler</code> implementations in the case that a user is not
* authorized to access a resource.
*/ */
public class AtomNotAuthorizedException extends AtomException { public class AtomNotAuthorizedException extends AtomException {
private static final long serialVersionUID = 1L;
/** Construct new exception */ /** Construct new exception */
public AtomNotAuthorizedException() { public AtomNotAuthorizedException() {
super(); super();
@ -50,4 +54,5 @@ public class AtomNotAuthorizedException extends AtomException {
public int getStatus() { public int getStatus() {
return HttpServletResponse.SC_UNAUTHORIZED; return HttpServletResponse.SC_UNAUTHORIZED;
} }
} }

View file

@ -25,6 +25,9 @@ import javax.servlet.http.HttpServletResponse;
* Exception thrown by AtomHandler in that case a resource is not found. * Exception thrown by AtomHandler in that case a resource is not found.
*/ */
public class AtomNotFoundException extends AtomException { public class AtomNotFoundException extends AtomException {
private static final long serialVersionUID = 1L;
/** Construct new exception */ /** Construct new exception */
public AtomNotFoundException() { public AtomNotFoundException() {
super(); super();

View file

@ -31,6 +31,7 @@ import javax.servlet.http.HttpServletRequest;
* Default request implementation. * Default request implementation.
*/ */
public class AtomRequestImpl implements AtomRequest { public class AtomRequestImpl implements AtomRequest {
private HttpServletRequest wrapped = null; private HttpServletRequest wrapped = null;
public AtomRequestImpl(final HttpServletRequest wrapped) { public AtomRequestImpl(final HttpServletRequest wrapped) {

View file

@ -50,12 +50,16 @@ import com.sun.syndication.io.impl.Atom10Generator;
import com.sun.syndication.io.impl.Atom10Parser; import com.sun.syndication.io.impl.Atom10Parser;
/** /**
* Atom Servlet implements Atom protocol by calling an {@link com.sun.syndication.propono.atom.server.AtomHandler} implementation. This servlet takes care of * Atom Servlet implements Atom protocol by calling an
* parsing incoming XML into ROME Atom {@link com.sun.syndication.feed.atom.Entry} objects, passing those to the handler and serializing to the response the * {@link com.sun.syndication.propono.atom.server.AtomHandler} implementation. This servlet takes
* entries and feeds returned by the handler. * care of parsing incoming XML into ROME Atom {@link com.sun.syndication.feed.atom.Entry} objects,
* passing those to the handler and serializing to the response the entries and feeds returned by
* the handler.
*/ */
public class AtomServlet extends HttpServlet { public class AtomServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/** /**
* Get feed type support by Servlet, "atom_1.0" * Get feed type support by Servlet, "atom_1.0"
*/ */
@ -160,7 +164,8 @@ public class AtomServlet extends HttpServlet {
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
/** /**
* Handles an Atom POST by calling handler to identify URI, reading/parsing data, calling handler and writing results to response. * Handles an Atom POST by calling handler to identify URI, reading/parsing data, calling
* handler and writing results to response.
*/ */
@Override @Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { protected void doPost(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException {
@ -265,7 +270,8 @@ public class AtomServlet extends HttpServlet {
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
/** /**
* Handles an Atom PUT by calling handler to identify URI, reading/parsing data, calling handler and writing results to response. * Handles an Atom PUT by calling handler to identify URI, reading/parsing data, calling handler
* and writing results to response.
*/ */
@Override @Override
protected void doPut(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { protected void doPut(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException {
@ -278,7 +284,8 @@ public class AtomServlet extends HttpServlet {
if (handler.isEntryURI(areq)) { if (handler.isEntryURI(areq)) {
// parse incoming entry // parse incoming entry
final Entry unsavedEntry = Atom10Parser.parseEntry(new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8")), null, Locale.US); final Entry unsavedEntry = Atom10Parser.parseEntry(new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8")), null,
Locale.US);
// call handler to put entry // call handler to put entry
handler.putEntry(areq, unsavedEntry); handler.putEntry(areq, unsavedEntry);

View file

@ -0,0 +1,21 @@
package org.rometools.propono.atom.server;
class ConfigurationError extends Error {
private static final long serialVersionUID = 1L;
private final Exception exception;
/**
* Construct a new instance with the specified detail string and exception.
*/
ConfigurationError(final String msg, final Exception x) {
super(msg);
exception = x;
}
Exception getException() {
return exception;
}
}

View file

@ -16,11 +16,15 @@
package org.rometools.propono.atom.server; package org.rometools.propono.atom.server;
/** /**
* Thrown when a problem with configuration with the {@link com.sun.syndication.propono.atom.server.AtomHandlerFactory} exists. This error will typically be * Thrown when a problem with configuration with the
* thrown when the class of a parser factory specified in the system properties cannot be found or instantiated. * {@link com.sun.syndication.propono.atom.server.AtomHandlerFactory} exists. This error will
* typically be thrown when the class of a parser factory specified in the system properties cannot
* be found or instantiated.
*/ */
public class FactoryConfigurationError extends Error { public class FactoryConfigurationError extends Error {
private static final long serialVersionUID = 1L;
/** /**
* <code>Exception</code> that represents the error. * <code>Exception</code> that represents the error.
*/ */
@ -35,7 +39,8 @@ public class FactoryConfigurationError extends Error {
} }
/** /**
* Create a new <code>FactoryConfigurationError</code> with the <code>String </code> specified as an error message. * Create a new <code>FactoryConfigurationError</code> with the <code>String </code> specified
* as an error message.
* *
* @param msg The error message for the exception. * @param msg The error message for the exception.
*/ */
@ -45,7 +50,8 @@ public class FactoryConfigurationError extends Error {
} }
/** /**
* Create a new <code>FactoryConfigurationError</code> with a given <code>Exception</code> base cause of the error. * Create a new <code>FactoryConfigurationError</code> with a given <code>Exception</code> base
* cause of the error.
* *
* @param e The exception to be encapsulated in a FactoryConfigurationError. * @param e The exception to be encapsulated in a FactoryConfigurationError.
*/ */
@ -55,7 +61,8 @@ public class FactoryConfigurationError extends Error {
} }
/** /**
* Create a new <code>FactoryConfigurationError</code> with the given <code>Exception</code> base cause and detail message. * Create a new <code>FactoryConfigurationError</code> with the given <code>Exception</code>
* base cause and detail message.
* *
* @param e The exception to be encapsulated in a FactoryConfigurationError * @param e The exception to be encapsulated in a FactoryConfigurationError
* @param msg The detail message. * @param msg The detail message.
@ -66,8 +73,9 @@ public class FactoryConfigurationError extends Error {
} }
/** /**
* Return the message (if any) for this error . If there is no message for the exception and there is an encapsulated exception then the message of that * Return the message (if any) for this error . If there is no message for the exception and
* exception, if it exists will be returned. Else the name of the encapsulated exception will be returned. * there is an encapsulated exception then the message of that exception, if it exists will be
* returned. Else the name of the encapsulated exception will be returned.
* *
* @return The error message. * @return The error message.
*/ */

View file

@ -22,13 +22,15 @@ import java.io.InputStreamReader;
import java.util.Properties; import java.util.Properties;
/** /**
* Find {@link com.sun.syndication.propono.atom.server.AtomHandlerFactory} based on properties files. * Find {@link com.sun.syndication.propono.atom.server.AtomHandlerFactory} based on properties
* files.
*/ */
class FactoryFinder { class FactoryFinder {
private static boolean debug = false; private static boolean debug = false;
static Properties cacheProps = new Properties(); private static Properties cacheProps = new Properties();
static SecuritySupport ss = new SecuritySupport(); private static SecuritySupport ss = new SecuritySupport();
static boolean firstTime = true; private static boolean firstTime = true;
private static void dPrint(final String msg) { private static void dPrint(final String msg) {
if (debug) { if (debug) {
@ -37,18 +39,20 @@ class FactoryFinder {
} }
/** /**
* Create an instance of a class using the specified ClassLoader and optionally fall back to the current ClassLoader if not found. * Create an instance of a class using the specified ClassLoader and optionally fall back to the
* current ClassLoader if not found.
* *
* @param className Name of the concrete class corresponding to the service provider * @param className Name of the concrete class corresponding to the service provider
* *
* @param cl ClassLoader to use to load the class, null means to use the bootstrap ClassLoader * @param cl ClassLoader to use to load the class, null means to use the bootstrap ClassLoader
* *
* @param doFallback true if the current ClassLoader should be tried as a fallback if the class is not found using cl * @param doFallback true if the current ClassLoader should be tried as a fallback if the class
* is not found using cl
*/ */
private static Object newInstance(final String className, ClassLoader cl, final boolean doFallback) throws ConfigurationError { private static Object newInstance(final String className, ClassLoader cl, final boolean doFallback) throws ConfigurationError {
try { try {
Class providerClass; Class<?> providerClass;
if (cl == null) { if (cl == null) {
// If classloader is null Use the bootstrap ClassLoader. // If classloader is null Use the bootstrap ClassLoader.
// Thus Class.forName(String) will use the current // Thus Class.forName(String) will use the current
@ -84,7 +88,8 @@ class FactoryFinder {
* @return Class object of factory, never null * @return Class object of factory, never null
* *
* @param factoryId Name of the factory to find, same as a property name * @param factoryId Name of the factory to find, same as a property name
* @param fallbackClassName Implementation class name, if nothing else is found. Use null to mean no fallback. * @param fallbackClassName Implementation class name, if nothing else is found. Use null to
* mean no fallback.
* *
* Package private so this code can be shared. * Package private so this code can be shared.
*/ */
@ -117,7 +122,6 @@ class FactoryFinder {
// try to read from /propono.properties // try to read from /propono.properties
try { try {
final String javah = ss.getSystemProperty("java.home");
final String configFile = "/propono.properties"; final String configFile = "/propono.properties";
String factoryClassName = null; String factoryClassName = null;
if (firstTime) { if (firstTime) {
@ -162,7 +166,6 @@ class FactoryFinder {
/* /*
* Try to find provider using Jar Service Provider Mechanism * Try to find provider using Jar Service Provider Mechanism
*
* @return instance of provider class if found or null * @return instance of provider class if found or null
*/ */
private static Object findJarServiceProvider(final String factoryId) throws ConfigurationError { private static Object findJarServiceProvider(final String factoryId) throws ConfigurationError {
@ -242,20 +245,4 @@ class FactoryFinder {
return null; return null;
} }
static class ConfigurationError extends Error {
private final Exception exception;
/**
* Construct a new instance with the specified detail string and exception.
*/
ConfigurationError(final String msg, final Exception x) {
super(msg);
exception = x;
}
Exception getException() {
return exception;
}
}
} }

View file

@ -25,14 +25,15 @@ import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction; import java.security.PrivilegedExceptionAction;
/** /**
* This class is duplicated for each subpackage, it is package private and therefore is not exposed as part of the public API. * This class is duplicated for each subpackage, it is package private and therefore is not exposed
* as part of the public API.
*/ */
class SecuritySupport { class SecuritySupport {
ClassLoader getContextClassLoader() { ClassLoader getContextClassLoader() {
return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() { final PrivilegedAction<ClassLoader> action = new PrivilegedAction<ClassLoader>() {
@Override @Override
public Object run() { public ClassLoader run() {
ClassLoader cl = null; ClassLoader cl = null;
try { try {
cl = Thread.currentThread().getContextClassLoader(); cl = Thread.currentThread().getContextClassLoader();
@ -40,35 +41,38 @@ class SecuritySupport {
} }
return cl; return cl;
} }
}); };
return AccessController.doPrivileged(action);
} }
String getSystemProperty(final String propName) { String getSystemProperty(final String propName) {
return (String) AccessController.doPrivileged(new PrivilegedAction() { final PrivilegedAction<String> action = new PrivilegedAction<String>() {
@Override @Override
public Object run() { public String run() {
return System.getProperty(propName); return System.getProperty(propName);
} }
}); };
return AccessController.doPrivileged(action);
} }
FileInputStream getFileInputStream(final File file) throws FileNotFoundException { FileInputStream getFileInputStream(final File file) throws FileNotFoundException {
try { try {
return (FileInputStream) AccessController.doPrivileged(new PrivilegedExceptionAction() { final PrivilegedExceptionAction<FileInputStream> action = new PrivilegedExceptionAction<FileInputStream>() {
@Override @Override
public Object run() throws FileNotFoundException { public FileInputStream run() throws FileNotFoundException {
return new FileInputStream(file); return new FileInputStream(file);
} }
}); };
return AccessController.doPrivileged(action);
} catch (final PrivilegedActionException e) { } catch (final PrivilegedActionException e) {
throw (FileNotFoundException) e.getException(); throw (FileNotFoundException) e.getException();
} }
} }
InputStream getResourceAsStream(final ClassLoader cl, final String name) { InputStream getResourceAsStream(final ClassLoader cl, final String name) {
return (InputStream) AccessController.doPrivileged(new PrivilegedAction() { final PrivilegedAction<InputStream> action = new PrivilegedAction<InputStream>() {
@Override @Override
public Object run() { public InputStream run() {
InputStream ris; InputStream ris;
if (cl == null) { if (cl == null) {
ris = ClassLoader.getSystemResourceAsStream(name); ris = ClassLoader.getSystemResourceAsStream(name);
@ -77,16 +81,18 @@ class SecuritySupport {
} }
return ris; return ris;
} }
}); };
return AccessController.doPrivileged(action);
} }
boolean doesFileExist(final File f) { boolean doesFileExist(final File f) {
return ((Boolean) AccessController.doPrivileged(new PrivilegedAction() { final PrivilegedAction<Boolean> action = new PrivilegedAction<Boolean>() {
@Override @Override
public Object run() { public Boolean run() {
return new Boolean(f.exists()); return f.exists();
} }
})).booleanValue(); };
return AccessController.doPrivileged(action).booleanValue();
} }
} }

View file

@ -36,22 +36,17 @@ import com.sun.syndication.feed.atom.Entry;
import com.sun.syndication.feed.atom.Feed; import com.sun.syndication.feed.atom.Feed;
/** /**
* File-based {@link com.sun.syndication.propono.atom.server.AtomHandler} * File-based {@link com.sun.syndication.propono.atom.server.AtomHandler} implementation that stores
* implementation that stores entries and media-entries to disk. Implemented * entries and media-entries to disk. Implemented using
* using
* {@link com.sun.syndication.propono.atom.server.impl.FileBasedAtomService}. * {@link com.sun.syndication.propono.atom.server.impl.FileBasedAtomService}.
*/ */
public class FileBasedAtomHandler implements AtomHandler { public class FileBasedAtomHandler implements AtomHandler {
private static Log log = LogFactory.getFactory().getInstance(FileBasedAtomHandler.class); private static final Log LOGGER = LogFactory.getFactory().getInstance(FileBasedAtomHandler.class);
private static String fileStoreDir = null;
private String userName = null; private String userName = null;
private String atomProtocolURL = null; private String atomProtocolURL = null;
private String contextURI = null; private String contextURI = null;
private final String uploadurl = null;
private FileBasedAtomService service = null; private FileBasedAtomService service = null;
/** /**
@ -70,7 +65,7 @@ public class FileBasedAtomHandler implements AtomHandler {
* @param uploaddir File storage upload dir. * @param uploaddir File storage upload dir.
*/ */
public FileBasedAtomHandler(final HttpServletRequest req, final String uploaddir) { public FileBasedAtomHandler(final HttpServletRequest req, final String uploaddir) {
log.debug("ctor"); LOGGER.debug("ctor");
userName = authenticateBASIC(req); userName = authenticateBASIC(req);
@ -86,9 +81,8 @@ public class FileBasedAtomHandler implements AtomHandler {
} }
/** /**
* Method used for validating user. Developers can overwrite this method and * Method used for validating user. Developers can overwrite this method and use credentials
* use credentials stored in Database or LDAP to confirm if the user is * stored in Database or LDAP to confirm if the user is allowed to access this service.
* allowed to access this service.
* *
* @param login user submitted login id * @param login user submitted login id
* @param password user submitted password * @param password user submitted password
@ -124,8 +118,7 @@ public class FileBasedAtomHandler implements AtomHandler {
/** /**
* Return introspection document * Return introspection document
* *
* @throws com.sun.syndication.propono.atom.server.AtomException Unexpected * @throws com.sun.syndication.propono.atom.server.AtomException Unexpected exception.
* exception.
* @return AtomService object with workspaces and collections. * @return AtomService object with workspaces and collections.
*/ */
@Override @Override
@ -136,13 +129,12 @@ public class FileBasedAtomHandler implements AtomHandler {
/** /**
* Returns null because we use in-line categories. * Returns null because we use in-line categories.
* *
* @throws com.sun.syndication.propono.atom.server.AtomException Unexpected * @throws com.sun.syndication.propono.atom.server.AtomException Unexpected exception.
* exception.
* @return Categories object * @return Categories object
*/ */
@Override @Override
public Categories getCategories(final AtomRequest areq) throws AtomException { public Categories getCategories(final AtomRequest areq) throws AtomException {
log.debug("getCollection"); LOGGER.debug("getCollection");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
final String handle = pathInfo[0]; final String handle = pathInfo[0];
final String collection = pathInfo[1]; final String collection = pathInfo[1];
@ -155,12 +147,12 @@ public class FileBasedAtomHandler implements AtomHandler {
* *
* @param areq Details of HTTP request * @param areq Details of HTTP request
* @return ROME feed representing collection. * @return ROME feed representing collection.
* @throws com.sun.syndication.propono.atom.server.AtomException Invalid * @throws com.sun.syndication.propono.atom.server.AtomException Invalid collection or other
* collection or other exception. * exception.
*/ */
@Override @Override
public Feed getCollection(final AtomRequest areq) throws AtomException { public Feed getCollection(final AtomRequest areq) throws AtomException {
log.debug("getCollection"); LOGGER.debug("getCollection");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
final String handle = pathInfo[0]; final String handle = pathInfo[0];
final String collection = pathInfo[1]; final String collection = pathInfo[1];
@ -169,19 +161,18 @@ public class FileBasedAtomHandler implements AtomHandler {
} }
/** /**
* Create a new entry specified by pathInfo and posted entry. We save the * Create a new entry specified by pathInfo and posted entry. We save the submitted Atom entry
* submitted Atom entry verbatim, but we do set the id and reset the update * verbatim, but we do set the id and reset the update time.
* time.
* *
* @param entry Entry to be added to collection. * @param entry Entry to be added to collection.
* @param areq Details of HTTP request * @param areq Details of HTTP request
* @throws com.sun.syndication.propono.atom.server.AtomException On invalid * @throws com.sun.syndication.propono.atom.server.AtomException On invalid collection or other
* collection or other error. * error.
* @return Entry as represented on server. * @return Entry as represented on server.
*/ */
@Override @Override
public Entry postEntry(final AtomRequest areq, final Entry entry) throws AtomException { public Entry postEntry(final AtomRequest areq, final Entry entry) throws AtomException {
log.debug("postEntry"); LOGGER.debug("postEntry");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
final String handle = pathInfo[0]; final String handle = pathInfo[0];
@ -200,13 +191,13 @@ public class FileBasedAtomHandler implements AtomHandler {
* Get entry specified by pathInfo. * Get entry specified by pathInfo.
* *
* @param areq Details of HTTP request * @param areq Details of HTTP request
* @throws com.sun.syndication.propono.atom.server.AtomException On invalid * @throws com.sun.syndication.propono.atom.server.AtomException On invalid pathinfo or other
* pathinfo or other error. * error.
* @return ROME Entry object. * @return ROME Entry object.
*/ */
@Override @Override
public Entry getEntry(final AtomRequest areq) throws AtomException { public Entry getEntry(final AtomRequest areq) throws AtomException {
log.debug("getEntry"); LOGGER.debug("getEntry");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
final String handle = pathInfo[0]; final String handle = pathInfo[0];
final String collection = pathInfo[1]; final String collection = pathInfo[1];
@ -232,7 +223,7 @@ public class FileBasedAtomHandler implements AtomHandler {
*/ */
@Override @Override
public void putEntry(final AtomRequest areq, final Entry entry) throws AtomException { public void putEntry(final AtomRequest areq, final Entry entry) throws AtomException {
log.debug("putEntry"); LOGGER.debug("putEntry");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
final String handle = pathInfo[0]; final String handle = pathInfo[0];
final String collection = pathInfo[1]; final String collection = pathInfo[1];
@ -253,7 +244,7 @@ public class FileBasedAtomHandler implements AtomHandler {
*/ */
@Override @Override
public void deleteEntry(final AtomRequest areq) throws AtomException { public void deleteEntry(final AtomRequest areq) throws AtomException {
log.debug("deleteEntry"); LOGGER.debug("deleteEntry");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
final String handle = pathInfo[0]; final String handle = pathInfo[0];
final String collection = pathInfo[1]; final String collection = pathInfo[1];
@ -264,15 +255,14 @@ public class FileBasedAtomHandler implements AtomHandler {
} catch (final Exception e) { } catch (final Exception e) {
final String msg = "ERROR in atom.deleteResource"; final String msg = "ERROR in atom.deleteResource";
log.error(msg, e); LOGGER.error(msg, e);
throw new AtomException(msg); throw new AtomException(msg);
} }
} }
/** /**
* Store media data in collection specified by pathInfo, create an Atom * Store media data in collection specified by pathInfo, create an Atom media-link entry to
* media-link entry to store metadata for the new media file and return that * store metadata for the new media file and return that entry to the caller.
* entry to the caller.
* *
* @param areq Details of HTTP request * @param areq Details of HTTP request
* @param entry New entry initialzied with only title and content type * @param entry New entry initialzied with only title and content type
@ -284,8 +274,8 @@ public class FileBasedAtomHandler implements AtomHandler {
// get incoming slug from HTTP header // get incoming slug from HTTP header
final String slug = areq.getHeader("Slug"); final String slug = areq.getHeader("Slug");
if (log.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
log.debug("postMedia - title: " + entry.getTitle() + " slug:" + slug); LOGGER.debug("postMedia - title: " + entry.getTitle() + " slug:" + slug);
} }
try { try {
@ -300,7 +290,7 @@ public class FileBasedAtomHandler implements AtomHandler {
} catch (final Exception e) { } catch (final Exception e) {
e.printStackTrace(); e.printStackTrace();
final String msg = "ERROR reading posted file"; final String msg = "ERROR reading posted file";
log.error(msg, e); LOGGER.error(msg, e);
throw new AtomException(msg, e); throw new AtomException(msg, e);
} finally { } finally {
if (tempFile != null) { if (tempFile != null) {
@ -317,13 +307,12 @@ public class FileBasedAtomHandler implements AtomHandler {
/** /**
* Update the media file part of a media-link entry. * Update the media file part of a media-link entry.
* *
* @param areq Details of HTTP request Assuming pathInfo of form * @param areq Details of HTTP request Assuming pathInfo of form /user-name/resource/name
* /user-name/resource/name
*/ */
@Override @Override
public void putMedia(final AtomRequest areq) throws AtomException { public void putMedia(final AtomRequest areq) throws AtomException {
log.debug("putMedia"); LOGGER.debug("putMedia");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
final String handle = pathInfo[0]; final String handle = pathInfo[0];
final String collection = pathInfo[1]; final String collection = pathInfo[1];
@ -339,7 +328,7 @@ public class FileBasedAtomHandler implements AtomHandler {
@Override @Override
public AtomMediaResource getMediaResource(final AtomRequest areq) throws AtomException { public AtomMediaResource getMediaResource(final AtomRequest areq) throws AtomException {
log.debug("putMedia"); LOGGER.debug("putMedia");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
final String handle = pathInfo[0]; final String handle = pathInfo[0];
final String collection = pathInfo[1]; final String collection = pathInfo[1];
@ -370,7 +359,7 @@ public class FileBasedAtomHandler implements AtomHandler {
*/ */
@Override @Override
public boolean isCategoriesURI(final AtomRequest areq) { public boolean isCategoriesURI(final AtomRequest areq) {
log.debug("isCategoriesDocumentURI"); LOGGER.debug("isCategoriesDocumentURI");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
if (pathInfo.length == 3 && "categories".equals(pathInfo[2])) { if (pathInfo.length == 3 && "categories".equals(pathInfo[2])) {
return true; return true;
@ -383,7 +372,7 @@ public class FileBasedAtomHandler implements AtomHandler {
*/ */
@Override @Override
public boolean isCollectionURI(final AtomRequest areq) { public boolean isCollectionURI(final AtomRequest areq) {
log.debug("isCollectionURI"); LOGGER.debug("isCollectionURI");
// workspace/collection-plural // workspace/collection-plural
// if length is 2 and points to a valid collection then YES // if length is 2 and points to a valid collection then YES
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
@ -403,7 +392,7 @@ public class FileBasedAtomHandler implements AtomHandler {
*/ */
@Override @Override
public boolean isEntryURI(final AtomRequest areq) { public boolean isEntryURI(final AtomRequest areq) {
log.debug("isEntryURI"); LOGGER.debug("isEntryURI");
// workspace/collection-singular/fsid // workspace/collection-singular/fsid
// if length is 3 and points to a valid collection then YES // if length is 3 and points to a valid collection then YES
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/"); final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
@ -422,7 +411,7 @@ public class FileBasedAtomHandler implements AtomHandler {
*/ */
@Override @Override
public boolean isMediaEditURI(final AtomRequest areq) { public boolean isMediaEditURI(final AtomRequest areq) {
log.debug("isMediaEditURI"); LOGGER.debug("isMediaEditURI");
// workspace/collection-singular/fsid/media/fsid // workspace/collection-singular/fsid/media/fsid
// if length is 4, points to a valid collection and fsid is mentioned // if length is 4, points to a valid collection and fsid is mentioned
// twice then YES // twice then YES
@ -444,7 +433,7 @@ public class FileBasedAtomHandler implements AtomHandler {
* BASIC authentication. * BASIC authentication.
*/ */
public String authenticateBASIC(final HttpServletRequest request) { public String authenticateBASIC(final HttpServletRequest request) {
log.debug("authenticateBASIC"); LOGGER.debug("authenticateBASIC");
boolean valid = false; boolean valid = false;
String userID = null; String userID = null;
String password = null; String password = null;
@ -469,7 +458,7 @@ public class FileBasedAtomHandler implements AtomHandler {
} }
} }
} catch (final Exception e) { } catch (final Exception e) {
log.debug(e); LOGGER.debug(e);
} }
if (valid) { if (valid) {
// For now assume userID as userName // For now assume userID as userName

View file

@ -34,4 +34,5 @@ public class FileBasedAtomHandlerFactory extends AtomHandlerFactory {
public AtomHandler newAtomHandler(final HttpServletRequest req, final HttpServletResponse res) { public AtomHandler newAtomHandler(final HttpServletRequest req, final HttpServletResponse res) {
return new FileBasedAtomHandler(req); return new FileBasedAtomHandler(req);
} }
} }

View file

@ -24,7 +24,8 @@ import org.rometools.propono.atom.common.AtomService;
import org.rometools.propono.utils.Utilities; import org.rometools.propono.utils.Utilities;
/** /**
* File based Atom service. Supports one workspace per user. Collections in workspace are defined in /propono.properties, for example: * File based Atom service. Supports one workspace per user. Collections in workspace are defined in
* /propono.properties, for example:
* *
* <pre> * <pre>
* # Define list of collections to be offered * # Define list of collections to be offered
@ -45,7 +46,8 @@ import org.rometools.propono.utils.Utilities;
* propono.atomserver.filebased.collection.gifimages.categories=general,category1,category2 * propono.atomserver.filebased.collection.gifimages.categories=general,category1,category2
* </pre> * </pre>
* *
* If no such properties are found, then service will fall back to two collections: 'entries' for Atom entries and 'resources' for any content-type. * If no such properties are found, then service will fall back to two collections: 'entries' for
* Atom entries and 'resources' for any content-type.
* *
* *
* <p> * <p>
@ -93,8 +95,9 @@ import org.rometools.propono.utils.Utilities;
* </p> * </p>
*/ */
public class FileBasedAtomService extends AtomService { public class FileBasedAtomService extends AtomService {
private final Map workspaceMap = new TreeMap();
private final Map collectionMap = new TreeMap(); private final Map<String, FileBasedWorkspace> workspaceMap = new TreeMap<String, FileBasedWorkspace>();
private final Map<String, FileBasedCollection> collectionMap = new TreeMap<String, FileBasedCollection>();
private static Properties cacheProps = new Properties(); private static Properties cacheProps = new Properties();
private boolean firstTime = true; private boolean firstTime = true;
@ -181,10 +184,10 @@ public class FileBasedAtomService extends AtomService {
* Find workspace by handle, returns null of not found. * Find workspace by handle, returns null of not found.
*/ */
FileBasedWorkspace findWorkspaceByHandle(final String handle) { FileBasedWorkspace findWorkspaceByHandle(final String handle) {
return (FileBasedWorkspace) workspaceMap.get(handle); return workspaceMap.get(handle);
} }
FileBasedCollection findCollectionByHandle(final String handle, final String collection) { FileBasedCollection findCollectionByHandle(final String handle, final String collection) {
return (FileBasedCollection) collectionMap.get(handle + "|" + collection); return collectionMap.get(handle + "|" + collection);
} }
} }

View file

@ -28,7 +28,6 @@ import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.StringTokenizer; import java.util.StringTokenizer;
@ -36,8 +35,6 @@ import java.util.StringTokenizer;
import javax.activation.FileTypeMap; import javax.activation.FileTypeMap;
import javax.activation.MimetypesFileTypeMap; import javax.activation.MimetypesFileTypeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom2.Document; import org.jdom2.Document;
import org.jdom2.output.XMLOutputter; import org.jdom2.output.XMLOutputter;
import org.rometools.propono.atom.common.Categories; import org.rometools.propono.atom.common.Categories;
@ -55,6 +52,7 @@ import com.sun.syndication.feed.atom.Content;
import com.sun.syndication.feed.atom.Entry; import com.sun.syndication.feed.atom.Entry;
import com.sun.syndication.feed.atom.Feed; import com.sun.syndication.feed.atom.Feed;
import com.sun.syndication.feed.atom.Link; import com.sun.syndication.feed.atom.Link;
import com.sun.syndication.feed.module.Module;
import com.sun.syndication.io.FeedException; import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.WireFeedInput; import com.sun.syndication.io.WireFeedInput;
import com.sun.syndication.io.WireFeedOutput; import com.sun.syndication.io.WireFeedOutput;
@ -62,11 +60,11 @@ import com.sun.syndication.io.impl.Atom10Generator;
import com.sun.syndication.io.impl.Atom10Parser; import com.sun.syndication.io.impl.Atom10Parser;
/** /**
* File based Atom collection implementation. This is the heart of the file-based Atom service implementation. It provides methods for adding, getting updating * File based Atom collection implementation. This is the heart of the file-based Atom service
* and deleting Atom entries and media entries. * implementation. It provides methods for adding, getting updating and deleting Atom entries and
* media entries.
*/ */
public class FileBasedCollection extends Collection { public class FileBasedCollection extends Collection {
private static Log log = LogFactory.getFactory().getInstance(FileBasedCollection.class);
private String handle = null; private String handle = null;
private String singular = null; private String singular = null;
@ -77,15 +75,16 @@ public class FileBasedCollection extends Collection {
private boolean relativeURIs = false; private boolean relativeURIs = false;
private String contextURI = null; private String contextURI = null;
private String contextPath = null;
private String servletPath = null; private String servletPath = null;
private String baseDir = null; private String baseDir = null;
private static final String FEED_TYPE = "atom_1.0"; private static final String FEED_TYPE = "atom_1.0";
/** /**
* Construct by providing title (plain text, no HTML), a workspace handle, a plural collection name (e.g. entries), a singular collection name (e.g. entry), * Construct by providing title (plain text, no HTML), a workspace handle, a plural collection
* the base directory for file storage, the content-type range accepted by the collection and the root Atom protocol URI for the service. * name (e.g. entries), a singular collection name (e.g. entry), the base directory for file
* storage, the content-type range accepted by the collection and the root Atom protocol URI for
* the service.
* *
* @param title Title of collection (plain text, no HTML) * @param title Title of collection (plain text, no HTML)
* @param handle Workspace handle * @param handle Workspace handle
@ -114,7 +113,6 @@ public class FileBasedCollection extends Collection {
this.baseDir = baseDir; this.baseDir = baseDir;
this.relativeURIs = relativeURIs; this.relativeURIs = relativeURIs;
this.contextURI = contextURI; this.contextURI = contextURI;
this.contextPath = contextPath;
this.servletPath = servletPath; this.servletPath = servletPath;
addAccept(accept); addAccept(accept);
@ -146,10 +144,10 @@ public class FileBasedCollection extends Collection {
/** /**
* Get list of one Categories object containing categories allowed by collection. * Get list of one Categories object containing categories allowed by collection.
* *
* @param inline True if Categories object should contain collection of in-line Categories objects or false if it should set the Href for out-of-line * @param inline True if Categories object should contain collection of in-line Categories
* categories. * objects or false if it should set the Href for out-of-line categories.
*/ */
public List getCategories(final boolean inline) { public List<Categories> getCategories(final boolean inline) {
final Categories cats = new Categories(); final Categories cats = new Categories();
cats.setFixed(true); cats.setFixed(true);
cats.setScheme(contextURI + "/" + handle + "/" + singular); cats.setScheme(contextURI + "/" + handle + "/" + singular);
@ -166,18 +164,21 @@ public class FileBasedCollection extends Collection {
} }
/** /**
* Get list of one Categories object containing categories allowed by collection, returns in-line categories if collection set to use in-line categories. * Get list of one Categories object containing categories allowed by collection, returns
* in-line categories if collection set to use in-line categories.
*/ */
@Override @Override
public List getCategories() { public List<Categories> getCategories() {
return getCategories(inlineCats); return getCategories(inlineCats);
} }
/** /**
* Add entry to collection. * Add entry to collection.
* *
* @param entry Entry to be added to collection. Entry will be saved to disk in a directory under the collection's directory and the path will follow the * @param entry Entry to be added to collection. Entry will be saved to disk in a directory
* pattern [collection-plural]/[entryid]/entry.xml. The entry will be added to the collection's feed in [collection-plural]/feed.xml. * under the collection's directory and the path will follow the pattern
* [collection-plural]/[entryid]/entry.xml. The entry will be added to the
* collection's feed in [collection-plural]/feed.xml.
* @throws java.lang.Exception On error. * @throws java.lang.Exception On error.
* @return Entry as it exists on the server. * @return Entry as it exists on the server.
*/ */
@ -206,10 +207,12 @@ public class FileBasedCollection extends Collection {
} }
/** /**
* Add media entry to collection. Accepts a media file to be added to collection. The file will be saved to disk in a directory under the collection's * Add media entry to collection. Accepts a media file to be added to collection. The file will
* directory and the path will follow the pattern <code>[collection-plural]/[entryid]/media/[entryid]</code>. An Atom entry will be created to store * be saved to disk in a directory under the collection's directory and the path will follow the
* metadata for the entry and it will exist at the path <code>[collection-plural]/[entryid]/entry.xml</code>. The entry will be added to the collection's * pattern <code>[collection-plural]/[entryid]/media/[entryid]</code>. An Atom entry will be
* feed in [collection-plural]/feed.xml. * created to store metadata for the entry and it will exist at the path
* <code>[collection-plural]/[entryid]/entry.xml</code>. The entry will be added to the
* collection's feed in [collection-plural]/feed.xml.
* *
* @param entry Entry object * @param entry Entry object
* @param slug String to be used in file-name * @param slug String to be used in file-name
@ -275,7 +278,6 @@ public class FileBasedCollection extends Collection {
final InputStream in = FileStore.getFileStore().getFileInputStream(entryPath); final InputStream in = FileStore.getFileStore().getFileInputStream(entryPath);
final Entry entry; final Entry entry;
final String filePath = getEntryMediaPath(fsid);
final File resource = new File(fsid); final File resource = new File(fsid);
if (resource.exists()) { if (resource.exists()) {
entry = loadAtomResourceEntry(in, resource); entry = loadAtomResourceEntry(in, resource);
@ -448,15 +450,12 @@ public class FileBasedCollection extends Collection {
updateFeedDocument(f); updateFeedDocument(f);
} }
private Entry findEntry(final String id, final Feed f) { private Entry findEntry(final String id, final Feed feed) {
final List l = f.getEntries(); for (final Entry entry : feed.getEntries()) {
for (final Iterator it = l.iterator(); it.hasNext();) { if (id.equals(entry.getId())) {
final Entry e = (Entry) it.next(); return entry;
if (id.equals(e.getId())) {
return e;
} }
} }
return null; return null;
} }
@ -526,10 +525,9 @@ public class FileBasedCollection extends Collection {
// Look for existing alt links and the alt link // Look for existing alt links and the alt link
Link altLink = null; Link altLink = null;
List altLinks = entry.getAlternateLinks(); List<Link> altLinks = entry.getAlternateLinks();
if (altLinks != null) { if (altLinks != null) {
for (final Iterator it = altLinks.iterator(); it.hasNext();) { for (final Link link : altLinks) {
final Link link = (Link) it.next();
if (link.getRel() == null || "alternate".equals(link.getRel())) { if (link.getRel() == null || "alternate".equals(link.getRel())) {
altLink = link; altLink = link;
break; break;
@ -537,7 +535,7 @@ public class FileBasedCollection extends Collection {
} }
} else { } else {
// No alt links found, so add them now // No alt links found, so add them now
altLinks = new ArrayList(); altLinks = new ArrayList<Link>();
entry.setAlternateLinks(altLinks); entry.setAlternateLinks(altLinks);
} }
// The alt link not found, so add it now // The alt link not found, so add it now
@ -551,10 +549,9 @@ public class FileBasedCollection extends Collection {
// Look for existing other links and the edit link // Look for existing other links and the edit link
Link editLink = null; Link editLink = null;
List otherLinks = entry.getOtherLinks(); List<Link> otherLinks = entry.getOtherLinks();
if (otherLinks != null) { if (otherLinks != null) {
for (final Iterator it = otherLinks.iterator(); it.hasNext();) { for (final Link link : otherLinks) {
final Link link = (Link) it.next();
if ("edit".equals(link.getRel())) { if ("edit".equals(link.getRel())) {
editLink = link; editLink = link;
break; break;
@ -562,7 +559,7 @@ public class FileBasedCollection extends Collection {
} }
} else { } else {
// No other links found, so add them now // No other links found, so add them now
otherLinks = new ArrayList(); otherLinks = new ArrayList<Link>();
entry.setOtherLinks(otherLinks); entry.setOtherLinks(otherLinks);
} }
// The edit link not found, so add it now // The edit link not found, so add it now
@ -585,13 +582,11 @@ public class FileBasedCollection extends Collection {
} catch (final Exception ignored) { } catch (final Exception ignored) {
} }
} }
final String contentType = map.getContentType(fileName);
entry.setId(getEntryMediaViewURI(fileName)); entry.setId(getEntryMediaViewURI(fileName));
entry.setTitle(fileName); entry.setTitle(fileName);
entry.setUpdated(new Date()); entry.setUpdated(new Date());
final List otherlinks = new ArrayList(); final List<Link> otherlinks = new ArrayList<Link>();
entry.setOtherLinks(otherlinks); entry.setOtherLinks(otherlinks);
final Link editlink = new Link(); final Link editlink = new Link();
@ -606,13 +601,14 @@ public class FileBasedCollection extends Collection {
final Content content = entry.getContents().get(0); final Content content = entry.getContents().get(0);
content.setSrc(getEntryMediaViewURI(fileName)); content.setSrc(getEntryMediaViewURI(fileName));
final List contents = new ArrayList(); final List<Content> contents = new ArrayList<Content>();
contents.add(content); contents.add(content);
entry.setContents(contents); entry.setContents(contents);
} }
/** /**
* Create a Rome Atom entry based on a Roller entry. Content is escaped. Link is stored as rel=alternate link. * Create a Rome Atom entry based on a Roller entry. Content is escaped. Link is stored as
* rel=alternate link.
*/ */
private Entry loadAtomEntry(final InputStream in) { private Entry loadAtomEntry(final InputStream in) {
try { try {
@ -633,7 +629,7 @@ public class FileBasedCollection extends Collection {
AppModule appModule = (AppModule) entry.getModule(AppModule.URI); AppModule appModule = (AppModule) entry.getModule(AppModule.URI);
if (appModule == null) { if (appModule == null) {
appModule = new AppModuleImpl(); appModule = new AppModuleImpl();
final List modules = entry.getModules() == null ? new ArrayList() : entry.getModules(); final List<Module> modules = entry.getModules() == null ? new ArrayList<Module>() : entry.getModules();
modules.add(appModule); modules.add(appModule);
entry.setModules(modules); entry.setModules(modules);
} }
@ -682,16 +678,20 @@ public class FileBasedCollection extends Collection {
* @param title Title to be used as basis for file name (or null) * @param title Title to be used as basis for file name (or null)
* @param contentType Content type of file (must not be null) * @param contentType Content type of file (must not be null)
* *
* If a title is specified, the method will apply the same create-anchor logic we use for weblog entries to create a file name based on the * If a title is specified, the method will apply the same create-anchor logic we use
* title. * for weblog entries to create a file name based on the title.
* *
* If title is null, the base file name will be the weblog handle plus a YYYYMMDDHHSS timestamp. * If title is null, the base file name will be the weblog handle plus a YYYYMMDDHHSS
* timestamp.
* *
* The extension will be formed by using the part of content type that comes after he slash. * The extension will be formed by using the part of content type that comes after he
* slash.
* *
* For example: weblog.handle = "daveblog" title = "Port Antonio" content-type = "image/jpg" Would result in port_antonio.jpg * For example: weblog.handle = "daveblog" title = "Port Antonio" content-type =
* "image/jpg" Would result in port_antonio.jpg
* *
* Another example: weblog.handle = "daveblog" title = null content-type = "image/jpg" Might result in daveblog-200608201034.jpg * Another example: weblog.handle = "daveblog" title = null content-type =
* "image/jpg" Might result in daveblog-200608201034.jpg
*/ */
private String createFileName(final String title, final String contentType) { private String createFileName(final String title, final String contentType) {

View file

@ -21,14 +21,10 @@ import org.rometools.propono.atom.common.Workspace;
* File based Atom service Workspace. * File based Atom service Workspace.
*/ */
public class FileBasedWorkspace extends Workspace { public class FileBasedWorkspace extends Workspace {
private String baseDir = null;
private String handle = null;
/** Creates a new instance of FileBasedWorkspace */ /** Creates a new instance of FileBasedWorkspace */
public FileBasedWorkspace(final String handle, final String baseDir) { public FileBasedWorkspace(final String handle, final String baseDir) {
super(handle, "text"); super(handle, "text");
this.handle = handle;
this.baseDir = baseDir;
} }
} }

View file

@ -34,7 +34,7 @@ import org.apache.commons.logging.LogFactory;
*/ */
class FileStore { class FileStore {
private static Log log = LogFactory.getFactory().getInstance(FileStore.class); private static final Log LOG = LogFactory.getFactory().getInstance(FileStore.class);
private static final FileStore fileStore = new FileStore(); private static final FileStore fileStore = new FileStore();
@ -49,29 +49,29 @@ class FileStore {
} }
public InputStream getFileInputStream(final String path) { public InputStream getFileInputStream(final String path) {
log.debug("getFileContents path: " + path); LOG.debug("getFileContents path: " + path);
try { try {
return new BufferedInputStream(new FileInputStream(path)); return new BufferedInputStream(new FileInputStream(path));
} catch (final FileNotFoundException e) { } catch (final FileNotFoundException e) {
log.debug(" File not found: " + path); LOG.debug(" File not found: " + path);
return null; return null;
} }
} }
public OutputStream getFileOutputStream(final String path) { public OutputStream getFileOutputStream(final String path) {
log.debug("getFileOutputStream path: " + path); LOG.debug("getFileOutputStream path: " + path);
try { try {
final File f = new File(path); final File f = new File(path);
f.getParentFile().mkdirs(); f.getParentFile().mkdirs();
return new BufferedOutputStream(new FileOutputStream(f)); return new BufferedOutputStream(new FileOutputStream(f));
} catch (final FileNotFoundException e) { } catch (final FileNotFoundException e) {
log.debug(" File not found: " + path); LOG.debug(" File not found: " + path);
return null; return null;
} }
} }
public void createOrUpdateFile(final String path, final InputStream content) throws FileNotFoundException, IOException { public void createOrUpdateFile(final String path, final InputStream content) throws FileNotFoundException, IOException {
log.debug("createOrUpdateFile path: " + path); LOG.debug("createOrUpdateFile path: " + path);
final File f = new File(path); final File f = new File(path);
f.mkdirs(); f.mkdirs();
final FileOutputStream out = new FileOutputStream(f); final FileOutputStream out = new FileOutputStream(f);
@ -81,13 +81,14 @@ class FileStore {
while ((read = content.read(buffer)) != -1) { while ((read = content.read(buffer)) != -1) {
out.write(buffer, 0, read); out.write(buffer, 0, read);
} }
out.close();
} }
public void deleteFile(final String path) { public void deleteFile(final String path) {
log.debug("deleteFile path: " + path); LOG.debug("deleteFile path: " + path);
final File f = new File(path); final File f = new File(path);
if (!f.delete()) { if (!f.delete()) {
log.debug(" Failed to delete: " + f.getAbsolutePath()); LOG.debug(" Failed to delete: " + f.getAbsolutePath());
} }
} }
@ -100,7 +101,7 @@ class FileStore {
} }
public boolean deleteDirectory(final File path) { public boolean deleteDirectory(final File path) {
log.debug("deleteDirectory path: " + path); LOG.debug("deleteDirectory path: " + path);
if (path.exists()) { if (path.exists()) {
final File[] files = path.listFiles(); final File[] files = path.listFiles();
for (final File file : files) { for (final File file : files) {

View file

@ -31,7 +31,7 @@ public abstract class BaseBlogEntry implements BlogEntry {
protected String summary = null; protected String summary = null;
protected Date modificationDate = null; protected Date modificationDate = null;
protected Date publicationDate = null; protected Date publicationDate = null;
protected List categories = new ArrayList(); protected List<Category> categories = new ArrayList<Category>();
protected boolean draft = false; protected boolean draft = false;
private Blog blog = null; private Blog blog = null;
@ -178,7 +178,7 @@ public abstract class BaseBlogEntry implements BlogEntry {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List getCategories() { public List<Category> getCategories() {
return categories; return categories;
} }
@ -186,7 +186,7 @@ public abstract class BaseBlogEntry implements BlogEntry {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public void setCategories(final List categories) { public void setCategories(final List<Category> categories) {
this.categories = categories; this.categories = categories;
} }

View file

@ -20,8 +20,9 @@ import java.util.List;
/** /**
* <p> * <p>
* Represents a blog, which has collections of entries and resources. You can access the collections using the getCollections() and getCollection(String name) * Represents a blog, which has collections of entries and resources. You can access the collections
* methods, which return Blog.Collection objects, which you can use to create, retrieve update or delete entries within a collection. * using the getCollections() and getCollection(String name) methods, which return Blog.Collection
* objects, which you can use to create, retrieve update or delete entries within a collection.
* </p> * </p>
*/ */
public interface Blog { public interface Blog {
@ -44,18 +45,20 @@ public interface Blog {
* Get a single BlogEntry (or BlogResource) by token. * Get a single BlogEntry (or BlogResource) by token.
* *
* @param token Token from blog entry's getToken() method. * @param token Token from blog entry's getToken() method.
* @throws com.sun.syndication.propono.blogclient.BlogClientException On error fetching the blog entry. * @throws com.sun.syndication.propono.blogclient.BlogClientException On error fetching the blog
* entry.
* @return Blog entry specified by token. * @return Blog entry specified by token.
*/ */
public BlogEntry getEntry(String token) throws BlogClientException; public BlogEntry getEntry(String token) throws BlogClientException;
/** /**
* Gets listing of entry and resource collections available in the blog, including the primary collections. * Gets listing of entry and resource collections available in the blog, including the primary
* collections.
* *
* @throws BlogClientException On error fetching collections. * @throws BlogClientException On error fetching collections.
* @return List of Blog.Collection objects. * @return List of Blog.Collection objects.
*/ */
public List getCollections() throws BlogClientException; public List<Collection> getCollections() throws BlogClientException;
/** /**
* Get collection by token. * Get collection by token.
@ -97,7 +100,7 @@ public interface Blog {
* *
* @return Comma-separated list of content-types accepted. * @return Comma-separated list of content-types accepted.
*/ */
public List getAccepts(); public List<String> getAccepts();
/** /**
* Determines if collection will accept a content-type. * Determines if collection will accept a content-type.
@ -113,7 +116,7 @@ public interface Blog {
* @throws BlogClientException On error fetching categories. * @throws BlogClientException On error fetching categories.
* @return List of BlogEntry.Category objects for this collection. * @return List of BlogEntry.Category objects for this collection.
*/ */
public List getCategories() throws BlogClientException; public List<BlogEntry.Category> getCategories() throws BlogClientException;
/** /**
* Create but do not save new entry in collection. To save entry, call its save() method. * Create but do not save new entry in collection. To save entry, call its save() method.
@ -124,7 +127,8 @@ public interface Blog {
public BlogEntry newEntry() throws BlogClientException; public BlogEntry newEntry() throws BlogClientException;
/** /**
* Create but do not save new resource in collection. To save resource, call its save() method. * Create but do not save new resource in collection. To save resource, call its save()
* method.
* *
* @param name Name of new resource. * @param name Name of new resource.
* @param contentType MIME content-type of new resource. * @param contentType MIME content-type of new resource.
@ -140,10 +144,11 @@ public interface Blog {
* @return List of BlogEntry objects, some may be BlogResources. * @return List of BlogEntry objects, some may be BlogResources.
* @throws BlogClientException On error fetching entries/resources. * @throws BlogClientException On error fetching entries/resources.
*/ */
public Iterator getEntries() throws BlogClientException; public Iterator<BlogEntry> getEntries() throws BlogClientException;
/** /**
* Save or update a BlogEntry in this collection by adding it to this collection and then calling it's entry.save() method. * Save or update a BlogEntry in this collection by adding it to this collection and then
* calling it's entry.save() method.
* *
* @param entry BlogEntry to be saved. * @param entry BlogEntry to be saved.
* @throws BlogClientException On error saving entry. * @throws BlogClientException On error saving entry.
@ -164,8 +169,9 @@ public interface Blog {
// Deprecated primary collection methods, instead use collections directly. // Deprecated primary collection methods, instead use collections directly.
/** /**
* Get iterator over entries in primary entries collection (the first collection that accepts entries). Note that entries may be partial, so don't try to * Get iterator over entries in primary entries collection (the first collection that accepts
* update and save them: to update and entry, first fetch it with getEntry(), change fields, then call entry.save(); * entries). Note that entries may be partial, so don't try to update and save them: to update
* and entry, first fetch it with getEntry(), change fields, then call entry.save();
* *
* @return To iterate over all entries in collection. * @return To iterate over all entries in collection.
* @throws BlogClientException On failure or if there is no primary entries collection. * @throws BlogClientException On failure or if there is no primary entries collection.
@ -173,10 +179,11 @@ public interface Blog {
* @deprecated Instead use collections directly. * @deprecated Instead use collections directly.
*/ */
@Deprecated @Deprecated
public Iterator getEntries() throws BlogClientException; public Iterator<BlogEntry> getEntries() throws BlogClientException;
/** /**
* Get entries in primary resources collection (the first collection that accepts anything other than entries). * Get entries in primary resources collection (the first collection that accepts anything other
* than entries).
* *
* @throws BlogClientException On failure or if there is no primary resources collection. * @throws BlogClientException On failure or if there is no primary resources collection.
* @return To iterate over all resojrces in collection. * @return To iterate over all resojrces in collection.
@ -184,11 +191,12 @@ public interface Blog {
* @deprecated Instead use collections directly. * @deprecated Instead use collections directly.
*/ */
@Deprecated @Deprecated
public Iterator getResources() throws BlogClientException; public Iterator<BlogEntry> getResources() throws BlogClientException;
/** /**
* Create but do not save it to server new BlogEntry in primary entries collection (the first collection found that accepts entries). To save the entry to * Create but do not save it to server new BlogEntry in primary entries collection (the first
* the server to a collection, use the entry's save() method. * collection found that accepts entries). To save the entry to the server to a collection, use
* the entry's save() method.
* *
* @throws BlogClientException On error or if there is no primary entries collection. * @throws BlogClientException On error or if there is no primary entries collection.
* @return Unsaved BlogEntry in primary entries collection. * @return Unsaved BlogEntry in primary entries collection.
@ -199,8 +207,9 @@ public interface Blog {
public BlogEntry newEntry() throws BlogClientException; public BlogEntry newEntry() throws BlogClientException;
/** /**
* Create but do not save it to server new BlogResource in primary resources collection (the first collection found that accepts resources). To save the * Create but do not save it to server new BlogResource in primary resources collection (the
* resource to the server to a collection, use the resource's save() method. * first collection found that accepts resources). To save the resource to the server to a
* collection, use the resource's save() method.
* *
* @param name Name of resource to be saved. * @param name Name of resource to be saved.
* @param type MIME content type of resource data. * @param type MIME content type of resource data.
@ -222,5 +231,5 @@ public interface Blog {
* @deprecated Instead use collections directly. * @deprecated Instead use collections directly.
*/ */
@Deprecated @Deprecated
public List getCategories() throws BlogClientException; public List<BlogEntry.Category> getCategories() throws BlogClientException;
} }

View file

@ -16,10 +16,13 @@
package org.rometools.propono.blogclient; package org.rometools.propono.blogclient;
/** /**
* Represents a Blog Client exception, the library throws these instead of implementation specific exceptions. * Represents a Blog Client exception, the library throws these instead of implementation specific
* exceptions.
*/ */
public class BlogClientException extends Exception { public class BlogClientException extends Exception {
private static final long serialVersionUID = 1L;
/** /**
* Construct a new exception * Construct a new exception
* *

View file

@ -18,12 +18,13 @@ package org.rometools.propono.blogclient;
import java.util.List; import java.util.List;
/** /**
* A BlogConnection is a single-user connection to a blog server where the user has access to multiple blogs, which are each represented by a Blog interface. * A BlogConnection is a single-user connection to a blog server where the user has access to
* multiple blogs, which are each represented by a Blog interface.
*/ */
public interface BlogConnection { public interface BlogConnection {
/** Returns collection of blogs available from this connection */ /** Returns collection of blogs available from this connection */
public abstract List getBlogs(); public abstract List<Blog> getBlogs();
/** Get blog by token */ /** Get blog by token */
public abstract Blog getBlog(String token); public abstract Blog getBlog(String token);

View file

@ -54,14 +54,15 @@ public class BlogConnectionFactory {
private static BlogConnection createBlogConnection(final String className, final String url, final String username, final String password) private static BlogConnection createBlogConnection(final String className, final String url, final String username, final String password)
throws BlogClientException { throws BlogClientException {
Class conClass;
Class<?> conClass;
try { try {
conClass = Class.forName(className); conClass = Class.forName(className);
} catch (final ClassNotFoundException ex) { } catch (final ClassNotFoundException ex) {
throw new BlogClientException("BlogConnection impl. class not found: " + className, ex); throw new BlogClientException("BlogConnection impl. class not found: " + className, ex);
} }
final Class[] args = new Class[] { String.class, String.class, String.class }; final Class<?>[] args = new Class[] { String.class, String.class, String.class };
Constructor ctor; Constructor<?> ctor;
try { try {
ctor = conClass.getConstructor(args); ctor = conClass.getConstructor(args);
return (BlogConnection) ctor.newInstance(new Object[] { url, username, password }); return (BlogConnection) ctor.newInstance(new Object[] { url, username, password });
@ -69,4 +70,5 @@ public class BlogConnectionFactory {
throw new BlogClientException("ERROR instantiating BlogConnection impl.", t); throw new BlogClientException("ERROR instantiating BlogConnection impl.", t);
} }
} }
} }

View file

@ -27,7 +27,8 @@ public interface BlogEntry {
public String getToken(); public String getToken();
/** /**
* Save this entry to it's collection. If this is a new entry and does not have a collection yet, then save() will save it to the primary collection. * Save this entry to it's collection. If this is a new entry and does not have a collection
* yet, then save() will save it to the primary collection.
*/ */
public void save() throws BlogClientException; public void save() throws BlogClientException;
@ -41,10 +42,10 @@ public interface BlogEntry {
public Blog getBlog(); public Blog getBlog();
/** Get categories, a list of BlogEntry.Category objects */ /** Get categories, a list of BlogEntry.Category objects */
public List getCategories(); public List<Category> getCategories();
/** Set categories, a list of BlogEntry.Category objects */ /** Set categories, a list of BlogEntry.Category objects */
public void setCategories(List categories); public void setCategories(List<Category> categories);
/** Get globally unique ID of this blog entry */ /** Get globally unique ID of this blog entry */
public String getId(); public String getId();
@ -117,14 +118,16 @@ public interface BlogEntry {
} }
/** /**
* Get type of content, either "text", "html", "xhtml" or a MIME content-type. Defaults to HTML. * Get type of content, either "text", "html", "xhtml" or a MIME content-type. Defaults to
* HTML.
*/ */
public String getType() { public String getType() {
return type; return type;
} }
/** /**
* Set type of content, either "text", "html", "xhtml" or a MIME content-type. Defaults to HTML. * Set type of content, either "text", "html", "xhtml" or a MIME content-type. Defaults to
* HTML.
*/ */
public void setType(final String type) { public void setType(final String type) {
this.type = type; this.type = type;

View file

@ -21,9 +21,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.TreeMap; import java.util.TreeMap;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.rometools.propono.atom.client.ClientAtomService; import org.rometools.propono.atom.client.ClientAtomService;
import org.rometools.propono.atom.client.ClientCollection; import org.rometools.propono.atom.client.ClientCollection;
import org.rometools.propono.atom.client.ClientEntry; import org.rometools.propono.atom.client.ClientEntry;
@ -39,25 +36,27 @@ import org.rometools.propono.utils.ProponoException;
* Atom protocol implementation of the BlogClient Blog interface. * Atom protocol implementation of the BlogClient Blog interface.
*/ */
public class AtomBlog implements Blog { public class AtomBlog implements Blog {
static final Log logger = LogFactory.getLog(AtomBlog.class);
private final HttpClient httpClient = null;
private String name = null; private String name = null;
private ClientAtomService service; private ClientAtomService service;
private ClientWorkspace workspace = null; private ClientWorkspace workspace = null;
private AtomCollection entriesCollection = null; private AtomCollection entriesCollection = null;
private AtomCollection resourcesCollection = null; private AtomCollection resourcesCollection = null;
private final Map collections = new TreeMap(); private final Map<String, AtomCollection> collections = new TreeMap<String, AtomCollection>();
/** /**
* Create AtomBlog using specified HTTPClient, user account and workspace, called by AtomConnection. Fetches Atom Service document and creates an * Create AtomBlog using specified HTTPClient, user account and workspace, called by
* AtomCollection object for each collection found. The first entry collection is considered the primary entry collection. And the first resource collection * AtomConnection. Fetches Atom Service document and creates an AtomCollection object for each
* is considered the primary resource collection. * collection found. The first entry collection is considered the primary entry collection. And
* the first resource collection is considered the primary resource collection.
*/ */
AtomBlog(final ClientAtomService service, final ClientWorkspace workspace) { AtomBlog(final ClientAtomService service, final ClientWorkspace workspace) {
setService(service); setService(service);
setWorkspace(workspace); setWorkspace(workspace);
name = workspace.getTitle(); name = workspace.getTitle();
final Iterator members = workspace.getCollections().iterator(); final List<org.rometools.propono.atom.common.Collection> collect = workspace.getCollections();
final Iterator<org.rometools.propono.atom.common.Collection> members = collect.iterator();
while (members.hasNext()) { while (members.hasNext()) {
final ClientCollection col = (ClientCollection) members.next(); final ClientCollection col = (ClientCollection) members.next();
@ -70,6 +69,7 @@ public class AtomBlog implements Blog {
} }
collections.put(col.getHrefResolved(), new AtomCollection(this, col)); collections.put(col.getHrefResolved(), new AtomCollection(this, col));
} }
} }
/** /**
@ -113,7 +113,6 @@ public class AtomBlog implements Blog {
@Override @Override
public BlogEntry getEntry(final String token) throws BlogClientException { public BlogEntry getEntry(final String token) throws BlogClientException {
ClientEntry clientEntry = null; ClientEntry clientEntry = null;
final AtomEntry atomEntry = null;
try { try {
clientEntry = getService().getEntry(token); clientEntry = getService().getEntry(token);
} catch (final ProponoException ex) { } catch (final ProponoException ex) {
@ -132,7 +131,7 @@ public class AtomBlog implements Blog {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public Iterator getEntries() throws BlogClientException { public Iterator<BlogEntry> getEntries() throws BlogClientException {
if (entriesCollection == null) { if (entriesCollection == null) {
throw new BlogClientException("No primary entry collection"); throw new BlogClientException("No primary entry collection");
} }
@ -143,7 +142,7 @@ public class AtomBlog implements Blog {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public Iterator getResources() throws BlogClientException { public Iterator<BlogEntry> getResources() throws BlogClientException {
if (resourcesCollection == null) { if (resourcesCollection == null) {
throw new BlogClientException("No primary entry collection"); throw new BlogClientException("No primary entry collection");
} }
@ -168,7 +167,7 @@ public class AtomBlog implements Blog {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List getCategories() throws BlogClientException { public List<BlogEntry.Category> getCategories() throws BlogClientException {
if (entriesCollection == null) { if (entriesCollection == null) {
throw new BlogClientException("No primary entry collection"); throw new BlogClientException("No primary entry collection");
} }
@ -201,8 +200,8 @@ public class AtomBlog implements Blog {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List getCollections() throws BlogClientException { public List<Collection> getCollections() throws BlogClientException {
return new ArrayList(collections.values()); return new ArrayList<Collection>(collections.values());
} }
/** /**
@ -210,7 +209,7 @@ public class AtomBlog implements Blog {
*/ */
@Override @Override
public Blog.Collection getCollection(final String token) throws BlogClientException { public Blog.Collection getCollection(final String token) throws BlogClientException {
return (Blog.Collection) collections.get(token); return collections.get(token);
} }
ClientAtomService getService() { ClientAtomService getService() {

View file

@ -19,8 +19,6 @@ import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.rometools.propono.atom.client.ClientAtomService; import org.rometools.propono.atom.client.ClientAtomService;
import org.rometools.propono.atom.client.ClientCollection; import org.rometools.propono.atom.client.ClientCollection;
import org.rometools.propono.atom.client.ClientEntry; import org.rometools.propono.atom.client.ClientEntry;
@ -36,20 +34,19 @@ import com.sun.syndication.feed.atom.Category;
* Atom protocol implementation of BlogClient Blog.Collection. * Atom protocol implementation of BlogClient Blog.Collection.
*/ */
public class AtomCollection implements Blog.Collection { public class AtomCollection implements Blog.Collection {
static final Log logger = LogFactory.getLog(AtomCollection.class);
private Blog blog = null; private Blog blog = null;
private List categories = new ArrayList(); private List<BlogEntry.Category> categories = new ArrayList<BlogEntry.Category>();
private ClientCollection clientCollection = null; private ClientCollection clientCollection = null;
AtomCollection(final AtomBlog blog, final ClientCollection col) { AtomCollection(final AtomBlog blog, final ClientCollection col) {
this.blog = blog; this.blog = blog;
clientCollection = col; clientCollection = col;
for (final Iterator catsIter = col.getCategories().iterator(); catsIter.hasNext();) { for (final Object element : col.getCategories()) {
final Categories cats = (Categories) catsIter.next(); final Categories cats = (Categories) element;
for (final Iterator catIter = cats.getCategories().iterator(); catIter.hasNext();) { for (final Object element2 : cats.getCategories()) {
final Category cat = (Category) catIter.next(); final Category cat = (Category) element2;
final BlogEntry.Category blogCat = new BlogEntry.Category(cat.getTerm()); final BlogEntry.Category blogCat = new BlogEntry.Category(cat.getTerm());
blogCat.setName(cat.getLabel()); blogCat.setName(cat.getLabel());
blogCat.setUrl(cat.getScheme()); blogCat.setUrl(cat.getScheme());
@ -78,7 +75,7 @@ public class AtomCollection implements Blog.Collection {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List getAccepts() { public List<String> getAccepts() {
return getClientCollection().getAccepts(); return getClientCollection().getAccepts();
} }
@ -94,7 +91,7 @@ public class AtomCollection implements Blog.Collection {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public Iterator getEntries() throws BlogClientException { public Iterator<BlogEntry> getEntries() throws BlogClientException {
return new AtomEntryIterator(this); return new AtomEntryIterator(this);
} }
@ -163,11 +160,11 @@ public class AtomCollection implements Blog.Collection {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List getCategories() { public List<BlogEntry.Category> getCategories() {
return categories; return categories;
} }
void setCategories(final List categories) { void setCategories(final List<BlogEntry.Category> categories) {
this.categories = categories; this.categories = categories;
} }

View file

@ -21,26 +21,22 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom2.Document;
import org.rometools.propono.atom.client.AtomClientFactory; import org.rometools.propono.atom.client.AtomClientFactory;
import org.rometools.propono.atom.client.BasicAuthStrategy; import org.rometools.propono.atom.client.BasicAuthStrategy;
import org.rometools.propono.atom.client.ClientAtomService; import org.rometools.propono.atom.client.ClientAtomService;
import org.rometools.propono.atom.client.ClientWorkspace; import org.rometools.propono.atom.client.ClientWorkspace;
import org.rometools.propono.atom.common.Workspace;
import org.rometools.propono.blogclient.Blog; import org.rometools.propono.blogclient.Blog;
import org.rometools.propono.blogclient.BlogClientException; import org.rometools.propono.blogclient.BlogClientException;
import org.rometools.propono.blogclient.BlogConnection; import org.rometools.propono.blogclient.BlogConnection;
/** /**
* Atom protocol of BlogConnection. Connects to Atom server, creates AtomBlog object for each Atom workspace found and within each blog a collection for each * Atom protocol of BlogConnection. Connects to Atom server, creates AtomBlog object for each Atom
* Atom collection found. * workspace found and within each blog a collection for each Atom collection found.
*/ */
public class AtomConnection implements BlogConnection { public class AtomConnection implements BlogConnection {
private static Log logger = LogFactory.getLog(AtomConnection.class);
private final HttpClient httpClient = null; private final Map<String, Blog> blogs = new HashMap<String, Blog>();
private final Map blogs = new HashMap();
/** /**
* Create Atom blog client instance for specified URL and user account. * Create Atom blog client instance for specified URL and user account.
@ -51,11 +47,9 @@ public class AtomConnection implements BlogConnection {
*/ */
public AtomConnection(final String uri, final String username, final String password) throws BlogClientException { public AtomConnection(final String uri, final String username, final String password) throws BlogClientException {
final Document doc = null;
try { try {
final ClientAtomService service = AtomClientFactory.getAtomService(uri, new BasicAuthStrategy(username, password)); final ClientAtomService service = AtomClientFactory.getAtomService(uri, new BasicAuthStrategy(username, password));
final Iterator iter = service.getWorkspaces().iterator(); final Iterator<Workspace> iter = service.getWorkspaces().iterator();
final int count = 0;
while (iter.hasNext()) { while (iter.hasNext()) {
final ClientWorkspace workspace = (ClientWorkspace) iter.next(); final ClientWorkspace workspace = (ClientWorkspace) iter.next();
final Blog blog = new AtomBlog(service, workspace); final Blog blog = new AtomBlog(service, workspace);
@ -70,8 +64,8 @@ public class AtomConnection implements BlogConnection {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List getBlogs() { public List<Blog> getBlogs() {
return new ArrayList(blogs.values()); return new ArrayList<Blog>(blogs.values());
} }
/** /**
@ -79,7 +73,7 @@ public class AtomConnection implements BlogConnection {
*/ */
@Override @Override
public Blog getBlog(final String token) { public Blog getBlog(final String token) {
return (AtomBlog) blogs.get(token); return blogs.get(token);
} }
/** /**

View file

@ -32,6 +32,8 @@ import org.rometools.propono.utils.ProponoException;
import com.sun.syndication.feed.atom.Entry; import com.sun.syndication.feed.atom.Entry;
import com.sun.syndication.feed.atom.Link; import com.sun.syndication.feed.atom.Link;
import com.sun.syndication.feed.module.Module;
import com.sun.syndication.feed.synd.SyndPerson;
/** /**
* Atom protocol implementation of BlogEntry. * Atom protocol implementation of BlogEntry.
@ -138,20 +140,19 @@ public class AtomEntry extends BaseBlogEntry implements BlogEntry {
id = entry.getId(); id = entry.getId();
title = entry.getTitle(); title = entry.getTitle();
editURI = entry.getEditURI(); editURI = entry.getEditURI();
final List altlinks = entry.getAlternateLinks(); final List<Link> altlinks = entry.getAlternateLinks();
if (altlinks != null) { if (altlinks != null) {
for (final Iterator iter = altlinks.iterator(); iter.hasNext();) { for (final Link link : altlinks) {
final Link link = (Link) iter.next();
if ("alternate".equals(link.getRel()) || link.getRel() == null) { if ("alternate".equals(link.getRel()) || link.getRel() == null) {
permalink = link.getHrefResolved(); permalink = link.getHrefResolved();
break; break;
} }
} }
} }
final List contents = entry.getContents(); final List<com.sun.syndication.feed.atom.Content> contents = entry.getContents();
com.sun.syndication.feed.atom.Content romeContent = null; com.sun.syndication.feed.atom.Content romeContent = null;
if (contents != null && contents.size() > 0) { if (contents != null && contents.size() > 0) {
romeContent = (com.sun.syndication.feed.atom.Content) contents.get(0); romeContent = contents.get(0);
} }
if (romeContent != null) { if (romeContent != null) {
content = new BlogEntry.Content(romeContent.getValue()); content = new BlogEntry.Content(romeContent.getValue());
@ -159,10 +160,9 @@ public class AtomEntry extends BaseBlogEntry implements BlogEntry {
content.setSrc(romeContent.getSrc()); content.setSrc(romeContent.getSrc());
} }
if (entry.getCategories() != null) { if (entry.getCategories() != null) {
final List cats = new ArrayList(); final List<Category> cats = new ArrayList<Category>();
final List romeCats = entry.getCategories(); final List<com.sun.syndication.feed.atom.Category> romeCats = entry.getCategories();
for (final Iterator iter = romeCats.iterator(); iter.hasNext();) { for (final com.sun.syndication.feed.atom.Category romeCat : romeCats) {
final com.sun.syndication.feed.atom.Category romeCat = (com.sun.syndication.feed.atom.Category) iter.next();
final BlogEntry.Category cat = new BlogEntry.Category(); final BlogEntry.Category cat = new BlogEntry.Category();
cat.setId(romeCat.getTerm()); cat.setId(romeCat.getTerm());
cat.setUrl(romeCat.getScheme()); cat.setUrl(romeCat.getScheme());
@ -171,7 +171,7 @@ public class AtomEntry extends BaseBlogEntry implements BlogEntry {
} }
categories = cats; categories = cats;
} }
final List authors = entry.getAuthors(); final List<SyndPerson> authors = entry.getAuthors();
if (authors != null && authors.size() > 0) { if (authors != null && authors.size() > 0) {
final com.sun.syndication.feed.atom.Person romeAuthor = (com.sun.syndication.feed.atom.Person) authors.get(0); final com.sun.syndication.feed.atom.Person romeAuthor = (com.sun.syndication.feed.atom.Person) authors.get(0);
if (romeAuthor != null) { if (romeAuthor != null) {
@ -202,7 +202,7 @@ public class AtomEntry extends BaseBlogEntry implements BlogEntry {
person.setName(author.getName()); person.setName(author.getName());
person.setEmail(author.getEmail()); person.setEmail(author.getEmail());
person.setUrl(author.getUrl()); person.setUrl(author.getUrl());
final List authors = new ArrayList(); final List<SyndPerson> authors = new ArrayList<SyndPerson>();
authors.add(person); authors.add(person);
entry.setAuthors(authors); entry.setAuthors(authors);
} }
@ -210,14 +210,14 @@ public class AtomEntry extends BaseBlogEntry implements BlogEntry {
final com.sun.syndication.feed.atom.Content romeContent = new com.sun.syndication.feed.atom.Content(); final com.sun.syndication.feed.atom.Content romeContent = new com.sun.syndication.feed.atom.Content();
romeContent.setValue(content.getValue()); romeContent.setValue(content.getValue());
romeContent.setType(content.getType()); romeContent.setType(content.getType());
final List contents = new ArrayList(); final List<com.sun.syndication.feed.atom.Content> contents = new ArrayList<com.sun.syndication.feed.atom.Content>();
contents.add(romeContent); contents.add(romeContent);
entry.setContents(contents); entry.setContents(contents);
} }
if (categories != null) { if (categories != null) {
final List romeCats = new ArrayList(); final List<com.sun.syndication.feed.atom.Category> romeCats = new ArrayList<com.sun.syndication.feed.atom.Category>();
for (final Iterator iter = categories.iterator(); iter.hasNext();) { for (final Iterator<Category> iter = categories.iterator(); iter.hasNext();) {
final BlogEntry.Category cat = (BlogEntry.Category) iter.next(); final BlogEntry.Category cat = iter.next();
final com.sun.syndication.feed.atom.Category romeCategory = new com.sun.syndication.feed.atom.Category(); final com.sun.syndication.feed.atom.Category romeCategory = new com.sun.syndication.feed.atom.Category();
romeCategory.setTerm(cat.getId()); romeCategory.setTerm(cat.getId());
romeCategory.setScheme(cat.getUrl()); romeCategory.setScheme(cat.getUrl());
@ -229,7 +229,7 @@ public class AtomEntry extends BaseBlogEntry implements BlogEntry {
entry.setPublished(publicationDate == null ? new Date() : publicationDate); entry.setPublished(publicationDate == null ? new Date() : publicationDate);
entry.setModified(modificationDate == null ? new Date() : modificationDate); entry.setModified(modificationDate == null ? new Date() : modificationDate);
final List modules = new ArrayList(); final List<Module> modules = new ArrayList<Module>();
final AppModule control = new AppModuleImpl(); final AppModule control = new AppModuleImpl();
control.setDraft(new Boolean(draft)); control.setDraft(new Boolean(draft));
modules.add(control); modules.add(control);

View file

@ -22,13 +22,15 @@ import org.apache.commons.logging.LogFactory;
import org.rometools.propono.atom.client.ClientEntry; import org.rometools.propono.atom.client.ClientEntry;
import org.rometools.propono.atom.client.ClientMediaEntry; import org.rometools.propono.atom.client.ClientMediaEntry;
import org.rometools.propono.blogclient.BlogClientException; import org.rometools.propono.blogclient.BlogClientException;
import org.rometools.propono.blogclient.BlogEntry;
/** /**
* Atom protocol implementation of BlogClient entry iterator. * Atom protocol implementation of BlogClient entry iterator.
*/ */
public class AtomEntryIterator implements Iterator { public class AtomEntryIterator implements Iterator<BlogEntry> {
static final Log logger = LogFactory.getLog(AtomEntryIterator.class);
private Iterator iterator = null; private static final Log logger = LogFactory.getLog(AtomEntryIterator.class);
private Iterator<ClientEntry> iterator = null;
private AtomCollection collection = null; private AtomCollection collection = null;
AtomEntryIterator(final AtomCollection collection) throws BlogClientException { AtomEntryIterator(final AtomCollection collection) throws BlogClientException {
@ -52,9 +54,9 @@ public class AtomEntryIterator implements Iterator {
* Get next entry. * Get next entry.
*/ */
@Override @Override
public Object next() { public BlogEntry next() {
try { try {
final ClientEntry entry = (ClientEntry) iterator.next(); final ClientEntry entry = iterator.next();
if (entry instanceof ClientMediaEntry) { if (entry instanceof ClientMediaEntry) {
return new AtomResource(collection, (ClientMediaEntry) entry); return new AtomResource(collection, (ClientMediaEntry) entry);
} else { } else {

View file

@ -16,7 +16,6 @@
package org.rometools.propono.blogclient.atomprotocol; package org.rometools.propono.blogclient.atomprotocol;
import java.io.InputStream; import java.io.InputStream;
import java.util.Iterator;
import java.util.List; import java.util.List;
import org.rometools.propono.atom.client.ClientAtomService; import org.rometools.propono.atom.client.ClientAtomService;
@ -33,6 +32,7 @@ import com.sun.syndication.feed.atom.Link;
* Atom protocol implementation of BlogResource. * Atom protocol implementation of BlogResource.
*/ */
public class AtomResource extends AtomEntry implements BlogResource { public class AtomResource extends AtomEntry implements BlogResource {
private AtomCollection collection; private AtomCollection collection;
private byte[] bytes; private byte[] bytes;
@ -119,17 +119,15 @@ public class AtomResource extends AtomEntry implements BlogResource {
@Override @Override
void copyFromRomeEntry(final ClientEntry entry) { void copyFromRomeEntry(final ClientEntry entry) {
super.copyFromRomeEntry(entry); super.copyFromRomeEntry(entry);
final List<Link> links = entry.getOtherLinks();
final List links = entry.getOtherLinks();
if (links != null) { if (links != null) {
for (final Iterator iter = links.iterator(); iter.hasNext();) { for (final Link link : links) {
final Link link = (Link) iter.next();
if ("edit-media".equals(link.getRel())) { if ("edit-media".equals(link.getRel())) {
id = link.getHrefResolved(); id = link.getHrefResolved();
break; break;
} }
} }
} }
} }
} }

View file

@ -30,20 +30,22 @@ import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.rometools.propono.blogclient.Blog; import org.rometools.propono.blogclient.Blog;
import org.rometools.propono.blogclient.BlogClientException; import org.rometools.propono.blogclient.BlogClientException;
import org.rometools.propono.blogclient.BlogEntry; import org.rometools.propono.blogclient.BlogEntry;
import org.rometools.propono.blogclient.BlogEntry.Category;
import org.rometools.propono.blogclient.BlogResource; import org.rometools.propono.blogclient.BlogResource;
/** /**
* Blog implementation that uses a mix of Blogger and MetaWeblog API methods. * Blog implementation that uses a mix of Blogger and MetaWeblog API methods.
*/ */
public class MetaWeblogBlog implements Blog { public class MetaWeblogBlog implements Blog {
private final String blogid; private final String blogid;
private final String name; private final String name;
private final URL url; private final URL url;
private final String userName; private final String userName;
private final String password; private final String password;
private String appkey = "dummy"; private final Map<String, MetaWeblogBlogCollection> collections;
private final Map collections;
private String appkey = "dummy";
private XmlRpcClient xmlRpcClient = null; private XmlRpcClient xmlRpcClient = null;
/** /**
@ -87,7 +89,7 @@ public class MetaWeblogBlog implements Blog {
this.url = url; this.url = url;
this.userName = userName; this.userName = userName;
this.password = password; this.password = password;
collections = new TreeMap(); collections = new TreeMap<String, MetaWeblogBlogCollection>();
collections.put("entries", new MetaWeblogBlogCollection(this, "entries", "Entries", "entry")); collections.put("entries", new MetaWeblogBlogCollection(this, "entries", "Entries", "entry"));
collections.put("resources", new MetaWeblogBlogCollection(this, "resources", "Resources", "*")); collections.put("resources", new MetaWeblogBlogCollection(this, "resources", "Resources", "*"));
} }
@ -106,7 +108,7 @@ public class MetaWeblogBlog implements Blog {
} }
String saveEntry(final BlogEntry entry) throws BlogClientException { String saveEntry(final BlogEntry entry) throws BlogClientException {
final Blog.Collection col = (Blog.Collection) collections.get("entries"); final Blog.Collection col = collections.get("entries");
return col.saveEntry(entry); return col.saveEntry(entry);
} }
@ -135,7 +137,7 @@ public class MetaWeblogBlog implements Blog {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public Iterator getEntries() throws BlogClientException { public Iterator<BlogEntry> getEntries() throws BlogClientException {
return new EntryIterator(); return new EntryIterator();
} }
@ -148,7 +150,7 @@ public class MetaWeblogBlog implements Blog {
} }
String saveResource(final MetaWeblogResource resource) throws BlogClientException { String saveResource(final MetaWeblogResource resource) throws BlogClientException {
final Blog.Collection col = (Blog.Collection) collections.get("resources"); final Blog.Collection col = collections.get("resources");
return col.saveResource(resource); return col.saveResource(resource);
} }
@ -160,8 +162,8 @@ public class MetaWeblogBlog implements Blog {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public Iterator getResources() throws BlogClientException { public NoOpIterator<BlogEntry> getResources() throws BlogClientException {
return new NoOpIterator(); return new NoOpIterator<BlogEntry>();
} }
void deleteResource(final BlogResource resource) throws BlogClientException { void deleteResource(final BlogResource resource) throws BlogClientException {
@ -172,14 +174,15 @@ public class MetaWeblogBlog implements Blog {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List getCategories() throws BlogClientException { public List<Category> getCategories() throws BlogClientException {
final ArrayList ret = new ArrayList(); final ArrayList<Category> ret = new ArrayList<Category>();
try { try {
final Object result = getXmlRpcClient().execute("metaWeblog.getCategories", new Object[] { blogid, userName, password }); final Object result = getXmlRpcClient().execute("metaWeblog.getCategories", new Object[] { blogid, userName, password });
if (result != null && result instanceof HashMap) { if (result != null && result instanceof HashMap) {
// Standard MetaWeblog API style: struct of struts // Standard MetaWeblog API style: struct of struts
final Map catsmap = (Map) result; final Map catsmap = (Map) result;
final Iterator keys = catsmap.keySet().iterator(); final Iterator keys = catsmap.keySet().iterator();
while (keys.hasNext()) { while (keys.hasNext()) {
final String key = (String) keys.next(); final String key = (String) keys.next();
@ -208,7 +211,7 @@ public class MetaWeblogBlog implements Blog {
return ret; return ret;
} }
private HashMap createPostStructure(final BlogEntry entry) { private Map<String, Object> createPostStructure(final BlogEntry entry) {
return ((MetaWeblogEntry) entry).toPostStructure(); return ((MetaWeblogEntry) entry).toPostStructure();
} }
@ -216,8 +219,8 @@ public class MetaWeblogBlog implements Blog {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List getCollections() throws BlogClientException { public List<Collection> getCollections() throws BlogClientException {
return new ArrayList(collections.values()); return new ArrayList<Collection>(collections.values());
} }
/** /**
@ -225,7 +228,7 @@ public class MetaWeblogBlog implements Blog {
*/ */
@Override @Override
public Blog.Collection getCollection(final String token) throws BlogClientException { public Blog.Collection getCollection(final String token) throws BlogClientException {
return (Blog.Collection) collections.get(token); return collections.get(token);
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
@ -269,7 +272,7 @@ public class MetaWeblogBlog implements Blog {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List getAccepts() { public List<String> getAccepts() {
return Collections.singletonList(accept); return Collections.singletonList(accept);
} }
@ -308,8 +311,8 @@ public class MetaWeblogBlog implements Blog {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public Iterator getEntries() throws BlogClientException { public Iterator<BlogEntry> getEntries() throws BlogClientException {
Iterator ret = null; Iterator<BlogEntry> ret = null;
if (accept.equals("entry")) { if (accept.equals("entry")) {
ret = MetaWeblogBlog.this.getEntries(); ret = MetaWeblogBlog.this.getEntries();
} else { } else {
@ -349,7 +352,7 @@ public class MetaWeblogBlog implements Blog {
public String saveResource(final BlogResource res) throws BlogClientException { public String saveResource(final BlogResource res) throws BlogClientException {
final MetaWeblogResource resource = (MetaWeblogResource) res; final MetaWeblogResource resource = (MetaWeblogResource) res;
try { try {
final HashMap resmap = new HashMap(); final HashMap<String, Object> resmap = new HashMap<String, Object>();
resmap.put("name", resource.getName()); resmap.put("name", resource.getName());
resmap.put("type", resource.getContent().getType()); resmap.put("type", resource.getContent().getType());
resmap.put("bits", resource.getBytes()); resmap.put("bits", resource.getBytes());
@ -366,7 +369,7 @@ public class MetaWeblogBlog implements Blog {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List getCategories() throws BlogClientException { public List<Category> getCategories() throws BlogClientException {
return MetaWeblogBlog.this.getCategories(); return MetaWeblogBlog.this.getCategories();
} }
@ -383,7 +386,7 @@ public class MetaWeblogBlog implements Blog {
/** /**
* Iterates over MetaWeblog API entries. * Iterates over MetaWeblog API entries.
*/ */
public class EntryIterator implements Iterator { public class EntryIterator implements Iterator<BlogEntry> {
private int pos = 0; private int pos = 0;
private boolean eod = false; private boolean eod = false;
private static final int BUFSIZE = 30; private static final int BUFSIZE = 30;
@ -414,7 +417,7 @@ public class MetaWeblogBlog implements Blog {
* Get next entry. * Get next entry.
*/ */
@Override @Override
public Object next() { public BlogEntry next() {
final Map entryHash = (Map) results.get(pos++); final Map entryHash = (Map) results.get(pos++);
return new MetaWeblogEntry(MetaWeblogBlog.this, entryHash); return new MetaWeblogEntry(MetaWeblogBlog.this, entryHash);
} }
@ -441,33 +444,4 @@ public class MetaWeblogBlog implements Blog {
} }
} }
// -------------------------------------------------------------------------
/**
* No-op iterator.
*/
public class NoOpIterator implements Iterator {
/**
* No-op
*/
@Override
public boolean hasNext() {
return false;
}
/**
* No-op
*/
@Override
public Object next() {
return null;
}
/**
* No-op
*/
@Override
public void remove() {
}
}
} }

View file

@ -33,11 +33,12 @@ import org.rometools.propono.blogclient.BlogConnection;
* BlogClient implementation that uses a mix of Blogger and MetaWeblog API methods. * BlogClient implementation that uses a mix of Blogger and MetaWeblog API methods.
*/ */
public class MetaWeblogConnection implements BlogConnection { public class MetaWeblogConnection implements BlogConnection {
private URL url = null; private URL url = null;
private String userName = null; private String userName = null;
private String password = null; private String password = null;
private String appkey = "null"; private String appkey = "null";
private Map blogs = null; private Map<String, MetaWeblogBlog> blogs = null;
private XmlRpcClient xmlRpcClient = null; private XmlRpcClient xmlRpcClient = null;
@ -66,20 +67,20 @@ public class MetaWeblogConnection implements BlogConnection {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public List getBlogs() { public List<Blog> getBlogs() {
return new ArrayList(blogs.values()); return new ArrayList<Blog>(blogs.values());
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
private Map createBlogMap() throws XmlRpcException, IOException { private Map<String, MetaWeblogBlog> createBlogMap() throws XmlRpcException, IOException {
final Map blogMap = new HashMap(); final Map<String, MetaWeblogBlog> blogMap = new HashMap<String, MetaWeblogBlog>();
final Object[] results = (Object[]) getXmlRpcClient().execute("blogger.getUsersBlogs", new Object[] { appkey, userName, password }); final Object[] results = (Object[]) getXmlRpcClient().execute("blogger.getUsersBlogs", new Object[] { appkey, userName, password });
for (final Object result : results) { for (final Object result : results) {
final Map blog = (Map) result; final Map<String, String> blog = (Map<String, String>) result;
final String blogid = (String) blog.get("blogid"); final String blogid = blog.get("blogid");
final String name = (String) blog.get("blogName"); final String name = blog.get("blogName");
blogMap.put(blogid, new MetaWeblogBlog(blogid, name, url, userName, password)); blogMap.put(blogid, new MetaWeblogBlog(blogid, name, url, userName, password));
} }
return blogMap; return blogMap;
@ -90,7 +91,7 @@ public class MetaWeblogConnection implements BlogConnection {
*/ */
@Override @Override
public Blog getBlog(final String token) { public Blog getBlog(final String token) {
return (Blog) blogs.get(token); return blogs.get(token);
} }
/** /**

View file

@ -50,7 +50,7 @@ public class MetaWeblogEntry extends BaseBlogEntry {
author.setName((String) entryMap.get("userid")); author.setName((String) entryMap.get("userid"));
author.setEmail((String) entryMap.get("author")); author.setEmail((String) entryMap.get("author"));
categories = new ArrayList(); categories = new ArrayList<Category>();
final Object[] catArray = (Object[]) entryMap.get("categories"); final Object[] catArray = (Object[]) entryMap.get("categories");
if (catArray != null) { if (catArray != null) {
for (final Object element : catArray) { for (final Object element : catArray) {
@ -98,8 +98,8 @@ public class MetaWeblogEntry extends BaseBlogEntry {
((MetaWeblogBlog) getBlog()).deleteEntry(id); ((MetaWeblogBlog) getBlog()).deleteEntry(id);
} }
HashMap toPostStructure() { Map<String, Object> toPostStructure() {
final HashMap struct = new HashMap(); final Map<String, Object> struct = new HashMap<String, Object>();
if (getTitle() != null) { if (getTitle() != null) {
struct.put("title", getTitle()); struct.put("title", getTitle());
} }
@ -107,10 +107,10 @@ public class MetaWeblogEntry extends BaseBlogEntry {
struct.put("description", getContent().getValue()); struct.put("description", getContent().getValue());
} }
if (getCategories() != null && getCategories().size() > 0) { if (getCategories() != null && getCategories().size() > 0) {
final List catArray = new ArrayList(); final List<String> catArray = new ArrayList<String>();
final List cats = getCategories(); final List<Category> cats = getCategories();
for (int i = 0; i < cats.size(); i++) { for (int i = 0; i < cats.size(); i++) {
final BlogEntry.Category cat = (BlogEntry.Category) cats.get(i); final BlogEntry.Category cat = cats.get(i);
catArray.add(cat.getName()); catArray.add(cat.getName());
} }
struct.put("categories", catArray); struct.put("categories", catArray);

View file

@ -0,0 +1,24 @@
package org.rometools.propono.blogclient.metaweblog;
import java.util.Iterator;
class NoOpIterator<T> implements Iterator<T> {
/** No-op */
@Override
public boolean hasNext() {
return false;
}
/** No-op */
@Override
public T next() {
return null;
}
/** No-op */
@Override
public void remove() {
}
}

View file

@ -23,8 +23,8 @@ import java.io.PrintWriter;
*/ */
public class ProponoException extends Exception { public class ProponoException extends Exception {
private static final long serialVersionUID = 1L;
private Throwable mRootCause = null; private Throwable mRootCause = null;
private String longMessage = null;
/** /**
* Construct emtpy exception object. * Construct emtpy exception object.
@ -49,7 +49,6 @@ public class ProponoException extends Exception {
*/ */
public ProponoException(final String s, final String longMessage) { public ProponoException(final String s, final String longMessage) {
super(s); super(s);
this.longMessage = longMessage;
} }
/** /**
@ -69,10 +68,9 @@ public class ProponoException extends Exception {
* @param s Error message * @param s Error message
* @param t Existing connection to wrap. * @param t Existing connection to wrap.
*/ */
public ProponoException(final String s, final String longMessge, final Throwable t) { public ProponoException(final String s, final String longMessage, final Throwable t) {
super(s); super(s);
mRootCause = t; mRootCause = t;
longMessage = longMessage;
} }
/** /**

View file

@ -28,53 +28,55 @@ import java.util.NoSuchElementException;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.Parent;
/** /**
* Utilities for file I/O and string manipulation. * Utilities for file I/O and string manipulation.
*/ */
public class Utilities { public final class Utilities {
private static final String LS = System.getProperty("line.separator"); private static final String LS = System.getProperty("line.separator");
private Utilities() {
}
/** /**
* Returns the contents of the file in a byte array (from JavaAlmanac). * Returns the contents of the file in a byte array (from JavaAlmanac).
*/ */
public static byte[] getBytesFromFile(final File file) throws IOException { public static byte[] getBytesFromFile(final File file) throws IOException {
final InputStream is = new FileInputStream(file); final InputStream is = new FileInputStream(file);
try {
// Get the size of the file // Get the size of the file
final long length = file.length(); final long length = file.length();
// You cannot create an array using a long type. // You cannot create an array using a long type.
// It needs to be an int type. // It needs to be an int type.
// Before converting to an int type, check // Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE. // to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) { if (length > Integer.MAX_VALUE) {
// File is too large // File is too large
}
// Create the byte array to hold the data
final byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + file.getName());
}
return bytes;
} finally {
is.close();
} }
// Create the byte array to hold the data
final byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
} }
/** /**
@ -159,107 +161,110 @@ public class Utilities {
static Pattern absoluteURIPattern = Pattern.compile("^[a-z0-9]*:.*$"); static Pattern absoluteURIPattern = Pattern.compile("^[a-z0-9]*:.*$");
private static boolean isAbsoluteURI(final String uri) { // private static boolean isAbsoluteURI(final String uri) {
return absoluteURIPattern.matcher(uri).find(); // return absoluteURIPattern.matcher(uri).find();
} // }
private static boolean isRelativeURI(final String uri) { // private static boolean isRelativeURI(final String uri) {
return !isAbsoluteURI(uri); // return !isAbsoluteURI(uri);
} // }
/** // /**
* } Resolve URI based considering xml:base and baseURI. // * } Resolve URI based considering xml:base and baseURI.
* // *
* @param baseURI Base URI of feed // * @param baseURI Base URI of feed
* @param parent Parent from which to consider xml:base // * @param parent Parent from which to consider xml:base
* @param url URL to be resolved // * @param url URL to be resolved
*/ // */
private static String resolveURI(final String baseURI, final Parent parent, String url) { // private static String resolveURI(final String baseURI, final Parent parent, String url) {
if (isRelativeURI(url)) { // if (isRelativeURI(url)) {
url = !".".equals(url) && !"./".equals(url) ? url : ""; // url = !".".equals(url) && !"./".equals(url) ? url : "";
//
// // Relative URI with parent
// if (parent != null && parent instanceof Element) {
//
// // Do we have an xml:base?
// String xmlbase = ((Element) parent).getAttributeValue("base", Namespace.XML_NAMESPACE);
// if (xmlbase != null && xmlbase.trim().length() > 0) {
// if (isAbsoluteURI(xmlbase)) {
// // Absolute xml:base, so form URI right now
// if (url.startsWith("/")) {
// // Host relative URI
// final int slashslash = xmlbase.indexOf("//");
// final int nextslash = xmlbase.indexOf("/", slashslash + 2);
// if (nextslash != -1) {
// xmlbase = xmlbase.substring(0, nextslash);
// }
// return formURI(xmlbase, url);
// }
// if (!xmlbase.endsWith("/")) {
// // Base URI is filename, strip it off
// xmlbase = xmlbase.substring(0, xmlbase.lastIndexOf("/"));
// }
// return formURI(xmlbase, url);
// } else {
// // Relative xml:base, so walk up tree
// return resolveURI(baseURI, parent.getParent(), stripTrailingSlash(xmlbase) + "/" +
// stripStartingSlash(url));
// }
// }
// // No xml:base so walk up tree
// return resolveURI(baseURI, parent.getParent(), url);
//
// // Relative URI with no parent (i.e. top of tree), so form URI right now
// } else if (parent == null || parent instanceof Document) {
// return formURI(baseURI, url);
// }
// }
// return url;
// }
// Relative URI with parent // /**
if (parent != null && parent instanceof Element) { // * Form URI by combining base with append portion and giving special consideration to append
// * portions that begin with ".."
// *
// * @param base Base of URI, may end with trailing slash
// * @param append String to append, may begin with slash or ".."
// */
// private static String formURI(String base, String append) {
// base = stripTrailingSlash(base);
// append = stripStartingSlash(append);
// if (append.startsWith("..")) {
// final String ret = null;
// final String[] parts = append.split("/");
// for (final String part : parts) {
// if ("..".equals(part)) {
// final int last = base.lastIndexOf("/");
// if (last != -1) {
// base = base.substring(0, last);
// append = append.substring(3, append.length());
// } else {
// break;
// }
// }
// }
// }
// return base + "/" + append;
// }
// Do we have an xml:base? // /**
String xmlbase = ((Element) parent).getAttributeValue("base", Namespace.XML_NAMESPACE); // * Strip starting slash from beginning of string.
if (xmlbase != null && xmlbase.trim().length() > 0) { // */
if (isAbsoluteURI(xmlbase)) { // private static String stripStartingSlash(String s) {
// Absolute xml:base, so form URI right now // if (s != null && s.startsWith("/")) {
if (url.startsWith("/")) { // s = s.substring(1, s.length());
// Host relative URI // }
final int slashslash = xmlbase.indexOf("//"); // return s;
final int nextslash = xmlbase.indexOf("/", slashslash + 2); // }
if (nextslash != -1) {
xmlbase = xmlbase.substring(0, nextslash);
}
return formURI(xmlbase, url);
}
if (!xmlbase.endsWith("/")) {
// Base URI is filename, strip it off
xmlbase = xmlbase.substring(0, xmlbase.lastIndexOf("/"));
}
return formURI(xmlbase, url);
} else {
// Relative xml:base, so walk up tree
return resolveURI(baseURI, parent.getParent(), stripTrailingSlash(xmlbase) + "/" + stripStartingSlash(url));
}
}
// No xml:base so walk up tree
return resolveURI(baseURI, parent.getParent(), url);
// Relative URI with no parent (i.e. top of tree), so form URI right now // /**
} else if (parent == null || parent instanceof Document) { // * Strip trailing slash from end of string.
return formURI(baseURI, url); // */
} // private static String stripTrailingSlash(String s) {
} // if (s != null && s.endsWith("/")) {
return url; // s = s.substring(0, s.length() - 1);
} // }
// return s;
// }
/**
* Form URI by combining base with append portion and giving special consideration to append portions that begin with ".."
*
* @param base Base of URI, may end with trailing slash
* @param append String to append, may begin with slash or ".."
*/
private static String formURI(String base, String append) {
base = stripTrailingSlash(base);
append = stripStartingSlash(append);
if (append.startsWith("..")) {
final String ret = null;
final String[] parts = append.split("/");
for (final String part : parts) {
if ("..".equals(part)) {
final int last = base.lastIndexOf("/");
if (last != -1) {
base = base.substring(0, last);
append = append.substring(3, append.length());
} else {
break;
}
}
}
}
return base + "/" + append;
}
/**
* Strip starting slash from beginning of string.
*/
private static String stripStartingSlash(String s) {
if (s != null && s.startsWith("/")) {
s = s.substring(1, s.length());
}
return s;
}
/**
* Strip trailing slash from end of string.
*/
private static String stripTrailingSlash(String s) {
if (s != null && s.endsWith("/")) {
s = s.substring(0, s.length() - 1);
}
return s;
}
} }

View file

@ -17,7 +17,6 @@ package org.rometools.propono.atom.client;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import junit.framework.Test; import junit.framework.Test;
@ -26,13 +25,13 @@ import junit.framework.TestSuite;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.junit.Ignore;
import org.rometools.propono.atom.common.Categories; import org.rometools.propono.atom.common.Categories;
import org.rometools.propono.atom.common.Collection; import org.rometools.propono.atom.common.Collection;
import org.rometools.propono.utils.ProponoException; import org.rometools.propono.utils.ProponoException;
import com.sun.syndication.feed.atom.Category; import com.sun.syndication.feed.atom.Category;
import com.sun.syndication.feed.atom.Content; import com.sun.syndication.feed.atom.Content;
import org.junit.Ignore;
/** /**
* Simple APP test designed to run against a live Atom server. * Simple APP test designed to run against a live Atom server.
@ -57,24 +56,31 @@ public class AtomClientTest extends TestCase {
} }
/* /*
* // Roller OAuth example private static String endpoint = "http://macsnoopdave:8080/roller-services/app"; private static String consumerKey = * // Roller OAuth example private static String endpoint =
* "55132608a2fb68816bcd3d1caeafc933"; private static String consumerSecret = "bb420783-fdea-4270-ab83-36445c18c307"; private static String requestUri = * "http://macsnoopdave:8080/roller-services/app"; private static String consumerKey =
* "http://macsnoopdave:8080/roller-services/oauth/requestToken"; private static String authorizeUri = * "55132608a2fb68816bcd3d1caeafc933"; private static String consumerSecret =
* "http://macsnoopdave:8080/roller-services/oauth/authorize?userId=roller&oauth_callback=none"; private static String accessUri = * "bb420783-fdea-4270-ab83-36445c18c307"; private static String requestUri =
* "http://macsnoopdave:8080/roller-services/oauth/accessToken"; private static String username = "roller"; private static String password = "n/a"; static { * "http://macsnoopdave:8080/roller-services/oauth/requestToken"; private static String
* try { service = AtomClientFactory.getAtomService(endpoint, new OAuthStrategy( username, consumerKey, consumerSecret, "HMAC-SHA1", requestUri, * authorizeUri =
* authorizeUri, accessUri)); } catch (Exception e) { log.error("ERROR creating service", e); } } * "http://macsnoopdave:8080/roller-services/oauth/authorize?userId=roller&oauth_callback=none";
* private static String accessUri =
* "http://macsnoopdave:8080/roller-services/oauth/accessToken"; private static String username
* = "roller"; private static String password = "n/a"; static { try { service =
* AtomClientFactory.getAtomService(endpoint, new OAuthStrategy( username, consumerKey,
* consumerSecret, "HMAC-SHA1", requestUri, authorizeUri, accessUri)); } catch (Exception e) {
* log.error("ERROR creating service", e); } }
*/ */
// GData Blogger API // GData Blogger API
/* /*
* private static String endpoint = "http://www.blogger.com/feeds/default/blogs?alt=atom-service"; private static String email = "EMAIL"; private static * private static String endpoint =
* String password = "PASSWORD"; private static String serviceName = "blogger"; static { try { service = AtomClientFactory.getAtomService(endpoint, new * "http://www.blogger.com/feeds/default/blogs?alt=atom-service"; private static String email =
* GDataAuthStrategy(email, password, serviceName)); } catch (Exception e) { log.error("ERROR creating service", e); } } * "EMAIL"; private static String password = "PASSWORD"; private static String serviceName =
* "blogger"; static { try { service = AtomClientFactory.getAtomService(endpoint, new
* GDataAuthStrategy(email, password, serviceName)); } catch (Exception e) {
* log.error("ERROR creating service", e); } }
*/ */
private final int maxPagingEntries = 10;
public AtomClientTest(final String testName) { public AtomClientTest(final String testName) {
super(testName); super(testName);
} }
@ -110,12 +116,12 @@ public class AtomClientTest extends TestCase {
public void testGetAtomService() throws Exception { public void testGetAtomService() throws Exception {
assertNotNull(service); assertNotNull(service);
assertTrue(service.getWorkspaces().size() > 0); assertTrue(service.getWorkspaces().size() > 0);
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) { for (final Object element : service.getWorkspaces()) {
final ClientWorkspace space = (ClientWorkspace) it.next(); final ClientWorkspace space = (ClientWorkspace) element;
assertNotNull(space.getTitle()); assertNotNull(space.getTitle());
log.debug("Workspace: " + space.getTitle()); log.debug("Workspace: " + space.getTitle());
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) { for (final Object element2 : space.getCollections()) {
final ClientCollection col = (ClientCollection) colit.next(); final ClientCollection col = (ClientCollection) element2;
log.debug(" Collection: " + col.getTitle() + " Accepts: " + col.getAccepts()); log.debug(" Collection: " + col.getTitle() + " Accepts: " + col.getAccepts());
log.debug(" href: " + col.getHrefResolved()); log.debug(" href: " + col.getHrefResolved());
assertNotNull(col.getTitle()); assertNotNull(col.getTitle());
@ -124,18 +130,19 @@ public class AtomClientTest extends TestCase {
} }
/** /**
* Tests that entries can be posted and removed in all collections that accept entries. Fails if no collections found that accept entries. * Tests that entries can be posted and removed in all collections that accept entries. Fails if
* no collections found that accept entries.
*/ */
public void testSimpleEntryPostAndRemove() throws Exception { public void testSimpleEntryPostAndRemove() throws Exception {
assertNotNull(service); assertNotNull(service);
assertTrue(service.getWorkspaces().size() > 0); assertTrue(service.getWorkspaces().size() > 0);
int count = 0; int count = 0;
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) { for (final Object element : service.getWorkspaces()) {
final ClientWorkspace space = (ClientWorkspace) it.next(); final ClientWorkspace space = (ClientWorkspace) element;
assertNotNull(space.getTitle()); assertNotNull(space.getTitle());
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) { for (final Object element2 : space.getCollections()) {
final ClientCollection col = (ClientCollection) colit.next(); final ClientCollection col = (ClientCollection) element2;
if (col.accepts(Collection.ENTRY_TYPE)) { if (col.accepts(Collection.ENTRY_TYPE)) {
// we found a collection that accepts entries, so post one // we found a collection that accepts entries, so post one
@ -171,18 +178,19 @@ public class AtomClientTest extends TestCase {
} }
/** /**
* Tests that entries can be posted, updated and removed in all collections that accept entries. Fails if no collections found that accept entries. * Tests that entries can be posted, updated and removed in all collections that accept entries.
* Fails if no collections found that accept entries.
*/ */
public void testSimpleEntryPostUpdateAndRemove() throws Exception { public void testSimpleEntryPostUpdateAndRemove() throws Exception {
assertNotNull(service); assertNotNull(service);
assertTrue(service.getWorkspaces().size() > 0); assertTrue(service.getWorkspaces().size() > 0);
int count = 0; int count = 0;
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) { for (final Object element : service.getWorkspaces()) {
final ClientWorkspace space = (ClientWorkspace) it.next(); final ClientWorkspace space = (ClientWorkspace) element;
assertNotNull(space.getTitle()); assertNotNull(space.getTitle());
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) { for (final Object element2 : space.getCollections()) {
final ClientCollection col = (ClientCollection) colit.next(); final ClientCollection col = (ClientCollection) element2;
if (col.accepts(Collection.ENTRY_TYPE)) { if (col.accepts(Collection.ENTRY_TYPE)) {
// we found a collection that accepts entries, so post one // we found a collection that accepts entries, so post one
@ -253,18 +261,19 @@ public class AtomClientTest extends TestCase {
} }
/** /**
* Test posting an entry to every available collection with a fixed and an unfixed category if server support allows, then cleanup. * Test posting an entry to every available collection with a fixed and an unfixed category if
* server support allows, then cleanup.
*/ */
public void testEntryPostWithCategories() throws Exception { public void testEntryPostWithCategories() throws Exception {
assertNotNull(service); assertNotNull(service);
assertTrue(service.getWorkspaces().size() > 0); assertTrue(service.getWorkspaces().size() > 0);
int count = 0; int count = 0;
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) { for (final Object element2 : service.getWorkspaces()) {
final ClientWorkspace space = (ClientWorkspace) it.next(); final ClientWorkspace space = (ClientWorkspace) element2;
assertNotNull(space.getTitle()); assertNotNull(space.getTitle());
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) { for (final Object element3 : space.getCollections()) {
final ClientCollection col = (ClientCollection) colit.next(); final ClientCollection col = (ClientCollection) element3;
if (col.accepts(Collection.ENTRY_TYPE)) { if (col.accepts(Collection.ENTRY_TYPE)) {
// we found a collection that accepts GIF, so post one // we found a collection that accepts GIF, so post one
@ -278,12 +287,12 @@ public class AtomClientTest extends TestCase {
// if possible, pick one fixed an un unfixed category // if possible, pick one fixed an un unfixed category
Category fixedCat = null; Category fixedCat = null;
Category unfixedCat = null; Category unfixedCat = null;
final List entryCats = new ArrayList(); final List<Category> entryCats = new ArrayList<Category>();
for (int i = 0; i < col.getCategories().size(); i++) { for (int i = 0; i < col.getCategories().size(); i++) {
final Categories cats = (Categories) col.getCategories().get(i); final Categories cats = col.getCategories().get(i);
if (cats.isFixed() && fixedCat == null) { if (cats.isFixed() && fixedCat == null) {
final String scheme = cats.getScheme(); final String scheme = cats.getScheme();
fixedCat = (Category) cats.getCategories().get(0); fixedCat = cats.getCategories().get(0);
if (fixedCat.getScheme() == null) { if (fixedCat.getScheme() == null) {
fixedCat.setScheme(scheme); fixedCat.setScheme(scheme);
} }
@ -352,12 +361,12 @@ public class AtomClientTest extends TestCase {
assertNotNull(service); assertNotNull(service);
assertTrue(service.getWorkspaces().size() > 0); assertTrue(service.getWorkspaces().size() > 0);
int count = 0; int count = 0;
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) { for (final Object element : service.getWorkspaces()) {
final ClientWorkspace space = (ClientWorkspace) it.next(); final ClientWorkspace space = (ClientWorkspace) element;
assertNotNull(space.getTitle()); assertNotNull(space.getTitle());
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) { for (final Object element2 : space.getCollections()) {
final ClientCollection col = (ClientCollection) colit.next(); final ClientCollection col = (ClientCollection) element2;
if (col.accepts("image/gif")) { if (col.accepts("image/gif")) {
// we found a collection that accepts GIF, so post one // we found a collection that accepts GIF, so post one
@ -390,17 +399,22 @@ public class AtomClientTest extends TestCase {
/** /**
* Post X media entries each media collection found, test paging, then cleanup. * Post X media entries each media collection found, test paging, then cleanup.
* *
* public void testMediaPaging() throws Exception { ClientAtomService service = getClientAtomService(); assertNotNull(service); * public void testMediaPaging() throws Exception { ClientAtomService service =
* assertTrue(service.getWorkspaces().size() > 0); int count = 0; for (Iterator it = service.getWorkspaces().iterator(); it.hasNext();) { ClientWorkspace * getClientAtomService(); assertNotNull(service); assertTrue(service.getWorkspaces().size() >
* space = (ClientWorkspace) it.next(); assertNotNull(space.getTitle()); * 0); int count = 0; for (Iterator it = service.getWorkspaces().iterator(); it.hasNext();) {
* ClientWorkspace space = (ClientWorkspace) it.next(); assertNotNull(space.getTitle());
* *
* for (Iterator colit = space.getCollections().iterator(); colit.hasNext();) { ClientCollection col = (ClientCollection) colit.next(); if * for (Iterator colit = space.getCollections().iterator(); colit.hasNext();) { ClientCollection
* (col.accepts("image/gif")) { * col = (ClientCollection) colit.next(); if (col.accepts("image/gif")) {
* *
* // we found a collection that accepts GIF, so post 100 of them List posted = new ArrayList(); for (int i=0; i<maxPagingEntries; i++) { ClientMediaEntry * // we found a collection that accepts GIF, so post 100 of them List posted = new ArrayList();
* m1 = col.createMediaEntry("duke"+count, "duke"+count, "image/gif", new FileInputStream("test/testdata/duke-wave-shadow.gif")); col.addEntry(m1); * for (int i=0; i<maxPagingEntries; i++) { ClientMediaEntry m1 =
* posted.add(m1); } int entryCount = 0; for (Iterator iter = col.getEntries(); iter.hasNext();) { ClientMediaEntry entry = (ClientMediaEntry) iter.next(); * col.createMediaEntry("duke"+count, "duke"+count, "image/gif", new
* entryCount++; } for (Iterator delit = posted.iterator(); delit.hasNext();) { ClientEntry entry = (ClientEntry) delit.next(); entry.remove(); } * FileInputStream("test/testdata/duke-wave-shadow.gif")); col.addEntry(m1); posted.add(m1); }
* assertTrue(entryCount >= maxPagingEntries); count++; break; } } } assertTrue(count > 0); } * int entryCount = 0; for (Iterator iter = col.getEntries(); iter.hasNext();) {
* ClientMediaEntry entry = (ClientMediaEntry) iter.next(); entryCount++; } for (Iterator delit
* = posted.iterator(); delit.hasNext();) { ClientEntry entry = (ClientEntry) delit.next();
* entry.remove(); } assertTrue(entryCount >= maxPagingEntries); count++; break; } } }
* assertTrue(count > 0); }
*/ */
} }

View file

@ -21,9 +21,10 @@ import junit.framework.Test;
import junit.framework.TestCase; import junit.framework.TestCase;
import junit.framework.TestSuite; import junit.framework.TestSuite;
import com.sun.syndication.feed.atom.Content;
import org.junit.Ignore; import org.junit.Ignore;
import com.sun.syndication.feed.atom.Content;
/** /**
* Simple APP test designed to run against Blogger.com. * Simple APP test designed to run against Blogger.com.
*/ */
@ -31,7 +32,8 @@ import org.junit.Ignore;
public class BloggerDotComTest extends TestCase { public class BloggerDotComTest extends TestCase {
private final String collectionURI = "http://www.blogger.com/feeds/BLOGID/posts/default"; private final String collectionURI = "http://www.blogger.com/feeds/BLOGID/posts/default";
private final String atomServiceURI = "http://www.blogger.com/feeds/default/blogs?alt=atom-service"; // private final String atomServiceURI =
// "http://www.blogger.com/feeds/default/blogs?alt=atom-service";
private final String email = "EMAIL"; private final String email = "EMAIL";
private final String password = "PASSWORD"; private final String password = "PASSWORD";
@ -61,8 +63,8 @@ public class BloggerDotComTest extends TestCase {
ClientCollection col = AtomClientFactory.getCollection(collectionURI, new GDataAuthStrategy(email, password, "blogger")); ClientCollection col = AtomClientFactory.getCollection(collectionURI, new GDataAuthStrategy(email, password, "blogger"));
assertNotNull(col); assertNotNull(col);
int count = 0; int count = 0;
for (final Iterator it = col.getEntries(); it.hasNext();) { for (final Iterator<ClientEntry> it = col.getEntries(); it.hasNext();) {
final ClientEntry entry = (ClientEntry) it.next(); final ClientEntry entry = it.next();
assertNotNull(entry); assertNotNull(entry);
count++; count++;
} }

View file

@ -15,9 +15,6 @@
*/ */
package org.rometools.propono.atom.common; package org.rometools.propono.atom.common;
import java.io.FileInputStream;
import java.util.Iterator;
import junit.framework.Test; import junit.framework.Test;
import junit.framework.TestCase; import junit.framework.TestCase;
import junit.framework.TestSuite; import junit.framework.TestSuite;
@ -26,8 +23,6 @@ import org.jdom2.Document;
import org.jdom2.Element; import org.jdom2.Element;
import org.jdom2.input.SAXBuilder; import org.jdom2.input.SAXBuilder;
import com.sun.syndication.feed.atom.Category;
/** /**
* Tests reading and writing of service document, no server needed. * Tests reading and writing of service document, no server needed.
*/ */
@ -65,25 +60,19 @@ public class AtomServiceTest extends TestCase {
int workspaceCount = 0; int workspaceCount = 0;
// Verify that service contains expected workspaces, collections and categories // Verify that service contains expected workspaces, collections and categories
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) { for (final Object element : service.getWorkspaces()) {
final Workspace space = (Workspace) it.next(); final Workspace space = (Workspace) element;
assertNotNull(space.getTitle()); assertNotNull(space.getTitle());
workspaceCount++; workspaceCount++;
int collectionCount = 0; for (final Object element2 : space.getCollections()) {
final Collection col = (Collection) element2;
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) {
final Collection col = (Collection) colit.next();
assertNotNull(col.getTitle()); assertNotNull(col.getTitle());
assertNotNull(col.getHrefResolved()); assertNotNull(col.getHrefResolved());
collectionCount++;
int catCount = 0; int catCount = 0;
if (col.getCategories().size() > 0) { if (col.getCategories().size() > 0) {
for (final Iterator catsit = col.getCategories().iterator(); catsit.hasNext();) { for (final Object element3 : col.getCategories()) {
final Categories cats = (Categories) catsit.next(); final Categories cats = (Categories) element3;
for (final Iterator catit = cats.getCategories().iterator(); catit.hasNext();) { catCount += cats.getCategories().size();
final Category cat = (Category) catit.next();
catCount++;
}
assertTrue(catCount > 0); assertTrue(catCount > 0);
} }
} }

View file

@ -51,7 +51,7 @@ public class CollectionTest extends TestCase {
assertTrue(col.accepts("image/png")); assertTrue(col.accepts("image/png"));
assertFalse(col.accepts("test/html")); assertFalse(col.accepts("test/html"));
final List accepts = new ArrayList(); final List<String> accepts = new ArrayList<String>();
accepts.add("image/*"); accepts.add("image/*");
accepts.add("text/*"); accepts.add("text/*");
col.setAccepts(accepts); col.setAccepts(accepts);

View file

@ -16,25 +16,22 @@
*/ */
package org.rometools.propono.atom.server; package org.rometools.propono.atom.server;
import com.sun.syndication.feed.atom.Category; import static junit.framework.TestCase.assertEquals;
import com.sun.syndication.feed.atom.Content; import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertTrue;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.logging.ConsoleHandler; import java.util.logging.ConsoleHandler;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertTrue;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mortbay.http.HttpContext; import org.mortbay.http.HttpContext;
import org.mortbay.http.HttpServer; import org.mortbay.http.HttpServer;
import org.mortbay.http.SocketListener; import org.mortbay.http.SocketListener;
@ -48,8 +45,12 @@ import org.rometools.propono.atom.client.ClientMediaEntry;
import org.rometools.propono.atom.client.ClientWorkspace; import org.rometools.propono.atom.client.ClientWorkspace;
import org.rometools.propono.atom.common.Categories; import org.rometools.propono.atom.common.Categories;
import org.rometools.propono.atom.common.Collection; import org.rometools.propono.atom.common.Collection;
import org.rometools.propono.atom.common.Workspace;
import org.rometools.propono.utils.ProponoException; import org.rometools.propono.utils.ProponoException;
import com.sun.syndication.feed.atom.Category;
import com.sun.syndication.feed.atom.Content;
/** /**
* Test Propono Atom Client against Atom Server via Jetty. Extends <code>AtomClientTest</code> to * Test Propono Atom Client against Atom Server via Jetty. Extends <code>AtomClientTest</code> to
* start Jetty server, run tests and then stop the Jetty server. * start Jetty server, run tests and then stop the Jetty server.
@ -100,8 +101,7 @@ public class AtomClientServerTest {
server.addContext(context); server.addContext(context);
server.start(); server.start();
service = AtomClientFactory.getAtomService(getEndpoint(), service = AtomClientFactory.getAtomService(getEndpoint(), new BasicAuthStrategy(getUsername(), getPassword()));
new BasicAuthStrategy(getUsername(), getPassword()));
} }
@After @After
@ -129,9 +129,7 @@ public class AtomClientServerTest {
} }
private ServletHandler createServletHandler() { private ServletHandler createServletHandler() {
System.setProperty( System.setProperty("org.rometools.propono.atom.server.AtomHandlerFactory", "org.rometools.propono.atom.server.TestAtomHandlerFactory");
"org.rometools.propono.atom.server.AtomHandlerFactory",
"org.rometools.propono.atom.server.TestAtomHandlerFactory");
final ServletHandler servlets = new ServletHandler(); final ServletHandler servlets = new ServletHandler();
servlets.addServlet("app", "/app/*", "org.rometools.propono.atom.server.AtomServlet"); servlets.addServlet("app", "/app/*", "org.rometools.propono.atom.server.AtomServlet");
return servlets; return servlets;
@ -150,12 +148,12 @@ public class AtomClientServerTest {
public void testGetAtomService() throws Exception { public void testGetAtomService() throws Exception {
assertNotNull(service); assertNotNull(service);
assertTrue(service.getWorkspaces().size() > 0); assertTrue(service.getWorkspaces().size() > 0);
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) { for (final Workspace workspace : service.getWorkspaces()) {
final ClientWorkspace space = (ClientWorkspace) it.next(); final ClientWorkspace space = (ClientWorkspace) workspace;
assertNotNull(space.getTitle()); assertNotNull(space.getTitle());
log.debug("Workspace: " + space.getTitle()); log.debug("Workspace: " + space.getTitle());
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) { for (final Object element : space.getCollections()) {
final ClientCollection col = (ClientCollection) colit.next(); final ClientCollection col = (ClientCollection) element;
log.debug(" Collection: " + col.getTitle() + " Accepts: " + col.getAccepts()); log.debug(" Collection: " + col.getTitle() + " Accepts: " + col.getAccepts());
log.debug(" href: " + col.getHrefResolved()); log.debug(" href: " + col.getHrefResolved());
assertNotNull(col.getTitle()); assertNotNull(col.getTitle());
@ -172,12 +170,12 @@ public class AtomClientServerTest {
assertNotNull(service); assertNotNull(service);
assertTrue(service.getWorkspaces().size() > 0); assertTrue(service.getWorkspaces().size() > 0);
int count = 0; int count = 0;
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) { for (final Object element : service.getWorkspaces()) {
final ClientWorkspace space = (ClientWorkspace) it.next(); final ClientWorkspace space = (ClientWorkspace) element;
assertNotNull(space.getTitle()); assertNotNull(space.getTitle());
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) { for (final Object element2 : space.getCollections()) {
final ClientCollection col = (ClientCollection) colit.next(); final ClientCollection col = (ClientCollection) element2;
if (col.accepts(Collection.ENTRY_TYPE)) { if (col.accepts(Collection.ENTRY_TYPE)) {
// we found a collection that accepts entries, so post one // we found a collection that accepts entries, so post one
@ -221,12 +219,12 @@ public class AtomClientServerTest {
assertNotNull(service); assertNotNull(service);
assertTrue(service.getWorkspaces().size() > 0); assertTrue(service.getWorkspaces().size() > 0);
int count = 0; int count = 0;
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) { for (final Object element : service.getWorkspaces()) {
final ClientWorkspace space = (ClientWorkspace) it.next(); final ClientWorkspace space = (ClientWorkspace) element;
assertNotNull(space.getTitle()); assertNotNull(space.getTitle());
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) { for (final Object element2 : space.getCollections()) {
final ClientCollection col = (ClientCollection) colit.next(); final ClientCollection col = (ClientCollection) element2;
if (col.accepts(Collection.ENTRY_TYPE)) { if (col.accepts(Collection.ENTRY_TYPE)) {
// we found a collection that accepts entries, so post one // we found a collection that accepts entries, so post one
@ -306,12 +304,12 @@ public class AtomClientServerTest {
assertNotNull(service); assertNotNull(service);
assertTrue(service.getWorkspaces().size() > 0); assertTrue(service.getWorkspaces().size() > 0);
int count = 0; int count = 0;
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) { for (final Object element2 : service.getWorkspaces()) {
final ClientWorkspace space = (ClientWorkspace) it.next(); final ClientWorkspace space = (ClientWorkspace) element2;
assertNotNull(space.getTitle()); assertNotNull(space.getTitle());
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) { for (final Object element3 : space.getCollections()) {
final ClientCollection col = (ClientCollection) colit.next(); final ClientCollection col = (ClientCollection) element3;
if (col.accepts(Collection.ENTRY_TYPE)) { if (col.accepts(Collection.ENTRY_TYPE)) {
// we found a collection that accepts GIF, so post one // we found a collection that accepts GIF, so post one
@ -325,12 +323,12 @@ public class AtomClientServerTest {
// if possible, pick one fixed an un unfixed category // if possible, pick one fixed an un unfixed category
Category fixedCat = null; Category fixedCat = null;
Category unfixedCat = null; Category unfixedCat = null;
final List entryCats = new ArrayList(); final List<Category> entryCats = new ArrayList<Category>();
for (int i = 0; i < col.getCategories().size(); i++) { for (int i = 0; i < col.getCategories().size(); i++) {
final Categories cats = (Categories) col.getCategories().get(i); final Categories cats = col.getCategories().get(i);
if (cats.isFixed() && fixedCat == null) { if (cats.isFixed() && fixedCat == null) {
final String scheme = cats.getScheme(); final String scheme = cats.getScheme();
fixedCat = (Category) cats.getCategories().get(0); fixedCat = cats.getCategories().get(0);
if (fixedCat.getScheme() == null) { if (fixedCat.getScheme() == null) {
fixedCat.setScheme(scheme); fixedCat.setScheme(scheme);
} }
@ -399,12 +397,12 @@ public class AtomClientServerTest {
assertNotNull(service); assertNotNull(service);
assertTrue(service.getWorkspaces().size() > 0); assertTrue(service.getWorkspaces().size() > 0);
int count = 0; int count = 0;
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) { for (final Object element : service.getWorkspaces()) {
final ClientWorkspace space = (ClientWorkspace) it.next(); final ClientWorkspace space = (ClientWorkspace) element;
assertNotNull(space.getTitle()); assertNotNull(space.getTitle());
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) { for (final Object element2 : space.getCollections()) {
final ClientCollection col = (ClientCollection) colit.next(); final ClientCollection col = (ClientCollection) element2;
if (col.accepts("image/gif")) { if (col.accepts("image/gif")) {
// we found a collection that accepts GIF, so post one // we found a collection that accepts GIF, so post one

View file

@ -22,13 +22,15 @@ import junit.framework.Test;
import junit.framework.TestCase; import junit.framework.TestCase;
import junit.framework.TestSuite; import junit.framework.TestSuite;
import org.junit.Ignore;
import org.rometools.propono.blogclient.Blog.Collection;
import org.rometools.propono.utils.Utilities; import org.rometools.propono.utils.Utilities;
import com.sun.syndication.io.impl.Atom10Parser; import com.sun.syndication.io.impl.Atom10Parser;
import org.junit.Ignore;
/** /**
* Tests Atom and MetaWeblog API CRUD via BlogClient. Exclude this from automated tests because it requires a live blog server. * Tests Atom and MetaWeblog API CRUD via BlogClient. Exclude this from automated tests because it
* requires a live blog server.
*/ */
@Ignore @Ignore
public class SimpleBlogClientTest extends TestCase { public class SimpleBlogClientTest extends TestCase {
@ -37,7 +39,7 @@ public class SimpleBlogClientTest extends TestCase {
// private String atomEndpoint = "http://localhost:8080/roller/roller-services/app"; // private String atomEndpoint = "http://localhost:8080/roller/roller-services/app";
private final String atomEndpoint = "http://localhost:8080/sample-atomserver/app"; private final String atomEndpoint = "http://localhost:8080/sample-atomserver/app";
private final String endpoint = "http://localhost:8080/atom-fileserver/app"; // private final String endpoint = "http://localhost:8080/atom-fileserver/app";
private final String username = "admin"; private final String username = "admin";
private final String password = "admin"; private final String password = "admin";
@ -65,8 +67,7 @@ public class SimpleBlogClientTest extends TestCase {
final BlogConnection conn = BlogConnectionFactory.getBlogConnection(type, endpoint, username, password); final BlogConnection conn = BlogConnectionFactory.getBlogConnection(type, endpoint, username, password);
int blogCount = 0; int blogCount = 0;
for (final Iterator it = conn.getBlogs().iterator(); it.hasNext();) { for (final Blog blog : conn.getBlogs()) {
final Blog blog = (Blog) it.next();
System.out.println(blog.getName()); System.out.println(blog.getName());
blogCount++; blogCount++;
} }
@ -96,7 +97,7 @@ public class SimpleBlogClientTest extends TestCase {
final String title1 = "Test content"; final String title1 = "Test content";
final String content1 = "Test content"; final String content1 = "Test content";
final Blog blog = (Blog) conn.getBlogs().get(0); final Blog blog = conn.getBlogs().get(0);
BlogEntry entry = blog.newEntry(); BlogEntry entry = blog.newEntry();
entry.setTitle(title1); entry.setTitle(title1);
entry.setContent(new BlogEntry.Content(content1)); entry.setContent(new BlogEntry.Content(content1));
@ -131,12 +132,12 @@ public class SimpleBlogClientTest extends TestCase {
assertTrue(conn.getBlogs().size() > 0); assertTrue(conn.getBlogs().size() > 0);
int count = 0; int count = 0;
for (final Iterator it = conn.getBlogs().iterator(); it.hasNext();) { for (final Blog blog2 : conn.getBlogs()) {
final Blog blog = (Blog) it.next(); final Blog blog = blog2;
assertNotNull(blog.getName()); assertNotNull(blog.getName());
for (final Iterator colit = blog.getCollections().iterator(); colit.hasNext();) { for (final Collection collection : blog.getCollections()) {
final Blog.Collection col = (Blog.Collection) colit.next(); final Blog.Collection col = collection;
if (col.accepts("image/gif")) { if (col.accepts("image/gif")) {
// we found a collection that accepts GIF, so post one // we found a collection that accepts GIF, so post one
@ -184,7 +185,7 @@ public class SimpleBlogClientTest extends TestCase {
final String title1 = "Test content"; final String title1 = "Test content";
final String content1 = "Test content"; final String content1 = "Test content";
final Blog blog = (Blog) conn.getBlogs().get(0); final Blog blog = conn.getBlogs().get(0);
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
final BlogEntry entry = blog.newEntry(); final BlogEntry entry = blog.newEntry();