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

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -16,7 +16,6 @@
package org.rometools.propono.atom.client;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
@ -36,19 +35,22 @@ import com.sun.syndication.feed.atom.Entry;
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
* 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.Workspace}s.
* This class models an Atom Publising Protocol Service Document. It extends the common
* {@link com.sun.syndication.propono.atom.common.Collection} class to add 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.Workspace}s.
*/
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 HttpClient httpClient = null;
private AuthStrategy authStrategy = null;
/**
* Create Atom blog service instance for specified URL and user account.
*
*
* @param url End-point URL of Atom service
*/
ClientAtomService(final String uri, final AuthStrategy authStrategy) throws ProponoException {
@ -103,13 +105,13 @@ public class ClientAtomService extends AtomService {
httpClient.executeMethod(method);
final SAXBuilder builder = new SAXBuilder();
String doc = method.getResponseBodyAsString();
logger.debug(doc);
final String doc = method.getResponseBodyAsString();
LOGGER.debug(doc);
return builder.build(method.getResponseBodyAsStream());
} catch (final Throwable t) {
final String msg = "ERROR retrieving Atom Service Document, code: " + code;
logger.debug(msg, t);
LOGGER.debug(msg, t);
throw new ProponoException(msg, t);
} finally {
if (method != null) {
@ -121,10 +123,8 @@ public class ClientAtomService extends AtomService {
/** Deserialize an Atom service XML document into an object */
private void parseAtomServiceDocument(final Document document) throws ProponoException {
final Element root = document.getRootElement();
final List spaces = root.getChildren("workspace", AtomService.ATOM_PROTOCOL);
final Iterator iter = spaces.iterator();
while (iter.hasNext()) {
final Element e = (Element) iter.next();
final List<Element> spaces = root.getChildren("workspace", AtomService.ATOM_PROTOCOL);
for (final Element e : spaces) {
addWorkspace(new ClientWorkspace(e, this, uri));
}
}
@ -135,4 +135,5 @@ public class ClientAtomService extends AtomService {
HttpClient getHttpClient() {
return httpClient;
}
}

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -17,7 +17,6 @@ package org.rometools.propono.atom.client;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
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.MultiThreadedHttpConnectionManager;
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.rometools.propono.atom.common.AtomService;
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;
/**
* 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 {
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 HttpClient httpClient = null;
private AuthStrategy authStrategy = null;
private ClientWorkspace workspace = null;
private ClientAtomService service = null;
@ -85,15 +81,17 @@ 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);
}
/**
* 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.
*/
public ClientEntry getEntry(final String uri) throws ProponoException {
@ -133,7 +131,7 @@ public class ClientCollection extends Collection {
/**
* Create new entry associated with collection, but do not save to server.
*
*
* @throws ProponoException if collecton is not writable.
*/
public ClientEntry createEntry() throws ProponoException {
@ -144,9 +142,10 @@ 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
* properties of the entry that is returned.
*
* 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 properties of the entry that is
* returned.
*
* @param title Title to used for uploaded file.
* @param slug String to be used in file-name of stored file
* @param contentType MIME content-type of file.
@ -161,9 +160,10 @@ 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
* properties of the entry that is returned.
*
* 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 properties of the entry that is
* returned.
*
* @param title Title to used for uploaded file.
* @param slug String to be used in file-name of stored file
* @param contentType MIME content-type of file.
@ -178,8 +178,9 @@ 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.
* @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) {
for (final Iterator it = acceptElems.iterator(); it.hasNext();) {
final Element acceptElem = (Element) it.next();
for (final Element acceptElem : acceptElems) {
addAccept(acceptElem.getTextTrim());
}
}
// Loop to parse <app:categories> element to Categories objects
final List catsElems = element.getChildren("categories", AtomService.ATOM_PROTOCOL);
for (final Iterator catsIter = catsElems.iterator(); catsIter.hasNext();) {
final Element catsElem = (Element) catsIter.next();
final List<Element> catsElems = element.getChildren("categories", AtomService.ATOM_PROTOCOL);
for (final Element catsElem : catsElems) {
final Categories cats = new ClientCategories(catsElem, this);
addCategories(cats);
}
}
}

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -20,6 +20,7 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
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.io.impl.Atom10Generator;
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 {
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 ClientCollection collection = null;
protected boolean partial = false;
public ClientEntry(final ClientAtomService service, final ClientCollection collection) {
super();
this.service = service;
this.collection = collection;
}
public ClientEntry(final ClientAtomService service, final ClientCollection collection, final Entry entry, final boolean partial) throws ProponoException {
super();
this.service = service;
this.collection = collection;
this.partial = partial;
@ -75,30 +75,33 @@ public class ClientEntry extends Entry {
/**
* Set content of entry.
*
*
* @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) {
final Content newContent = new Content();
newContent.setType(type == null ? Content.HTML : type);
newContent.setValue(contentString);
final ArrayList contents = new ArrayList();
final ArrayList<Content> contents = new ArrayList<Content>();
contents.add(newContent);
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) {
final ArrayList contents = new ArrayList();
final ArrayList<Content> contents = new ArrayList<Content>();
contents.add(c);
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() {
if (getContents() != null && getContents().size() > 0) {
@ -123,10 +126,12 @@ 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
* 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
* {@link com.sun.syndication.propono.atom.common.Collection} or {@link com.sun.syndication.propono.atom.common.AtomService}.
*
* 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 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 {@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.
*/
public void update() throws ProponoException {
@ -149,7 +154,7 @@ public class ClientEntry extends Entry {
} catch (final Exception e) {
final String msg = "ERROR: updating entry, HTTP code: " + code;
logger.debug(msg, e);
LOGGER.debug(msg, e);
throw new ProponoException(msg, e);
} finally {
method.releaseConnection();
@ -216,16 +221,16 @@ public class ClientEntry extends Entry {
} catch (final Exception e) {
final String msg = "ERROR: saving entry, HTTP code: " + code;
logger.debug(msg, e);
LOGGER.debug(msg, e);
throw new ProponoException(msg, e);
} finally {
method.releaseConnection();
}
final Header locationHeader = method.getResponseHeader("Location");
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) {
final List links = getOtherLinks();
final List<Link> links = getOtherLinks();
final Link link = new Link();
link.setHref(locationHeader.getValue());
link.setRel("edit");
@ -252,7 +257,7 @@ public class ClientEntry extends Entry {
}
@Override
public void setCreated(Date d) {
public void setCreated(final Date d) {
// protected against null created property (an old Atom 0.3 property)
if (d != null) {
super.setCreated(d);

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -47,10 +47,13 @@ import com.sun.syndication.io.impl.Atom10Generator;
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 {
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 byte[] bytes;
@ -76,7 +79,7 @@ public class ClientMediaEntry extends ClientEntry {
setSlug(slug);
final Content content = new Content();
content.setType(contentType);
final List contents = new ArrayList();
final List<Content> contents = new ArrayList<Content>();
contents.add(content);
setContents(contents);
}
@ -89,14 +92,14 @@ public class ClientMediaEntry extends ClientEntry {
setSlug(slug);
final Content content = new Content();
content.setType(contentType);
final List contents = new ArrayList();
final List<Content> contents = new ArrayList<Content>();
contents.add(content);
setContents(contents);
}
/**
* Get bytes of media resource associated with entry.
*
*
* @return Bytes or null if none available or if entry uses an InputStream instead.
*/
public byte[] getBytes() {
@ -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) {
if (inputStream != null) {
@ -115,7 +119,7 @@ public class ClientMediaEntry extends ClientEntry {
/**
* Get input stream for media resource associated with this entry.
*
*
* @return InputStream or null if none available or if entry uses bytes instead.
*/
public InputStream getInputStream() {
@ -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) {
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() {
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 {
if (getContents() != null && getContents().size() > 0) {
@ -237,8 +244,6 @@ public class ClientMediaEntry extends ClientEntry {
setCollection(col);
final EntityEnclosingMethod method = new PostMethod(col.getHrefResolved());
getCollection().addAuthentication(method);
final StringWriter sw = new StringWriter();
final boolean error = false;
try {
final Content c = getContents().get(0);
if (inputStream != null) {
@ -274,9 +279,9 @@ public class ClientMediaEntry extends ClientEntry {
}
final Header locationHeader = method.getResponseHeader("Location");
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) {
final List links = getOtherLinks();
final List<Link> links = getOtherLinks();
final Link link = new Link();
link.setHref(locationHeader.getValue());
link.setRel("edit");

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -15,7 +15,6 @@
*/
package org.rometools.propono.atom.client;
import java.util.Iterator;
import java.util.List;
import org.jdom2.Element;
@ -24,10 +23,13 @@ import org.rometools.propono.atom.common.Workspace;
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
* {@link com.sun.syndication.propono.atom.client.ClientCollection} objects instead of common {@link com.sun.syndication.propono.atom.common.Collection}s.
* Represents Atom protocol workspace on client-side. It extends the common
* {@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 {
private ClientAtomService atomService = null;
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) {
setTitleType(titleElem.getAttribute("type", AtomService.ATOM_FORMAT).getValue());
}
final List collections = element.getChildren("collection", AtomService.ATOM_PROTOCOL);
final Iterator iter = collections.iterator();
while (iter.hasNext()) {
final Element e = (Element) iter.next();
final List<Element> collections = element.getChildren("collection", AtomService.ATOM_PROTOCOL);
for (final Element e : collections) {
addCollection(new ClientCollection(e, this, baseURI));
}
}
}

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -34,16 +34,15 @@ import com.sun.syndication.io.WireFeedInput;
/**
* Enables iteration over entries in Atom protocol collection.
*/
public class EntryIterator implements Iterator {
static final Log logger = LogFactory.getLog(EntryIterator.class);
public class EntryIterator implements Iterator<ClientEntry> {
private static final Log LOGGER = LogFactory.getLog(EntryIterator.class);
private final ClientCollection collection;
int maxEntries = 20;
int offset = 0;
Iterator members = null;
Feed col = null;
String collectionURI;
String nextURI;
private Iterator<Entry> members = null;
private Feed col = null;
private final String collectionURI;
private String nextURI;
EntryIterator(final ClientCollection collection) throws ProponoException {
this.collection = collection;
@ -61,7 +60,7 @@ public class EntryIterator implements Iterator {
try {
getNextEntries();
} catch (final Exception ignored) {
logger.error("ERROR getting next entries", ignored);
LOGGER.error("ERROR getting next entries", ignored);
}
}
return members.hasNext();
@ -71,9 +70,9 @@ public class EntryIterator implements Iterator {
* Get next entry in collection.
*/
@Override
public Object next() {
public ClientEntry next() {
if (hasNext()) {
final Entry romeEntry = (Entry) members.next();
final Entry romeEntry = members.next();
try {
if (!romeEntry.isMediaEntry()) {
return new ClientEntry(null, collection, romeEntry, true);
@ -113,18 +112,17 @@ public class EntryIterator implements Iterator {
colGet.releaseConnection();
}
members = col.getEntries().iterator();
offset += col.getEntries().size();
col.getEntries().size();
nextURI = null;
final List altLinks = col.getOtherLinks();
final List<Link> altLinks = col.getOtherLinks();
if (altLinks != null) {
final Iterator iter = altLinks.iterator();
while (iter.hasNext()) {
final Link link = (Link) iter.next();
for (final Link link : altLinks) {
if ("next".equals(link.getRel())) {
nextURI = link.getHref();
}
}
}
}
}

View file

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

View file

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

View file

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

View file

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

View file

@ -18,7 +18,6 @@
package org.rometools.propono.atom.common;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jdom2.Element;
@ -28,13 +27,14 @@ import org.rometools.propono.utils.ProponoException;
* Models an Atom workspace.
*/
public class Workspace {
private String title = null;
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.
*
*
* @param title Title for collection
* @param titleType Content type of title (null for plain text)
*/
@ -48,7 +48,7 @@ public class Workspace {
}
/** Iterate over collections in workspace */
public List getCollections() {
public List<Collection> getCollections() {
return collections;
}
@ -87,14 +87,14 @@ public class Workspace {
/**
* Find collection by title and/or content-type.
*
*
* @param title Title or null to match all titles.
* @param contentType Content-type or null to match all content-types.
* @return First Collection that matches title and/or content-type.
*/
public Collection findCollection(final String title, final String contentType) {
for (final Iterator it = collections.iterator(); it.hasNext();) {
final Collection col = (Collection) it.next();
for (final Object element : collections) {
final Collection col = (Collection) element;
if (title != null && col.accepts(contentType)) {
return col;
} else if (col.accepts(contentType)) {
@ -124,11 +124,10 @@ public class Workspace {
}
element.addContent(titleElem);
final Iterator iter = space.getCollections().iterator();
while (iter.hasNext()) {
final Collection col = (Collection) iter.next();
for (final Collection col : space.getCollections()) {
element.addContent(col.collectionToElement());
}
return element;
}
@ -139,11 +138,10 @@ public class Workspace {
if (titleElem.getAttribute("type", AtomService.ATOM_FORMAT) != null) {
setTitleType(titleElem.getAttribute("type", AtomService.ATOM_FORMAT).getValue());
}
final List collections = element.getChildren("collection", AtomService.ATOM_PROTOCOL);
final Iterator iter = collections.iterator();
while (iter.hasNext()) {
final Element e = (Element) iter.next();
final List<Element> collections = element.getChildren("collection", AtomService.ATOM_PROTOCOL);
for (final Element e : collections) {
addCollection(new Collection(e));
}
}
}

View file

@ -1,6 +1,6 @@
/*
* Copyright 2007 Apache Software Foundation
*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. The ASF licenses this file to You
* under the Apache License, Version 2.0 (the "License"); you may not
@ -36,6 +36,7 @@ import com.sun.syndication.io.ModuleGenerator;
* Creates JDOM representation for APP Extension Module.
*/
public class AppModuleGenerator implements ModuleGenerator {
private static final Namespace APP_NS = Namespace.getNamespace("app", AppModule.URI);
@Override
@ -43,17 +44,17 @@ public class AppModuleGenerator implements ModuleGenerator {
return AppModule.URI;
}
private static final Set NAMESPACES;
private static final Set<Namespace> NAMESPACES;
static {
final Set nss = new HashSet();
final Set<Namespace> nss = new HashSet<Namespace>();
nss.add(APP_NS);
NAMESPACES = Collections.unmodifiableSet(nss);
}
/** Get namespaces associated with this module */
@Override
public Set getNamespaces() {
public Set<Namespace> getNamespaces() {
return NAMESPACES;
}

View file

@ -1,7 +1,7 @@
/*
* Copyright 2007 Apache Software Foundation
* Copyright 2011 The ROME Teams
*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. The ASF licenses this file to You
* under the Apache License, Version 2.0 (the "License"); you may not
@ -29,6 +29,9 @@ import com.sun.syndication.feed.module.ModuleImpl;
* Bean representation of APP module.
*/
public class AppModuleImpl extends ModuleImpl implements AppModule {
private static final long serialVersionUID = 1L;
private boolean draft = false;
private Date edited = null;
@ -62,7 +65,7 @@ public class AppModuleImpl extends ModuleImpl implements AppModule {
/** Get interface class of module */
@Override
public Class getInterface() {
public Class<AppModule> getInterface() {
return AppModule.class;
}
@ -73,4 +76,5 @@ public class AppModuleImpl extends ModuleImpl implements AppModule {
setDraft(m.getDraft());
setEdited(m.getEdited());
}
}

View file

@ -1,6 +1,6 @@
/*
* Copyright 2007 Apache Software Foundation
*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. The ASF licenses this file to You
* under the Apache License, Version 2.0 (the "License"); you may not
@ -22,9 +22,13 @@ package org.rometools.propono.atom.server;
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 {
private static final long serialVersionUID = 1L;
/** Construct new exception */
public AtomException() {
super();

View file

@ -73,7 +73,7 @@ public abstract class AtomHandlerFactory {
public static AtomHandlerFactory newInstance() {
try {
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);
throw new FactoryConfigurationError(e.getException(), e.getMessage());
}

View file

@ -1,6 +1,6 @@
/*
* Copyright 2007 Apache Software Foundation
*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. The ASF licenses this file to You
* under the Apache License, Version 2.0 (the "License"); you may not
@ -22,9 +22,13 @@ package org.rometools.propono.atom.server;
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 {
private static final long serialVersionUID = 1L;
/** Construct new exception */
public AtomNotAuthorizedException() {
super();
@ -50,4 +54,5 @@ public class AtomNotAuthorizedException extends AtomException {
public int getStatus() {
return HttpServletResponse.SC_UNAUTHORIZED;
}
}

View file

@ -1,6 +1,6 @@
/*
* Copyright 2007 Apache Software Foundation
*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. The ASF licenses this file to You
* under the Apache License, Version 2.0 (the "License"); you may not
@ -25,6 +25,9 @@ import javax.servlet.http.HttpServletResponse;
* Exception thrown by AtomHandler in that case a resource is not found.
*/
public class AtomNotFoundException extends AtomException {
private static final long serialVersionUID = 1L;
/** Construct new exception */
public AtomNotFoundException() {
super();

View file

@ -1,6 +1,6 @@
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. The ASF licenses this file to You
* under the Apache License, Version 2.0 (the "License"); you may not
@ -31,6 +31,7 @@ import javax.servlet.http.HttpServletRequest;
* Default request implementation.
*/
public class AtomRequestImpl implements AtomRequest {
private HttpServletRequest wrapped = null;
public AtomRequestImpl(final HttpServletRequest wrapped) {

View file

@ -1,6 +1,6 @@
/*
* Copyright 2007 Apache Software Foundation
*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. The ASF licenses this file to You
* under the Apache License, Version 2.0 (the "License"); you may not
@ -50,12 +50,16 @@ import com.sun.syndication.io.impl.Atom10Generator;
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
* 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.
* Atom Servlet implements Atom protocol by calling an
* {@link com.sun.syndication.propono.atom.server.AtomHandler} implementation. This servlet takes
* 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 {
private static final long serialVersionUID = 1L;
/**
* 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
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
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)) {
// 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
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

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -16,11 +16,15 @@
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 the class of a parser factory specified in the system properties cannot be found or instantiated.
* Thrown when a problem with configuration with the
* {@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 {
private static final long serialVersionUID = 1L;
/**
* <code>Exception</code> that represents the error.
*/
@ -35,8 +39,9 @@ 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.
*/
public FactoryConfigurationError(final String msg) {
@ -45,8 +50,9 @@ 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.
*/
public FactoryConfigurationError(final Exception e) {
@ -55,8 +61,9 @@ 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 msg The detail message.
*/
@ -66,9 +73,10 @@ 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
* exception, if it exists will be returned. Else the name of the encapsulated exception will be returned.
*
* 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 exception, if it exists will be
* returned. Else the name of the encapsulated exception will be returned.
*
* @return The error message.
*/
@Override
@ -84,7 +92,7 @@ public class FactoryConfigurationError extends Error {
/**
* Return the actual exception (if any) that caused this exception to be raised.
*
*
* @return The encapsulated exception, or null if there is none.
*/
public Exception getException() {

View file

@ -22,13 +22,15 @@ import java.io.InputStreamReader;
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 {
private static boolean debug = false;
static Properties cacheProps = new Properties();
static SecuritySupport ss = new SecuritySupport();
static boolean firstTime = true;
private static Properties cacheProps = new Properties();
private static SecuritySupport ss = new SecuritySupport();
private static boolean firstTime = true;
private static void dPrint(final String msg) {
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 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 {
try {
Class providerClass;
Class<?> providerClass;
if (cl == null) {
// If classloader is null Use the bootstrap ClassLoader.
// Thus Class.forName(String) will use the current
@ -80,12 +84,13 @@ class FactoryFinder {
/**
* Finds the implementation Class object in the specified order. Main entry point.
*
*
* @return Class object of factory, never null
*
*
* @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.
*/
static Object find(final String factoryId, final String fallbackClassName) throws ConfigurationError {
@ -117,7 +122,6 @@ class FactoryFinder {
// try to read from /propono.properties
try {
final String javah = ss.getSystemProperty("java.home");
final String configFile = "/propono.properties";
String factoryClassName = null;
if (firstTime) {
@ -162,7 +166,6 @@ class FactoryFinder {
/*
* Try to find provider using Jar Service Provider Mechanism
*
* @return instance of provider class if found or null
*/
private static Object findJarServiceProvider(final String factoryId) throws ConfigurationError {
@ -242,20 +245,4 @@ class FactoryFinder {
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

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -25,14 +25,15 @@ import java.security.PrivilegedActionException;
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 {
ClassLoader getContextClassLoader() {
return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
final PrivilegedAction<ClassLoader> action = new PrivilegedAction<ClassLoader>() {
@Override
public Object run() {
public ClassLoader run() {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
@ -40,35 +41,38 @@ class SecuritySupport {
}
return cl;
}
});
};
return AccessController.doPrivileged(action);
}
String getSystemProperty(final String propName) {
return (String) AccessController.doPrivileged(new PrivilegedAction() {
final PrivilegedAction<String> action = new PrivilegedAction<String>() {
@Override
public Object run() {
public String run() {
return System.getProperty(propName);
}
});
};
return AccessController.doPrivileged(action);
}
FileInputStream getFileInputStream(final File file) throws FileNotFoundException {
try {
return (FileInputStream) AccessController.doPrivileged(new PrivilegedExceptionAction() {
final PrivilegedExceptionAction<FileInputStream> action = new PrivilegedExceptionAction<FileInputStream>() {
@Override
public Object run() throws FileNotFoundException {
public FileInputStream run() throws FileNotFoundException {
return new FileInputStream(file);
}
});
};
return AccessController.doPrivileged(action);
} catch (final PrivilegedActionException e) {
throw (FileNotFoundException) e.getException();
}
}
InputStream getResourceAsStream(final ClassLoader cl, final String name) {
return (InputStream) AccessController.doPrivileged(new PrivilegedAction() {
final PrivilegedAction<InputStream> action = new PrivilegedAction<InputStream>() {
@Override
public Object run() {
public InputStream run() {
InputStream ris;
if (cl == null) {
ris = ClassLoader.getSystemResourceAsStream(name);
@ -77,16 +81,18 @@ class SecuritySupport {
}
return ris;
}
});
};
return AccessController.doPrivileged(action);
}
boolean doesFileExist(final File f) {
return ((Boolean) AccessController.doPrivileged(new PrivilegedAction() {
final PrivilegedAction<Boolean> action = new PrivilegedAction<Boolean>() {
@Override
public Object run() {
return new Boolean(f.exists());
public Boolean run() {
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;
/**
* File-based {@link com.sun.syndication.propono.atom.server.AtomHandler}
* implementation that stores entries and media-entries to disk. Implemented
* using
* File-based {@link com.sun.syndication.propono.atom.server.AtomHandler} implementation that stores
* entries and media-entries to disk. Implemented using
* {@link com.sun.syndication.propono.atom.server.impl.FileBasedAtomService}.
*/
public class FileBasedAtomHandler implements AtomHandler {
private static Log log = LogFactory.getFactory().getInstance(FileBasedAtomHandler.class);
private static String fileStoreDir = null;
private static final Log LOGGER = LogFactory.getFactory().getInstance(FileBasedAtomHandler.class);
private String userName = null;
private String atomProtocolURL = null;
private String contextURI = null;
private final String uploadurl = null;
private FileBasedAtomService service = null;
/**
@ -70,7 +65,7 @@ public class FileBasedAtomHandler implements AtomHandler {
* @param uploaddir File storage upload dir.
*/
public FileBasedAtomHandler(final HttpServletRequest req, final String uploaddir) {
log.debug("ctor");
LOGGER.debug("ctor");
userName = authenticateBASIC(req);
@ -86,9 +81,8 @@ public class FileBasedAtomHandler implements AtomHandler {
}
/**
* Method used for validating user. Developers can overwrite this method and
* use credentials stored in Database or LDAP to confirm if the user is
* allowed to access this service.
* Method used for validating user. Developers can overwrite this method and use credentials
* stored in Database or LDAP to confirm if the user is allowed to access this service.
*
* @param login user submitted login id
* @param password user submitted password
@ -124,8 +118,7 @@ public class FileBasedAtomHandler implements AtomHandler {
/**
* Return introspection document
*
* @throws com.sun.syndication.propono.atom.server.AtomException Unexpected
* exception.
* @throws com.sun.syndication.propono.atom.server.AtomException Unexpected exception.
* @return AtomService object with workspaces and collections.
*/
@Override
@ -136,13 +129,12 @@ public class FileBasedAtomHandler implements AtomHandler {
/**
* Returns null because we use in-line categories.
*
* @throws com.sun.syndication.propono.atom.server.AtomException Unexpected
* exception.
* @throws com.sun.syndication.propono.atom.server.AtomException Unexpected exception.
* @return Categories object
*/
@Override
public Categories getCategories(final AtomRequest areq) throws AtomException {
log.debug("getCollection");
LOGGER.debug("getCollection");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
final String handle = pathInfo[0];
final String collection = pathInfo[1];
@ -155,12 +147,12 @@ public class FileBasedAtomHandler implements AtomHandler {
*
* @param areq Details of HTTP request
* @return ROME feed representing collection.
* @throws com.sun.syndication.propono.atom.server.AtomException Invalid
* collection or other exception.
* @throws com.sun.syndication.propono.atom.server.AtomException Invalid collection or other
* exception.
*/
@Override
public Feed getCollection(final AtomRequest areq) throws AtomException {
log.debug("getCollection");
LOGGER.debug("getCollection");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
final String handle = pathInfo[0];
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
* submitted Atom entry verbatim, but we do set the id and reset the update
* time.
* Create a new entry specified by pathInfo and posted entry. We save the submitted Atom entry
* verbatim, but we do set the id and reset the update time.
*
* @param entry Entry to be added to collection.
* @param areq Details of HTTP request
* @throws com.sun.syndication.propono.atom.server.AtomException On invalid
* collection or other error.
* @throws com.sun.syndication.propono.atom.server.AtomException On invalid collection or other
* error.
* @return Entry as represented on server.
*/
@Override
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 handle = pathInfo[0];
@ -200,13 +191,13 @@ public class FileBasedAtomHandler implements AtomHandler {
* Get entry specified by pathInfo.
*
* @param areq Details of HTTP request
* @throws com.sun.syndication.propono.atom.server.AtomException On invalid
* pathinfo or other error.
* @throws com.sun.syndication.propono.atom.server.AtomException On invalid pathinfo or other
* error.
* @return ROME Entry object.
*/
@Override
public Entry getEntry(final AtomRequest areq) throws AtomException {
log.debug("getEntry");
LOGGER.debug("getEntry");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
final String handle = pathInfo[0];
final String collection = pathInfo[1];
@ -232,7 +223,7 @@ public class FileBasedAtomHandler implements AtomHandler {
*/
@Override
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 handle = pathInfo[0];
final String collection = pathInfo[1];
@ -253,7 +244,7 @@ public class FileBasedAtomHandler implements AtomHandler {
*/
@Override
public void deleteEntry(final AtomRequest areq) throws AtomException {
log.debug("deleteEntry");
LOGGER.debug("deleteEntry");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
final String handle = pathInfo[0];
final String collection = pathInfo[1];
@ -264,15 +255,14 @@ public class FileBasedAtomHandler implements AtomHandler {
} catch (final Exception e) {
final String msg = "ERROR in atom.deleteResource";
log.error(msg, e);
LOGGER.error(msg, e);
throw new AtomException(msg);
}
}
/**
* Store media data in collection specified by pathInfo, create an Atom
* media-link entry to store metadata for the new media file and return that
* entry to the caller.
* Store media data in collection specified by pathInfo, create an Atom media-link entry to
* store metadata for the new media file and return that entry to the caller.
*
* @param areq Details of HTTP request
* @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
final String slug = areq.getHeader("Slug");
if (log.isDebugEnabled()) {
log.debug("postMedia - title: " + entry.getTitle() + " slug:" + slug);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("postMedia - title: " + entry.getTitle() + " slug:" + slug);
}
try {
@ -300,7 +290,7 @@ public class FileBasedAtomHandler implements AtomHandler {
} catch (final Exception e) {
e.printStackTrace();
final String msg = "ERROR reading posted file";
log.error(msg, e);
LOGGER.error(msg, e);
throw new AtomException(msg, e);
} finally {
if (tempFile != null) {
@ -317,13 +307,12 @@ public class FileBasedAtomHandler implements AtomHandler {
/**
* Update the media file part of a media-link entry.
*
* @param areq Details of HTTP request Assuming pathInfo of form
* /user-name/resource/name
* @param areq Details of HTTP request Assuming pathInfo of form /user-name/resource/name
*/
@Override
public void putMedia(final AtomRequest areq) throws AtomException {
log.debug("putMedia");
LOGGER.debug("putMedia");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
final String handle = pathInfo[0];
final String collection = pathInfo[1];
@ -339,7 +328,7 @@ public class FileBasedAtomHandler implements AtomHandler {
@Override
public AtomMediaResource getMediaResource(final AtomRequest areq) throws AtomException {
log.debug("putMedia");
LOGGER.debug("putMedia");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
final String handle = pathInfo[0];
final String collection = pathInfo[1];
@ -370,7 +359,7 @@ public class FileBasedAtomHandler implements AtomHandler {
*/
@Override
public boolean isCategoriesURI(final AtomRequest areq) {
log.debug("isCategoriesDocumentURI");
LOGGER.debug("isCategoriesDocumentURI");
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
if (pathInfo.length == 3 && "categories".equals(pathInfo[2])) {
return true;
@ -383,7 +372,7 @@ public class FileBasedAtomHandler implements AtomHandler {
*/
@Override
public boolean isCollectionURI(final AtomRequest areq) {
log.debug("isCollectionURI");
LOGGER.debug("isCollectionURI");
// workspace/collection-plural
// if length is 2 and points to a valid collection then YES
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
@ -403,7 +392,7 @@ public class FileBasedAtomHandler implements AtomHandler {
*/
@Override
public boolean isEntryURI(final AtomRequest areq) {
log.debug("isEntryURI");
LOGGER.debug("isEntryURI");
// workspace/collection-singular/fsid
// if length is 3 and points to a valid collection then YES
final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
@ -422,7 +411,7 @@ public class FileBasedAtomHandler implements AtomHandler {
*/
@Override
public boolean isMediaEditURI(final AtomRequest areq) {
log.debug("isMediaEditURI");
LOGGER.debug("isMediaEditURI");
// workspace/collection-singular/fsid/media/fsid
// if length is 4, points to a valid collection and fsid is mentioned
// twice then YES
@ -444,7 +433,7 @@ public class FileBasedAtomHandler implements AtomHandler {
* BASIC authentication.
*/
public String authenticateBASIC(final HttpServletRequest request) {
log.debug("authenticateBASIC");
LOGGER.debug("authenticateBASIC");
boolean valid = false;
String userID = null;
String password = null;
@ -469,7 +458,7 @@ public class FileBasedAtomHandler implements AtomHandler {
}
}
} catch (final Exception e) {
log.debug(e);
LOGGER.debug(e);
}
if (valid) {
// For now assume userID as userName

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -34,4 +34,5 @@ public class FileBasedAtomHandlerFactory extends AtomHandlerFactory {
public AtomHandler newAtomHandler(final HttpServletRequest req, final HttpServletResponse res) {
return new FileBasedAtomHandler(req);
}
}

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -24,19 +24,20 @@ import org.rometools.propono.atom.common.AtomService;
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>
* # Define list of collections to be offered
* propono.atomserver.filebased.collections=entries,gifimages
*
*
* # Defines 'entries' collection, accepts entries
* propono.atomserver.filebased.collection.entries.title=Entries
* propono.atomserver.filebased.collection.entries.singular=entry
* propono.atomserver.filebased.collection.entries.plural=entries
* propono.atomserver.filebased.collection.entries.accept=application/atom+xml;type=entry
* propono.atomserver.filebased.collection.entries.categories=general,category1,category2
*
*
* # Defines 'gifimages' collection, accepts only GIF files
* propono.atomserver.filebased.collection.gifimages.title=GIF Images
* propono.atomserver.filebased.collection.gifimages.singular=gif
@ -44,57 +45,59 @@ import org.rometools.propono.utils.Utilities;
* propono.atomserver.filebased.collection.gifimages.accept=image/gif
* propono.atomserver.filebased.collection.gifimages.categories=general,category1,category2
* </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>
* <b>URI structure used for accessing collections and entries</b>
* </p>
*
*
* <p>
* Collection feed (URI allows GET to get collection, POST to add to it)<br/>
* <code>[servlet-context-uri]/app/[workspace-handle]/[collection-plural] </code>
* </p>
*
*
* <p>
* Collection entry (URI allows GET, PUT and DELETE)<br/>
* <code>[servlet-context-uri]/app/[workspace-handle]/[collection-singular]/[entryid] </code>
* </p>
*
*
* <p>
* Collection entry media (URI allows GET, PUT and DELETE)<br/>
* <code>[servlet-context-uri]/app/[workspace-handle]/[collection-singular]/media/[entryid]</code>
* </p>
*
*
* <p>
* Categories URI if not using inline categories (URI allows GET)<br/>
* <code>[servlet-context-uri]/app/[workspace-handle]/[collection-plural]/categories</code>
* </p>
*
*
*
*
* <p>
* <b>Directory structure used to store collections and entries</b>
* </p>
*
*
* <p>
* Collection feed (kept constantly up to date)<br/>
* <code>[servlet-context-dir]/[workspace-handle]/[collection-plural]/feed.xml</code>
* </p>
*
*
* <p>
* Collection entry (individual entries also stored as entry.xml files)<br/>
* <code>[servlet-context-dir]/[workspace-handle]/[collection-plural]/id/entry.xml</code>
* </p>
*
*
* <p>
* Collection entry media (media file stored under entry directory)<br/>
* <code>[servlet-context-dir]/[workspace-handle]/[collection-plural]/id/media/id</code>
* </p>
*/
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 boolean firstTime = true;
@ -181,10 +184,10 @@ public class FileBasedAtomService extends AtomService {
* Find workspace by handle, returns null of not found.
*/
FileBasedWorkspace findWorkspaceByHandle(final String handle) {
return (FileBasedWorkspace) workspaceMap.get(handle);
return workspaceMap.get(handle);
}
FileBasedCollection findCollectionByHandle(final String handle, final String collection) {
return (FileBasedCollection) collectionMap.get(handle + "|" + collection);
return collectionMap.get(handle + "|" + collection);
}
}

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -28,7 +28,6 @@ import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
@ -36,8 +35,6 @@ import java.util.StringTokenizer;
import javax.activation.FileTypeMap;
import javax.activation.MimetypesFileTypeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom2.Document;
import org.jdom2.output.XMLOutputter;
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.Feed;
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.WireFeedInput;
import com.sun.syndication.io.WireFeedOutput;
@ -62,11 +60,11 @@ import com.sun.syndication.io.impl.Atom10Generator;
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
* and deleting Atom entries and media entries.
* File based Atom collection implementation. This is the heart of the file-based Atom service
* implementation. It provides methods for adding, getting updating and deleting Atom entries and
* media entries.
*/
public class FileBasedCollection extends Collection {
private static Log log = LogFactory.getFactory().getInstance(FileBasedCollection.class);
private String handle = null;
private String singular = null;
@ -77,16 +75,17 @@ public class FileBasedCollection extends Collection {
private boolean relativeURIs = false;
private String contextURI = null;
private String contextPath = null;
private String servletPath = null;
private String baseDir = null;
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),
* the base directory for file storage, the content-type range accepted by the collection and the root Atom protocol URI for the service.
*
* 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), 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 handle Workspace handle
* @param collection Collection handle, plural
@ -114,7 +113,6 @@ public class FileBasedCollection extends Collection {
this.baseDir = baseDir;
this.relativeURIs = relativeURIs;
this.contextURI = contextURI;
this.contextPath = contextPath;
this.servletPath = servletPath;
addAccept(accept);
@ -122,7 +120,7 @@ public class FileBasedCollection extends Collection {
/**
* Get feed document representing collection.
*
*
* @throws com.sun.syndication.propono.atom.server.AtomException On error retrieving feed file.
* @return Atom Feed representing collection.
*/
@ -145,11 +143,11 @@ public class FileBasedCollection extends 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
* categories.
*
* @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 categories.
*/
public List getCategories(final boolean inline) {
public List<Categories> getCategories(final boolean inline) {
final Categories cats = new Categories();
cats.setFixed(true);
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
public List getCategories() {
public List<Categories> getCategories() {
return getCategories(inlineCats);
}
/**
* 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
* pattern [collection-plural]/[entryid]/entry.xml. The entry will be added to the collection's feed in [collection-plural]/feed.xml.
*
* @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 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.
* @return Entry as it exists on the server.
*/
@ -206,11 +207,13 @@ 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
* directory and the path will follow the pattern <code>[collection-plural]/[entryid]/media/[entryid]</code>. An Atom entry will be 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.
*
* 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 directory and the path will follow the
* pattern <code>[collection-plural]/[entryid]/media/[entryid]</code>. An Atom entry will be
* 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 slug String to be used in file-name
* @param is Source of media data
@ -259,7 +262,7 @@ public class FileBasedCollection extends Collection {
/**
* Get an entry from the collection.
*
*
* @param fsid Internal ID of entry to be returned
* @throws java.lang.Exception On error
* @return Entry specified by fileName/ID
@ -275,7 +278,6 @@ public class FileBasedCollection extends Collection {
final InputStream in = FileStore.getFileStore().getFileInputStream(entryPath);
final Entry entry;
final String filePath = getEntryMediaPath(fsid);
final File resource = new File(fsid);
if (resource.exists()) {
entry = loadAtomResourceEntry(in, resource);
@ -298,7 +300,7 @@ public class FileBasedCollection extends Collection {
/**
* Update an entry in the collection.
*
*
* @param entry Updated entry to be stored
* @param fsid Internal ID of entry
* @throws java.lang.Exception On error
@ -328,7 +330,7 @@ public class FileBasedCollection extends Collection {
/**
* Update media associated with a media-link entry.
*
*
* @param fileName Internal ID of entry being updated
* @param contentType Content type of data
* @param is Source of updated data
@ -374,7 +376,7 @@ public class FileBasedCollection extends Collection {
/**
* Delete an entry and any associated media file.
*
*
* @param fsid Internal ID of entry
* @throws java.lang.Exception On error
*/
@ -448,15 +450,12 @@ public class FileBasedCollection extends Collection {
updateFeedDocument(f);
}
private Entry findEntry(final String id, final Feed f) {
final List l = f.getEntries();
for (final Iterator it = l.iterator(); it.hasNext();) {
final Entry e = (Entry) it.next();
if (id.equals(e.getId())) {
return e;
private Entry findEntry(final String id, final Feed feed) {
for (final Entry entry : feed.getEntries()) {
if (id.equals(entry.getId())) {
return entry;
}
}
return null;
}
@ -526,10 +525,9 @@ public class FileBasedCollection extends Collection {
// Look for existing alt links and the alt link
Link altLink = null;
List altLinks = entry.getAlternateLinks();
List<Link> altLinks = entry.getAlternateLinks();
if (altLinks != null) {
for (final Iterator it = altLinks.iterator(); it.hasNext();) {
final Link link = (Link) it.next();
for (final Link link : altLinks) {
if (link.getRel() == null || "alternate".equals(link.getRel())) {
altLink = link;
break;
@ -537,7 +535,7 @@ public class FileBasedCollection extends Collection {
}
} else {
// No alt links found, so add them now
altLinks = new ArrayList();
altLinks = new ArrayList<Link>();
entry.setAlternateLinks(altLinks);
}
// 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
Link editLink = null;
List otherLinks = entry.getOtherLinks();
List<Link> otherLinks = entry.getOtherLinks();
if (otherLinks != null) {
for (final Iterator it = otherLinks.iterator(); it.hasNext();) {
final Link link = (Link) it.next();
for (final Link link : otherLinks) {
if ("edit".equals(link.getRel())) {
editLink = link;
break;
@ -562,7 +559,7 @@ public class FileBasedCollection extends Collection {
}
} else {
// No other links found, so add them now
otherLinks = new ArrayList();
otherLinks = new ArrayList<Link>();
entry.setOtherLinks(otherLinks);
}
// The edit link not found, so add it now
@ -585,13 +582,11 @@ public class FileBasedCollection extends Collection {
} catch (final Exception ignored) {
}
}
final String contentType = map.getContentType(fileName);
entry.setId(getEntryMediaViewURI(fileName));
entry.setTitle(fileName);
entry.setUpdated(new Date());
final List otherlinks = new ArrayList();
final List<Link> otherlinks = new ArrayList<Link>();
entry.setOtherLinks(otherlinks);
final Link editlink = new Link();
@ -606,13 +601,14 @@ public class FileBasedCollection extends Collection {
final Content content = entry.getContents().get(0);
content.setSrc(getEntryMediaViewURI(fileName));
final List contents = new ArrayList();
final List<Content> contents = new ArrayList<Content>();
contents.add(content);
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) {
try {
@ -633,7 +629,7 @@ public class FileBasedCollection extends Collection {
AppModule appModule = (AppModule) entry.getModule(AppModule.URI);
if (appModule == null) {
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);
entry.setModules(modules);
}
@ -642,7 +638,7 @@ public class FileBasedCollection extends Collection {
/**
* Save file to website's resource directory.
*
*
* @param handle Weblog handle to save to
* @param name Name of file to save
* @param size Size of file to be saved
@ -677,21 +673,25 @@ public class FileBasedCollection extends Collection {
/**
* Creates a file name for a file based on a weblog handle, title string and a content-type.
*
*
* @param handle Weblog handle
* @param title Title to be used as basis for file name (or 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
* title.
*
* 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.
*
* 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
*
* 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 title.
*
* 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.
*
* 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
*/
private String createFileName(final String title, final String contentType) {

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -21,14 +21,10 @@ import org.rometools.propono.atom.common.Workspace;
* File based Atom service Workspace.
*/
public class FileBasedWorkspace extends Workspace {
private String baseDir = null;
private String handle = null;
/** Creates a new instance of FileBasedWorkspace */
public FileBasedWorkspace(final String handle, final String baseDir) {
super(handle, "text");
this.handle = handle;
this.baseDir = baseDir;
}
}

View file

@ -34,7 +34,7 @@ import org.apache.commons.logging.LogFactory;
*/
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();
@ -49,29 +49,29 @@ class FileStore {
}
public InputStream getFileInputStream(final String path) {
log.debug("getFileContents path: " + path);
LOG.debug("getFileContents path: " + path);
try {
return new BufferedInputStream(new FileInputStream(path));
} catch (final FileNotFoundException e) {
log.debug(" File not found: " + path);
LOG.debug(" File not found: " + path);
return null;
}
}
public OutputStream getFileOutputStream(final String path) {
log.debug("getFileOutputStream path: " + path);
LOG.debug("getFileOutputStream path: " + path);
try {
final File f = new File(path);
f.getParentFile().mkdirs();
return new BufferedOutputStream(new FileOutputStream(f));
} catch (final FileNotFoundException e) {
log.debug(" File not found: " + path);
LOG.debug(" File not found: " + path);
return null;
}
}
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);
f.mkdirs();
final FileOutputStream out = new FileOutputStream(f);
@ -81,13 +81,14 @@ class FileStore {
while ((read = content.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
out.close();
}
public void deleteFile(final String path) {
log.debug("deleteFile path: " + path);
LOG.debug("deleteFile path: " + path);
final File f = new File(path);
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) {
log.debug("deleteDirectory path: " + path);
LOG.debug("deleteDirectory path: " + path);
if (path.exists()) {
final File[] files = path.listFiles();
for (final File file : files) {

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Dave Johnson (Blogapps project)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -31,7 +31,7 @@ public abstract class BaseBlogEntry implements BlogEntry {
protected String summary = null;
protected Date modificationDate = null;
protected Date publicationDate = null;
protected List categories = new ArrayList();
protected List<Category> categories = new ArrayList<Category>();
protected boolean draft = false;
private Blog blog = null;
@ -178,7 +178,7 @@ public abstract class BaseBlogEntry implements BlogEntry {
* {@inheritDoc}
*/
@Override
public List getCategories() {
public List<Category> getCategories() {
return categories;
}
@ -186,7 +186,7 @@ public abstract class BaseBlogEntry implements BlogEntry {
* {@inheritDoc}
*/
@Override
public void setCategories(final List categories) {
public void setCategories(final List<Category> categories) {
this.categories = categories;
}

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Dave Johnson (Blogapps project)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -20,46 +20,49 @@ import java.util.List;
/**
* <p>
* Represents a blog, which has collections of entries and resources. You can access the collections 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.
* Represents a blog, which has collections of entries and resources. You can access the collections
* 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>
*/
public interface Blog {
/**
* Token can be used to fetch this blog again from getBlog() method.
*
*
* @return Blog object specified by token.
*/
public String getToken();
/**
* Name of this blog.
*
*
* @return Display name of this blog.
*/
public String getName();
/**
* Get a single BlogEntry (or BlogResource) by token.
*
*
* @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.
*/
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.
* @return List of Blog.Collection objects.
*/
public List getCollections() throws BlogClientException;
public List<Collection> getCollections() throws BlogClientException;
/**
* Get collection by token.
*
*
* @param token Token from a collection's getToken() method.
* @throws BlogClientException On error fetching collection.
* @return Blog.Collection object.
@ -73,35 +76,35 @@ public interface Blog {
/**
* Get blog that contains this collection.
*
*
* @return Blog that contains this collection.
*/
public Blog getBlog();
/**
* Title of collection.
*
*
* @return Title of collecton.
*/
public String getTitle();
/**
* Token that can be used to fetch collection.
*
*
* @return Token that can be used to fetch collection.
*/
public String getToken();
/**
* Content-types accepted by collection.
*
*
* @return Comma-separated list of content-types accepted.
*/
public List getAccepts();
public List<String> getAccepts();
/**
* Determines if collection will accept a content-type.
*
*
* @param contentType Content-type to be considered.
* @return True of content type will be accepted, false otherwise.
*/
@ -109,23 +112,24 @@ public interface Blog {
/**
* Return categories allowed by colletion.
*
*
* @throws BlogClientException On error fetching categories.
* @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.
*
*
* @throws BlogClientException On error creating entry.
* @return New BlogEntry object.
*/
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 contentType MIME content-type of new resource.
* @param bytes Data for new resource.
@ -136,15 +140,16 @@ public interface Blog {
/**
* Get iterator over entries/resources in this collection.
*
*
* @return List of BlogEntry objects, some may be BlogResources.
* @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.
* @throws BlogClientException On error saving entry.
* @return URI of entry.
@ -153,7 +158,7 @@ public interface Blog {
/**
* Save or update resource in this collection
*
*
* @param resource BlogResource to be saved.
* @throws BlogClientException On error saving resource.
* @return URI of resource.
@ -164,50 +169,54 @@ public interface Blog {
// 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
* update and save them: to update and entry, first fetch it with getEntry(), change fields, then call entry.save();
*
* 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 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.
* @throws BlogClientException On failure or if there is no primary entries collection.
*
*
* @deprecated Instead use collections directly.
*/
@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.
* @return To iterate over all resojrces in collection.
*
*
* @deprecated Instead use collections directly.
*/
@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
* the server to a collection, use the entry's save() method.
*
* 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 the server to a collection, use
* the entry's save() method.
*
* @throws BlogClientException On error or if there is no primary entries collection.
* @return Unsaved BlogEntry in primary entries collection.
*
*
* @deprecated Instead use collections directly.
*/
@Deprecated
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
* resource to the server to a collection, use the resource's save() method.
*
* Create but do not save it to server new BlogResource in primary resources collection (the
* 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 type MIME content type of resource data.
* @param bytes Bytes of resource data.
* @throws BlogClientException On error or if there is no primary respurces collection.
* @return Unsaved BlogEntry in primary resources collection.
*
*
* @deprecated Instead use collections directly.
*/
@Deprecated
@ -215,12 +224,12 @@ public interface Blog {
/**
* Returns list of available BlogEntry.Category in primary entries collection.
*
*
* @throws BlogClientException On error or if there is no primary entries collection.
* @return List of BlogEntry.Category objects.
*
*
* @deprecated Instead use collections directly.
*/
@Deprecated
public List getCategories() throws BlogClientException;
public List<BlogEntry.Category> getCategories() throws BlogClientException;
}

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Dave Johnson (Blogapps project)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -16,13 +16,16 @@
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 {
private static final long serialVersionUID = 1L;
/**
* Construct a new exception
*
*
* @param msg Text message that explains exception
*/
public BlogClientException(final String msg) {
@ -31,7 +34,7 @@ public class BlogClientException extends Exception {
/**
* Construct a new exception which wraps a throwable.
*
*
* @param msg Text message that explains exception
* @param t Throwable to be wrapped by exception
*/

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Dave Johnson (Blogapps project)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -18,12 +18,13 @@ package org.rometools.propono.blogclient;
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 {
/** Returns collection of blogs available from this connection */
public abstract List getBlogs();
public abstract List<Blog> getBlogs();
/** Get blog by token */
public abstract Blog getBlog(String token);

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Dave Johnson (Blogapps project)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -33,7 +33,7 @@ public class BlogConnectionFactory {
/**
* Create a connection to a blog server.
*
*
* @param type Connection type, must be "atom" or "metaweblog"
* @param url End-point URL to connect to
* @param username Username for login to blog server
@ -54,14 +54,15 @@ public class BlogConnectionFactory {
private static BlogConnection createBlogConnection(final String className, final String url, final String username, final String password)
throws BlogClientException {
Class conClass;
Class<?> conClass;
try {
conClass = Class.forName(className);
} catch (final ClassNotFoundException ex) {
throw new BlogClientException("BlogConnection impl. class not found: " + className, ex);
}
final Class[] args = new Class[] { String.class, String.class, String.class };
Constructor ctor;
final Class<?>[] args = new Class[] { String.class, String.class, String.class };
Constructor<?> ctor;
try {
ctor = conClass.getConstructor(args);
return (BlogConnection) ctor.newInstance(new Object[] { url, username, password });
@ -69,4 +70,5 @@ public class BlogConnectionFactory {
throw new BlogClientException("ERROR instantiating BlogConnection impl.", t);
}
}
}

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Dave Johnson (Blogapps project)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -27,7 +27,8 @@ public interface BlogEntry {
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;
@ -41,10 +42,10 @@ public interface BlogEntry {
public Blog getBlog();
/** Get categories, a list of BlogEntry.Category objects */
public List getCategories();
public List<Category> getCategories();
/** 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 */
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() {
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) {
this.type = type;

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Dave Johnson (Blogapps project)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -21,9 +21,6 @@ import java.util.List;
import java.util.Map;
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.ClientCollection;
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.
*/
public class AtomBlog implements Blog {
static final Log logger = LogFactory.getLog(AtomBlog.class);
private final HttpClient httpClient = null;
private String name = null;
private ClientAtomService service;
private ClientWorkspace workspace = null;
private AtomCollection entriesCollection = 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
* AtomCollection object for each collection found. The first entry collection is considered the primary entry collection. And the first resource collection
* is considered the primary resource collection.
* Create AtomBlog using specified HTTPClient, user account and workspace, called by
* AtomConnection. Fetches Atom Service document and creates an AtomCollection object for each
* 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) {
setService(service);
setWorkspace(workspace);
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()) {
final ClientCollection col = (ClientCollection) members.next();
@ -70,6 +69,7 @@ public class AtomBlog implements Blog {
}
collections.put(col.getHrefResolved(), new AtomCollection(this, col));
}
}
/**
@ -113,7 +113,6 @@ public class AtomBlog implements Blog {
@Override
public BlogEntry getEntry(final String token) throws BlogClientException {
ClientEntry clientEntry = null;
final AtomEntry atomEntry = null;
try {
clientEntry = getService().getEntry(token);
} catch (final ProponoException ex) {
@ -132,7 +131,7 @@ public class AtomBlog implements Blog {
* {@inheritDoc}
*/
@Override
public Iterator getEntries() throws BlogClientException {
public Iterator<BlogEntry> getEntries() throws BlogClientException {
if (entriesCollection == null) {
throw new BlogClientException("No primary entry collection");
}
@ -143,7 +142,7 @@ public class AtomBlog implements Blog {
* {@inheritDoc}
*/
@Override
public Iterator getResources() throws BlogClientException {
public Iterator<BlogEntry> getResources() throws BlogClientException {
if (resourcesCollection == null) {
throw new BlogClientException("No primary entry collection");
}
@ -168,7 +167,7 @@ public class AtomBlog implements Blog {
* {@inheritDoc}
*/
@Override
public List getCategories() throws BlogClientException {
public List<BlogEntry.Category> getCategories() throws BlogClientException {
if (entriesCollection == null) {
throw new BlogClientException("No primary entry collection");
}
@ -201,8 +200,8 @@ public class AtomBlog implements Blog {
* {@inheritDoc}
*/
@Override
public List getCollections() throws BlogClientException {
return new ArrayList(collections.values());
public List<Collection> getCollections() throws BlogClientException {
return new ArrayList<Collection>(collections.values());
}
/**
@ -210,7 +209,7 @@ public class AtomBlog implements Blog {
*/
@Override
public Blog.Collection getCollection(final String token) throws BlogClientException {
return (Blog.Collection) collections.get(token);
return collections.get(token);
}
ClientAtomService getService() {

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Dave Johnson (Blogapps project)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -19,8 +19,6 @@ import java.util.ArrayList;
import java.util.Iterator;
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.ClientCollection;
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.
*/
public class AtomCollection implements Blog.Collection {
static final Log logger = LogFactory.getLog(AtomCollection.class);
private Blog blog = null;
private List categories = new ArrayList();
private List<BlogEntry.Category> categories = new ArrayList<BlogEntry.Category>();
private ClientCollection clientCollection = null;
AtomCollection(final AtomBlog blog, final ClientCollection col) {
this.blog = blog;
clientCollection = col;
for (final Iterator catsIter = col.getCategories().iterator(); catsIter.hasNext();) {
final Categories cats = (Categories) catsIter.next();
for (final Iterator catIter = cats.getCategories().iterator(); catIter.hasNext();) {
final Category cat = (Category) catIter.next();
for (final Object element : col.getCategories()) {
final Categories cats = (Categories) element;
for (final Object element2 : cats.getCategories()) {
final Category cat = (Category) element2;
final BlogEntry.Category blogCat = new BlogEntry.Category(cat.getTerm());
blogCat.setName(cat.getLabel());
blogCat.setUrl(cat.getScheme());
@ -78,7 +75,7 @@ public class AtomCollection implements Blog.Collection {
* {@inheritDoc}
*/
@Override
public List getAccepts() {
public List<String> getAccepts() {
return getClientCollection().getAccepts();
}
@ -94,7 +91,7 @@ public class AtomCollection implements Blog.Collection {
* {@inheritDoc}
*/
@Override
public Iterator getEntries() throws BlogClientException {
public Iterator<BlogEntry> getEntries() throws BlogClientException {
return new AtomEntryIterator(this);
}
@ -163,11 +160,11 @@ public class AtomCollection implements Blog.Collection {
* {@inheritDoc}
*/
@Override
public List getCategories() {
public List<BlogEntry.Category> getCategories() {
return categories;
}
void setCategories(final List categories) {
void setCategories(final List<BlogEntry.Category> categories) {
this.categories = categories;
}

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Dave Johnson (Blogapps project)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -21,41 +21,35 @@ import java.util.Iterator;
import java.util.List;
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.BasicAuthStrategy;
import org.rometools.propono.atom.client.ClientAtomService;
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.BlogClientException;
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 collection found.
* 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 collection found.
*/
public class AtomConnection implements BlogConnection {
private static Log logger = LogFactory.getLog(AtomConnection.class);
private final HttpClient httpClient = null;
private final Map blogs = new HashMap();
private final Map<String, Blog> blogs = new HashMap<String, Blog>();
/**
* Create Atom blog client instance for specified URL and user account.
*
*
* @param uri End-point URL of Atom service
* @param username Username of account
* @param password Password of account
*/
public AtomConnection(final String uri, final String username, final String password) throws BlogClientException {
final Document doc = null;
try {
final ClientAtomService service = AtomClientFactory.getAtomService(uri, new BasicAuthStrategy(username, password));
final Iterator iter = service.getWorkspaces().iterator();
final int count = 0;
final Iterator<Workspace> iter = service.getWorkspaces().iterator();
while (iter.hasNext()) {
final ClientWorkspace workspace = (ClientWorkspace) iter.next();
final Blog blog = new AtomBlog(service, workspace);
@ -70,8 +64,8 @@ public class AtomConnection implements BlogConnection {
* {@inheritDoc}
*/
@Override
public List getBlogs() {
return new ArrayList(blogs.values());
public List<Blog> getBlogs() {
return new ArrayList<Blog>(blogs.values());
}
/**
@ -79,7 +73,7 @@ public class AtomConnection implements BlogConnection {
*/
@Override
public Blog getBlog(final String token) {
return (AtomBlog) blogs.get(token);
return blogs.get(token);
}
/**

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Dave Johnson (Blogapps project)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -32,6 +32,8 @@ import org.rometools.propono.utils.ProponoException;
import com.sun.syndication.feed.atom.Entry;
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.
@ -138,20 +140,19 @@ public class AtomEntry extends BaseBlogEntry implements BlogEntry {
id = entry.getId();
title = entry.getTitle();
editURI = entry.getEditURI();
final List altlinks = entry.getAlternateLinks();
final List<Link> altlinks = entry.getAlternateLinks();
if (altlinks != null) {
for (final Iterator iter = altlinks.iterator(); iter.hasNext();) {
final Link link = (Link) iter.next();
for (final Link link : altlinks) {
if ("alternate".equals(link.getRel()) || link.getRel() == null) {
permalink = link.getHrefResolved();
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;
if (contents != null && contents.size() > 0) {
romeContent = (com.sun.syndication.feed.atom.Content) contents.get(0);
romeContent = contents.get(0);
}
if (romeContent != null) {
content = new BlogEntry.Content(romeContent.getValue());
@ -159,10 +160,9 @@ public class AtomEntry extends BaseBlogEntry implements BlogEntry {
content.setSrc(romeContent.getSrc());
}
if (entry.getCategories() != null) {
final List cats = new ArrayList();
final List romeCats = entry.getCategories();
for (final Iterator iter = romeCats.iterator(); iter.hasNext();) {
final com.sun.syndication.feed.atom.Category romeCat = (com.sun.syndication.feed.atom.Category) iter.next();
final List<Category> cats = new ArrayList<Category>();
final List<com.sun.syndication.feed.atom.Category> romeCats = entry.getCategories();
for (final com.sun.syndication.feed.atom.Category romeCat : romeCats) {
final BlogEntry.Category cat = new BlogEntry.Category();
cat.setId(romeCat.getTerm());
cat.setUrl(romeCat.getScheme());
@ -171,7 +171,7 @@ public class AtomEntry extends BaseBlogEntry implements BlogEntry {
}
categories = cats;
}
final List authors = entry.getAuthors();
final List<SyndPerson> authors = entry.getAuthors();
if (authors != null && authors.size() > 0) {
final com.sun.syndication.feed.atom.Person romeAuthor = (com.sun.syndication.feed.atom.Person) authors.get(0);
if (romeAuthor != null) {
@ -202,7 +202,7 @@ public class AtomEntry extends BaseBlogEntry implements BlogEntry {
person.setName(author.getName());
person.setEmail(author.getEmail());
person.setUrl(author.getUrl());
final List authors = new ArrayList();
final List<SyndPerson> authors = new ArrayList<SyndPerson>();
authors.add(person);
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();
romeContent.setValue(content.getValue());
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);
entry.setContents(contents);
}
if (categories != null) {
final List romeCats = new ArrayList();
for (final Iterator iter = categories.iterator(); iter.hasNext();) {
final BlogEntry.Category cat = (BlogEntry.Category) iter.next();
final List<com.sun.syndication.feed.atom.Category> romeCats = new ArrayList<com.sun.syndication.feed.atom.Category>();
for (final Iterator<Category> iter = categories.iterator(); iter.hasNext();) {
final BlogEntry.Category cat = iter.next();
final com.sun.syndication.feed.atom.Category romeCategory = new com.sun.syndication.feed.atom.Category();
romeCategory.setTerm(cat.getId());
romeCategory.setScheme(cat.getUrl());
@ -229,7 +229,7 @@ public class AtomEntry extends BaseBlogEntry implements BlogEntry {
entry.setPublished(publicationDate == null ? new Date() : publicationDate);
entry.setModified(modificationDate == null ? new Date() : modificationDate);
final List modules = new ArrayList();
final List<Module> modules = new ArrayList<Module>();
final AppModule control = new AppModuleImpl();
control.setDraft(new Boolean(draft));
modules.add(control);

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Dave Johnson (Blogapps project)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -22,13 +22,15 @@ import org.apache.commons.logging.LogFactory;
import org.rometools.propono.atom.client.ClientEntry;
import org.rometools.propono.atom.client.ClientMediaEntry;
import org.rometools.propono.blogclient.BlogClientException;
import org.rometools.propono.blogclient.BlogEntry;
/**
* Atom protocol implementation of BlogClient entry iterator.
*/
public class AtomEntryIterator implements Iterator {
static final Log logger = LogFactory.getLog(AtomEntryIterator.class);
private Iterator iterator = null;
public class AtomEntryIterator implements Iterator<BlogEntry> {
private static final Log logger = LogFactory.getLog(AtomEntryIterator.class);
private Iterator<ClientEntry> iterator = null;
private AtomCollection collection = null;
AtomEntryIterator(final AtomCollection collection) throws BlogClientException {
@ -52,9 +54,9 @@ public class AtomEntryIterator implements Iterator {
* Get next entry.
*/
@Override
public Object next() {
public BlogEntry next() {
try {
final ClientEntry entry = (ClientEntry) iterator.next();
final ClientEntry entry = iterator.next();
if (entry instanceof ClientMediaEntry) {
return new AtomResource(collection, (ClientMediaEntry) entry);
} else {

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Dave Johnson (Blogapps project)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -16,7 +16,6 @@
package org.rometools.propono.blogclient.atomprotocol;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import org.rometools.propono.atom.client.ClientAtomService;
@ -33,6 +32,7 @@ import com.sun.syndication.feed.atom.Link;
* Atom protocol implementation of BlogResource.
*/
public class AtomResource extends AtomEntry implements BlogResource {
private AtomCollection collection;
private byte[] bytes;
@ -119,17 +119,15 @@ public class AtomResource extends AtomEntry implements BlogResource {
@Override
void copyFromRomeEntry(final ClientEntry entry) {
super.copyFromRomeEntry(entry);
final List links = entry.getOtherLinks();
final List<Link> links = entry.getOtherLinks();
if (links != null) {
for (final Iterator iter = links.iterator(); iter.hasNext();) {
final Link link = (Link) iter.next();
for (final Link link : links) {
if ("edit-media".equals(link.getRel())) {
id = link.getHrefResolved();
break;
}
}
}
}
}

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Dave Johnson (Blogapps project)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -30,20 +30,22 @@ import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.rometools.propono.blogclient.Blog;
import org.rometools.propono.blogclient.BlogClientException;
import org.rometools.propono.blogclient.BlogEntry;
import org.rometools.propono.blogclient.BlogEntry.Category;
import org.rometools.propono.blogclient.BlogResource;
/**
* Blog implementation that uses a mix of Blogger and MetaWeblog API methods.
*/
public class MetaWeblogBlog implements Blog {
private final String blogid;
private final String name;
private final URL url;
private final String userName;
private final String password;
private String appkey = "dummy";
private final Map collections;
private final Map<String, MetaWeblogBlogCollection> collections;
private String appkey = "dummy";
private XmlRpcClient xmlRpcClient = null;
/**
@ -87,7 +89,7 @@ public class MetaWeblogBlog implements Blog {
this.url = url;
this.userName = userName;
this.password = password;
collections = new TreeMap();
collections = new TreeMap<String, MetaWeblogBlogCollection>();
collections.put("entries", new MetaWeblogBlogCollection(this, "entries", "Entries", "entry"));
collections.put("resources", new MetaWeblogBlogCollection(this, "resources", "Resources", "*"));
}
@ -106,7 +108,7 @@ public class MetaWeblogBlog implements Blog {
}
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);
}
@ -135,7 +137,7 @@ public class MetaWeblogBlog implements Blog {
* {@inheritDoc}
*/
@Override
public Iterator getEntries() throws BlogClientException {
public Iterator<BlogEntry> getEntries() throws BlogClientException {
return new EntryIterator();
}
@ -148,7 +150,7 @@ public class MetaWeblogBlog implements Blog {
}
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);
}
@ -160,8 +162,8 @@ public class MetaWeblogBlog implements Blog {
* {@inheritDoc}
*/
@Override
public Iterator getResources() throws BlogClientException {
return new NoOpIterator();
public NoOpIterator<BlogEntry> getResources() throws BlogClientException {
return new NoOpIterator<BlogEntry>();
}
void deleteResource(final BlogResource resource) throws BlogClientException {
@ -172,14 +174,15 @@ public class MetaWeblogBlog implements Blog {
* {@inheritDoc}
*/
@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 {
final Object result = getXmlRpcClient().execute("metaWeblog.getCategories", new Object[] { blogid, userName, password });
if (result != null && result instanceof HashMap) {
// Standard MetaWeblog API style: struct of struts
final Map catsmap = (Map) result;
final Iterator keys = catsmap.keySet().iterator();
while (keys.hasNext()) {
final String key = (String) keys.next();
@ -208,7 +211,7 @@ public class MetaWeblogBlog implements Blog {
return ret;
}
private HashMap createPostStructure(final BlogEntry entry) {
private Map<String, Object> createPostStructure(final BlogEntry entry) {
return ((MetaWeblogEntry) entry).toPostStructure();
}
@ -216,8 +219,8 @@ public class MetaWeblogBlog implements Blog {
* {@inheritDoc}
*/
@Override
public List getCollections() throws BlogClientException {
return new ArrayList(collections.values());
public List<Collection> getCollections() throws BlogClientException {
return new ArrayList<Collection>(collections.values());
}
/**
@ -225,7 +228,7 @@ public class MetaWeblogBlog implements Blog {
*/
@Override
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}
*/
@Override
public List getAccepts() {
public List<String> getAccepts() {
return Collections.singletonList(accept);
}
@ -308,8 +311,8 @@ public class MetaWeblogBlog implements Blog {
* {@inheritDoc}
*/
@Override
public Iterator getEntries() throws BlogClientException {
Iterator ret = null;
public Iterator<BlogEntry> getEntries() throws BlogClientException {
Iterator<BlogEntry> ret = null;
if (accept.equals("entry")) {
ret = MetaWeblogBlog.this.getEntries();
} else {
@ -349,7 +352,7 @@ public class MetaWeblogBlog implements Blog {
public String saveResource(final BlogResource res) throws BlogClientException {
final MetaWeblogResource resource = (MetaWeblogResource) res;
try {
final HashMap resmap = new HashMap();
final HashMap<String, Object> resmap = new HashMap<String, Object>();
resmap.put("name", resource.getName());
resmap.put("type", resource.getContent().getType());
resmap.put("bits", resource.getBytes());
@ -366,7 +369,7 @@ public class MetaWeblogBlog implements Blog {
* {@inheritDoc}
*/
@Override
public List getCategories() throws BlogClientException {
public List<Category> getCategories() throws BlogClientException {
return MetaWeblogBlog.this.getCategories();
}
@ -383,7 +386,7 @@ public class MetaWeblogBlog implements Blog {
/**
* Iterates over MetaWeblog API entries.
*/
public class EntryIterator implements Iterator {
public class EntryIterator implements Iterator<BlogEntry> {
private int pos = 0;
private boolean eod = false;
private static final int BUFSIZE = 30;
@ -414,7 +417,7 @@ public class MetaWeblogBlog implements Blog {
* Get next entry.
*/
@Override
public Object next() {
public BlogEntry next() {
final Map entryHash = (Map) results.get(pos++);
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

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Dave Johnson (Blogapps project)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -33,11 +33,12 @@ import org.rometools.propono.blogclient.BlogConnection;
* BlogClient implementation that uses a mix of Blogger and MetaWeblog API methods.
*/
public class MetaWeblogConnection implements BlogConnection {
private URL url = null;
private String userName = null;
private String password = null;
private String appkey = "null";
private Map blogs = null;
private Map<String, MetaWeblogBlog> blogs = null;
private XmlRpcClient xmlRpcClient = null;
@ -66,20 +67,20 @@ public class MetaWeblogConnection implements BlogConnection {
* {@inheritDoc}
*/
@Override
public List getBlogs() {
return new ArrayList(blogs.values());
public List<Blog> getBlogs() {
return new ArrayList<Blog>(blogs.values());
}
/**
* {@inheritDoc}
*/
private Map createBlogMap() throws XmlRpcException, IOException {
final Map blogMap = new HashMap();
private Map<String, MetaWeblogBlog> createBlogMap() throws XmlRpcException, IOException {
final Map<String, MetaWeblogBlog> blogMap = new HashMap<String, MetaWeblogBlog>();
final Object[] results = (Object[]) getXmlRpcClient().execute("blogger.getUsersBlogs", new Object[] { appkey, userName, password });
for (final Object result : results) {
final Map blog = (Map) result;
final String blogid = (String) blog.get("blogid");
final String name = (String) blog.get("blogName");
final Map<String, String> blog = (Map<String, String>) result;
final String blogid = blog.get("blogid");
final String name = blog.get("blogName");
blogMap.put(blogid, new MetaWeblogBlog(blogid, name, url, userName, password));
}
return blogMap;
@ -90,7 +91,7 @@ public class MetaWeblogConnection implements BlogConnection {
*/
@Override
public Blog getBlog(final String token) {
return (Blog) blogs.get(token);
return blogs.get(token);
}
/**

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Dave Johnson (Blogapps project)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -50,7 +50,7 @@ public class MetaWeblogEntry extends BaseBlogEntry {
author.setName((String) entryMap.get("userid"));
author.setEmail((String) entryMap.get("author"));
categories = new ArrayList();
categories = new ArrayList<Category>();
final Object[] catArray = (Object[]) entryMap.get("categories");
if (catArray != null) {
for (final Object element : catArray) {
@ -98,8 +98,8 @@ public class MetaWeblogEntry extends BaseBlogEntry {
((MetaWeblogBlog) getBlog()).deleteEntry(id);
}
HashMap toPostStructure() {
final HashMap struct = new HashMap();
Map<String, Object> toPostStructure() {
final Map<String, Object> struct = new HashMap<String, Object>();
if (getTitle() != null) {
struct.put("title", getTitle());
}
@ -107,10 +107,10 @@ public class MetaWeblogEntry extends BaseBlogEntry {
struct.put("description", getContent().getValue());
}
if (getCategories() != null && getCategories().size() > 0) {
final List catArray = new ArrayList();
final List cats = getCategories();
final List<String> catArray = new ArrayList<String>();
final List<Category> cats = getCategories();
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());
}
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

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -23,8 +23,8 @@ import java.io.PrintWriter;
*/
public class ProponoException extends Exception {
private static final long serialVersionUID = 1L;
private Throwable mRootCause = null;
private String longMessage = null;
/**
* Construct emtpy exception object.
@ -35,7 +35,7 @@ public class ProponoException extends Exception {
/**
* Construct ProponoException with message string.
*
*
* @param s Error message string.
*/
public ProponoException(final String s) {
@ -44,17 +44,16 @@ public class ProponoException extends Exception {
/**
* Construct ProponoException with message string.
*
*
* @param s Error message string.
*/
public ProponoException(final String s, final String longMessage) {
super(s);
this.longMessage = longMessage;
}
/**
* Construct ProponoException, wrapping existing throwable.
*
*
* @param s Error message
* @param t Existing connection to wrap.
*/
@ -65,19 +64,18 @@ public class ProponoException extends Exception {
/**
* Construct ProponoException, wrapping existing throwable.
*
*
* @param s Error message
* @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);
mRootCause = t;
longMessage = longMessage;
}
/**
* Construct ProponoException, wrapping existing throwable.
*
*
* @param t Existing exception to be wrapped.
*/
public ProponoException(final Throwable t) {
@ -86,7 +84,7 @@ public class ProponoException extends Exception {
/**
* Get root cause object, or null if none.
*
*
* @return Root cause or null if none.
*/
public Throwable getRootCause() {
@ -95,7 +93,7 @@ public class ProponoException extends Exception {
/**
* Get root cause message.
*
*
* @return Root cause message.
*/
public String getRootCauseMessage() {
@ -113,7 +111,7 @@ public class ProponoException extends Exception {
/**
* Print stack trace for exception and for root cause exception if htere is one.
*
*
* @see java.lang.Throwable#printStackTrace()
*/
@Override
@ -127,7 +125,7 @@ public class ProponoException extends Exception {
/**
* Print stack trace for exception and for root cause exception if htere is one.
*
*
* @param s Stream to print to.
*/
@Override
@ -141,7 +139,7 @@ public class ProponoException extends Exception {
/**
* Print stack trace for exception and for root cause exception if htere is one.
*
*
* @param s Writer to write to.
*/
@Override

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Dave Johnson (Blogapps project)
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -28,53 +28,55 @@ import java.util.NoSuchElementException;
import java.util.StringTokenizer;
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.
*/
public class Utilities {
public final class Utilities {
private static final String LS = System.getProperty("line.separator");
private Utilities() {
}
/**
* Returns the contents of the file in a byte array (from JavaAlmanac).
*/
public static byte[] getBytesFromFile(final File file) throws IOException {
final InputStream is = new FileInputStream(file);
try {
// Get the size of the file
final long length = file.length();
// Get the size of the file
final long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// 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]*:.*$");
private static boolean isAbsoluteURI(final String uri) {
return absoluteURIPattern.matcher(uri).find();
}
// private static boolean isAbsoluteURI(final String uri) {
// return absoluteURIPattern.matcher(uri).find();
// }
private static boolean isRelativeURI(final String uri) {
return !isAbsoluteURI(uri);
}
// private static boolean isRelativeURI(final String uri) {
// return !isAbsoluteURI(uri);
// }
/**
* } Resolve URI based considering xml:base and baseURI.
*
* @param baseURI Base URI of feed
* @param parent Parent from which to consider xml:base
* @param url URL to be resolved
*/
private static String resolveURI(final String baseURI, final Parent parent, String url) {
if (isRelativeURI(url)) {
url = !".".equals(url) && !"./".equals(url) ? url : "";
// /**
// * } Resolve URI based considering xml:base and baseURI.
// *
// * @param baseURI Base URI of feed
// * @param parent Parent from which to consider xml:base
// * @param url URL to be resolved
// */
// private static String resolveURI(final String baseURI, final Parent parent, String url) {
// if (isRelativeURI(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);
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);
// /**
// * 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;
// }
// 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;
}
// /**
// * 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;
// }
/**
* 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

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -17,7 +17,6 @@ package org.rometools.propono.atom.client;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import junit.framework.Test;
@ -26,13 +25,13 @@ import junit.framework.TestSuite;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Ignore;
import org.rometools.propono.atom.common.Categories;
import org.rometools.propono.atom.common.Collection;
import org.rometools.propono.utils.ProponoException;
import com.sun.syndication.feed.atom.Category;
import com.sun.syndication.feed.atom.Content;
import org.junit.Ignore;
/**
* 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 =
* "55132608a2fb68816bcd3d1caeafc933"; private static String consumerSecret = "bb420783-fdea-4270-ab83-36445c18c307"; private static String requestUri =
* "http://macsnoopdave:8080/roller-services/oauth/requestToken"; private static String authorizeUri =
* "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); } }
* // Roller OAuth example private static String endpoint =
* "http://macsnoopdave:8080/roller-services/app"; private static String consumerKey =
* "55132608a2fb68816bcd3d1caeafc933"; private static String consumerSecret =
* "bb420783-fdea-4270-ab83-36445c18c307"; private static String requestUri =
* "http://macsnoopdave:8080/roller-services/oauth/requestToken"; private static String
* authorizeUri =
* "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
/*
* private static String endpoint = "http://www.blogger.com/feeds/default/blogs?alt=atom-service"; private static String email = "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 static String endpoint =
* "http://www.blogger.com/feeds/default/blogs?alt=atom-service"; private static String email =
* "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) {
super(testName);
}
@ -110,12 +116,12 @@ public class AtomClientTest extends TestCase {
public void testGetAtomService() throws Exception {
assertNotNull(service);
assertTrue(service.getWorkspaces().size() > 0);
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) {
final ClientWorkspace space = (ClientWorkspace) it.next();
for (final Object element : service.getWorkspaces()) {
final ClientWorkspace space = (ClientWorkspace) element;
assertNotNull(space.getTitle());
log.debug("Workspace: " + space.getTitle());
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) {
final ClientCollection col = (ClientCollection) colit.next();
for (final Object element2 : space.getCollections()) {
final ClientCollection col = (ClientCollection) element2;
log.debug(" Collection: " + col.getTitle() + " Accepts: " + col.getAccepts());
log.debug(" href: " + col.getHrefResolved());
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 {
assertNotNull(service);
assertTrue(service.getWorkspaces().size() > 0);
int count = 0;
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) {
final ClientWorkspace space = (ClientWorkspace) it.next();
for (final Object element : service.getWorkspaces()) {
final ClientWorkspace space = (ClientWorkspace) element;
assertNotNull(space.getTitle());
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) {
final ClientCollection col = (ClientCollection) colit.next();
for (final Object element2 : space.getCollections()) {
final ClientCollection col = (ClientCollection) element2;
if (col.accepts(Collection.ENTRY_TYPE)) {
// 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 {
assertNotNull(service);
assertTrue(service.getWorkspaces().size() > 0);
int count = 0;
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) {
final ClientWorkspace space = (ClientWorkspace) it.next();
for (final Object element : service.getWorkspaces()) {
final ClientWorkspace space = (ClientWorkspace) element;
assertNotNull(space.getTitle());
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) {
final ClientCollection col = (ClientCollection) colit.next();
for (final Object element2 : space.getCollections()) {
final ClientCollection col = (ClientCollection) element2;
if (col.accepts(Collection.ENTRY_TYPE)) {
// 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 {
assertNotNull(service);
assertTrue(service.getWorkspaces().size() > 0);
int count = 0;
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) {
final ClientWorkspace space = (ClientWorkspace) it.next();
for (final Object element2 : service.getWorkspaces()) {
final ClientWorkspace space = (ClientWorkspace) element2;
assertNotNull(space.getTitle());
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) {
final ClientCollection col = (ClientCollection) colit.next();
for (final Object element3 : space.getCollections()) {
final ClientCollection col = (ClientCollection) element3;
if (col.accepts(Collection.ENTRY_TYPE)) {
// 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
Category fixedCat = 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++) {
final Categories cats = (Categories) col.getCategories().get(i);
final Categories cats = col.getCategories().get(i);
if (cats.isFixed() && fixedCat == null) {
final String scheme = cats.getScheme();
fixedCat = (Category) cats.getCategories().get(0);
fixedCat = cats.getCategories().get(0);
if (fixedCat.getScheme() == null) {
fixedCat.setScheme(scheme);
}
@ -352,12 +361,12 @@ public class AtomClientTest extends TestCase {
assertNotNull(service);
assertTrue(service.getWorkspaces().size() > 0);
int count = 0;
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) {
final ClientWorkspace space = (ClientWorkspace) it.next();
for (final Object element : service.getWorkspaces()) {
final ClientWorkspace space = (ClientWorkspace) element;
assertNotNull(space.getTitle());
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) {
final ClientCollection col = (ClientCollection) colit.next();
for (final Object element2 : space.getCollections()) {
final ClientCollection col = (ClientCollection) element2;
if (col.accepts("image/gif")) {
// we found a collection that accepts GIF, so post one
@ -389,18 +398,23 @@ public class AtomClientTest extends TestCase {
/**
* Post X media entries each media collection found, test paging, then cleanup.
*
* public void testMediaPaging() throws Exception { ClientAtomService service = getClientAtomService(); assertNotNull(service);
* assertTrue(service.getWorkspaces().size() > 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
* (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
* m1 = col.createMediaEntry("duke"+count, "duke"+count, "image/gif", new FileInputStream("test/testdata/duke-wave-shadow.gif")); col.addEntry(m1);
* posted.add(m1); } 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); }
*
* public void testMediaPaging() throws Exception { ClientAtomService service =
* getClientAtomService(); assertNotNull(service); assertTrue(service.getWorkspaces().size() >
* 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 (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 m1 =
* col.createMediaEntry("duke"+count, "duke"+count, "image/gif", new
* FileInputStream("test/testdata/duke-wave-shadow.gif")); col.addEntry(m1); posted.add(m1); }
* 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

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -21,9 +21,10 @@ import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import com.sun.syndication.feed.atom.Content;
import org.junit.Ignore;
import com.sun.syndication.feed.atom.Content;
/**
* Simple APP test designed to run against Blogger.com.
*/
@ -31,7 +32,8 @@ import org.junit.Ignore;
public class BloggerDotComTest extends TestCase {
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 password = "PASSWORD";
@ -61,8 +63,8 @@ public class BloggerDotComTest extends TestCase {
ClientCollection col = AtomClientFactory.getCollection(collectionURI, new GDataAuthStrategy(email, password, "blogger"));
assertNotNull(col);
int count = 0;
for (final Iterator it = col.getEntries(); it.hasNext();) {
final ClientEntry entry = (ClientEntry) it.next();
for (final Iterator<ClientEntry> it = col.getEntries(); it.hasNext();) {
final ClientEntry entry = it.next();
assertNotNull(entry);
count++;
}

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -15,9 +15,6 @@
*/
package org.rometools.propono.atom.common;
import java.io.FileInputStream;
import java.util.Iterator;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
@ -26,8 +23,6 @@ import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import com.sun.syndication.feed.atom.Category;
/**
* Tests reading and writing of service document, no server needed.
*/
@ -65,25 +60,19 @@ public class AtomServiceTest extends TestCase {
int workspaceCount = 0;
// Verify that service contains expected workspaces, collections and categories
for (final Iterator it = service.getWorkspaces().iterator(); it.hasNext();) {
final Workspace space = (Workspace) it.next();
for (final Object element : service.getWorkspaces()) {
final Workspace space = (Workspace) element;
assertNotNull(space.getTitle());
workspaceCount++;
int collectionCount = 0;
for (final Iterator colit = space.getCollections().iterator(); colit.hasNext();) {
final Collection col = (Collection) colit.next();
for (final Object element2 : space.getCollections()) {
final Collection col = (Collection) element2;
assertNotNull(col.getTitle());
assertNotNull(col.getHrefResolved());
collectionCount++;
int catCount = 0;
if (col.getCategories().size() > 0) {
for (final Iterator catsit = col.getCategories().iterator(); catsit.hasNext();) {
final Categories cats = (Categories) catsit.next();
for (final Iterator catit = cats.getCategories().iterator(); catit.hasNext();) {
final Category cat = (Category) catit.next();
catCount++;
}
for (final Object element3 : col.getCategories()) {
final Categories cats = (Categories) element3;
catCount += cats.getCategories().size();
assertTrue(catCount > 0);
}
}

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -51,7 +51,7 @@ public class CollectionTest extends TestCase {
assertTrue(col.accepts("image/png"));
assertFalse(col.accepts("test/html"));
final List accepts = new ArrayList();
final List<String> accepts = new ArrayList<String>();
accepts.add("image/*");
accepts.add("text/*");
col.setAccepts(accepts);

View file

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

View file

@ -1,10 +1,10 @@
/*
/*
* Copyright 2007 Sun Microsystems, Inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
@ -22,13 +22,15 @@ import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Ignore;
import org.rometools.propono.blogclient.Blog.Collection;
import org.rometools.propono.utils.Utilities;
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
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 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 password = "admin";
@ -65,8 +67,7 @@ public class SimpleBlogClientTest extends TestCase {
final BlogConnection conn = BlogConnectionFactory.getBlogConnection(type, endpoint, username, password);
int blogCount = 0;
for (final Iterator it = conn.getBlogs().iterator(); it.hasNext();) {
final Blog blog = (Blog) it.next();
for (final Blog blog : conn.getBlogs()) {
System.out.println(blog.getName());
blogCount++;
}
@ -96,7 +97,7 @@ public class SimpleBlogClientTest extends TestCase {
final String title1 = "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();
entry.setTitle(title1);
entry.setContent(new BlogEntry.Content(content1));
@ -131,12 +132,12 @@ public class SimpleBlogClientTest extends TestCase {
assertTrue(conn.getBlogs().size() > 0);
int count = 0;
for (final Iterator it = conn.getBlogs().iterator(); it.hasNext();) {
final Blog blog = (Blog) it.next();
for (final Blog blog2 : conn.getBlogs()) {
final Blog blog = blog2;
assertNotNull(blog.getName());
for (final Iterator colit = blog.getCollections().iterator(); colit.hasNext();) {
final Blog.Collection col = (Blog.Collection) colit.next();
for (final Collection collection : blog.getCollections()) {
final Blog.Collection col = collection;
if (col.accepts("image/gif")) {
// 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 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++) {
final BlogEntry entry = blog.newEntry();