From 8f475d9ae11106c02809d6d8537d41cc12b75b76 Mon Sep 17 00:00:00 2001
From: Patrick Gotthard To create your own Atom protocol implementation you must implement this
- * interface and create a concrete sub-class of
- * {@link com.sun.syndication.propono.atom.server.AtomHandlerFactory}
- * which is capable of instantiating it.
+ * To create your own Atom protocol implementation you must implement this interface and create a concrete sub-class of
+ * {@link com.sun.syndication.propono.atom.server.AtomHandlerFactory} which is capable of instantiating it.
+ * To create your own Atom protocol implementation you must sub-class this
- * class with your own factory that is capable of creating instances of your
- * {@link com.sun.syndication.propono.atom.server.AtomHandler} impementation.
+ * To create your own Atom protocol implementation you must sub-class this class with your own factory that is capable of creating instances of your
+ * {@link com.sun.syndication.propono.atom.server.AtomHandler} impementation.
+ * Protected constructor to prevent instantiation.
- * Use {@link #newInstance()}. Protected constructor to prevent instantiation. Use {@link #newInstance()}. URI structure used for accessing collections and entries Collection feed (URI allows GET to get collection, POST to add to it)
+ * URI structure used for accessing collections and entries
* Collection entry (URI allows GET, PUT and DELETE)
+ * Collection feed (URI allows GET to get collection, POST to add to it) Collection entry media (URI allows GET, PUT and DELETE)
+ * Collection entry (URI allows GET, PUT and DELETE) Categories URI if not using inline categories (URI allows GET)
+ * Collection entry media (URI allows GET, PUT and DELETE) Directory structure used to store collections and entries Collection feed (kept constantly up to date)
+ * Categories URI if not using inline categories (URI allows GET) Collection entry (individual entries also stored as entry.xml files)
+ * Directory structure used to store collections and entries
* Collection entry media (media file stored under entry directory)
+ * Collection feed (kept constantly up to date)
+ * Collection entry (individual entries also stored as entry.xml files)
+ * Collection entry media (media file stored under entry directory)getEntry()
method and to return
- * {@link com.sun.syndication.propono.atom.client.ClientWorkspace}
- * objects instead of common
+ * 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 getEntry()
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 String uri = null;
- private HttpClient httpClient = null;
+ 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
+ *
+ * @param url End-point URL of Atom service
*/
- ClientAtomService(String uri, AuthStrategy authStrategy)
- throws ProponoException {
+ ClientAtomService(final String uri, final AuthStrategy authStrategy) throws ProponoException {
this.uri = uri;
this.authStrategy = authStrategy;
- Document doc = getAtomServiceDocument();
+ final Document doc = getAtomServiceDocument();
parseAtomServiceDocument(doc);
}
-
+
/**
* Get full entry from service by entry edit URI.
*/
- public ClientEntry getEntry(String uri) throws ProponoException {
- GetMethod method = new GetMethod(uri);
+ public ClientEntry getEntry(final String uri) throws ProponoException {
+ final GetMethod method = new GetMethod(uri);
authStrategy.addAuthentication(httpClient, method);
try {
- httpClient.executeMethod(method);
+ httpClient.executeMethod(method);
if (method.getStatusCode() != 200) {
throw new ProponoException("ERROR HTTP status code=" + method.getStatusCode());
}
- Entry romeEntry = Atom10Parser.parseEntry(
- new InputStreamReader(method.getResponseBodyAsStream()), uri);
+ final Entry romeEntry = Atom10Parser.parseEntry(new InputStreamReader(method.getResponseBodyAsStream()), uri);
if (!romeEntry.isMediaEntry()) {
return new ClientEntry(this, null, romeEntry, false);
} else {
return new ClientMediaEntry(this, null, romeEntry, false);
}
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new ProponoException("ERROR: getting or parsing entry/media", e);
} finally {
method.releaseConnection();
}
}
- void addAuthentication(HttpMethodBase method) throws ProponoException {
+ void addAuthentication(final HttpMethodBase method) throws ProponoException {
authStrategy.addAuthentication(httpClient, method);
}
AuthStrategy getAuthStrategy() {
return authStrategy;
}
-
+
private Document getAtomServiceDocument() throws ProponoException {
GetMethod method = null;
- int code = -1;
+ final int code = -1;
try {
httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
// TODO: make connection timeout configurable
- httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
-
+ httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
+
method = new GetMethod(uri);
authStrategy.addAuthentication(httpClient, method);
httpClient.executeMethod(method);
-
- SAXBuilder builder = new SAXBuilder();
+
+ final SAXBuilder builder = new SAXBuilder();
return builder.build(method.getResponseBodyAsStream());
-
- } catch (Throwable t) {
- String msg = "ERROR retrieving Atom Service Document, code: "+code;
+
+ } catch (final Throwable t) {
+ final String msg = "ERROR retrieving Atom Service Document, code: " + code;
logger.debug(msg, t);
throw new ProponoException(msg, t);
} finally {
- if (method != null) method.releaseConnection();
+ if (method != null) {
+ method.releaseConnection();
+ }
}
}
/** Deserialize an Atom service XML document into an object */
- private void parseAtomServiceDocument(Document document) throws ProponoException {
- Element root = document.getRootElement();
- List spaces = root.getChildren("workspace", AtomService.ATOM_PROTOCOL);
- Iterator iter = spaces.iterator();
+ 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()) {
- Element e = (Element) iter.next();
+ final Element e = (Element) iter.next();
addWorkspace(new ClientWorkspace(e, this, uri));
}
}
-
+
/**
* Package access to httpClient.
*/
@@ -135,4 +133,3 @@ public class ClientAtomService extends AtomService {
return httpClient;
}
}
-
diff --git a/src/main/java/org/rometools/propono/atom/client/ClientCategories.java b/src/main/java/org/rometools/propono/atom/client/ClientCategories.java
index 784ea3d..d8f7876 100644
--- a/src/main/java/org/rometools/propono/atom/client/ClientCategories.java
+++ b/src/main/java/org/rometools/propono/atom/client/ClientCategories.java
@@ -1,70 +1,66 @@
/*
-* Licensed to the Apache Software Foundation (ASF) under one or more
-* contributor license agreements. The ASF licenses this file to You
-* under the Apache License, Version 2.0 (the "License"); you may not
-* use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License. For additional information regarding
-* copyright in this work, please see the NOTICE file in the top level
-* directory of this distribution.
-*/
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License. For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ */
package org.rometools.propono.atom.client;
-import com.sun.syndication.feed.atom.Category;
-import org.rometools.propono.atom.common.*;
-import org.rometools.propono.utils.ProponoException;
import java.io.IOException;
import java.io.InputStreamReader;
+
import org.apache.commons.httpclient.methods.GetMethod;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
+import org.rometools.propono.atom.common.Categories;
+import org.rometools.propono.utils.ProponoException;
-
-/**
- * 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 ClientCategories extends Categories {
+public class ClientCategories extends Categories {
private ClientCollection clientCollection = null;
-
+
/** Load select from XML element */
- public ClientCategories(Element e, ClientCollection clientCollection) throws ProponoException {
+ public ClientCategories(final Element e, final ClientCollection clientCollection) throws ProponoException {
this.clientCollection = clientCollection;
parseCategoriesElement(e);
- if (getHref() != null) fetchContents();
+ if (getHref() != null) {
+ fetchContents();
+ }
}
-
+
public void fetchContents() throws ProponoException {
- GetMethod method = new GetMethod(getHrefResolved());
+ final GetMethod method = new GetMethod(getHrefResolved());
clientCollection.addAuthentication(method);
try {
- clientCollection.getHttpClient().executeMethod(method);
+ clientCollection.getHttpClient().executeMethod(method);
if (method.getStatusCode() != 200) {
throw new ProponoException("ERROR HTTP status code=" + method.getStatusCode());
}
- SAXBuilder builder = new SAXBuilder();
- Document catsDoc = builder.build(
- new InputStreamReader(method.getResponseBodyAsStream()));
+ final SAXBuilder builder = new SAXBuilder();
+ final Document catsDoc = builder.build(new InputStreamReader(method.getResponseBodyAsStream()));
parseCategoriesElement(catsDoc.getRootElement());
- } catch (IOException ioe) {
- throw new ProponoException(
- "ERROR: reading out-of-line categories", ioe);
- } catch (JDOMException jde) {
- throw new ProponoException(
- "ERROR: parsing out-of-line categories", jde);
+ } catch (final IOException ioe) {
+ throw new ProponoException("ERROR: reading out-of-line categories", ioe);
+ } catch (final JDOMException jde) {
+ throw new ProponoException("ERROR: parsing out-of-line categories", jde);
} finally {
method.releaseConnection();
}
}
}
-
diff --git a/src/main/java/org/rometools/propono/atom/client/ClientCollection.java b/src/main/java/org/rometools/propono/atom/client/ClientCollection.java
index a1d6bda..0f63efd 100644
--- a/src/main/java/org/rometools/propono/atom/client/ClientCollection.java
+++ b/src/main/java/org/rometools/propono/atom/client/ClientCollection.java
@@ -12,69 +12,70 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
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.io.InputStreamReader;
-import com.sun.syndication.feed.atom.Entry;
-import com.sun.syndication.io.impl.Atom10Parser;
-import org.rometools.propono.atom.common.AtomService;
-import org.rometools.propono.atom.common.Categories;
-import org.rometools.propono.utils.ProponoException;
-import org.rometools.propono.atom.common.Collection;
-import org.rometools.propono.atom.common.Workspace;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
+import java.util.List;
+
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;
+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.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 List categories = new ArrayList();
- private HttpClient httpClient = null;
+ private final List categories = new ArrayList();
+ private HttpClient httpClient = null;
private AuthStrategy authStrategy = null;
- private boolean writable = true;
+ private final boolean writable = true;
private ClientWorkspace workspace = null;
private ClientAtomService service = null;
- ClientCollection(Element e, ClientWorkspace workspace, String baseURI) throws ProponoException {
- super(e, baseURI);
+ ClientCollection(final Element e, final ClientWorkspace workspace, final String baseURI) throws ProponoException {
+ super(e, baseURI);
this.workspace = workspace;
- this.service = workspace.getAtomService();
- this.httpClient = workspace.getAtomService().getHttpClient();
- this.authStrategy = workspace.getAtomService().getAuthStrategy();
+ service = workspace.getAtomService();
+ httpClient = workspace.getAtomService().getHttpClient();
+ authStrategy = workspace.getAtomService().getAuthStrategy();
parseCollectionElement(e);
}
- ClientCollection(String href, AuthStrategy authStrategy) throws ProponoException {
+ ClientCollection(final String href, final AuthStrategy authStrategy) throws ProponoException {
super("Standalone connection", "text", href);
this.authStrategy = authStrategy;
try {
httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
// TODO: make connection timeout configurable
- httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
- } catch (Throwable t) {
+ httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
+ } catch (final Throwable t) {
throw new ProponoException("ERROR creating HTTPClient", t);
}
}
- void addAuthentication(HttpMethodBase method) throws ProponoException {
+ void addAuthentication(final HttpMethodBase method) throws ProponoException {
authStrategy.addAuthentication(httpClient, method);
}
-
+
/**
* Package access to httpClient to allow use by ClientEntry and ClientMediaEntry.
*/
@@ -82,135 +83,141 @@ public class ClientCollection extends Collection {
return httpClient;
}
- /**
- * 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 {
- return new EntryIterator(this);
+ return new EntryIterator(this);
}
-
+
/**
- * Get full entry specified by entry edit URI.
- * Note that entry may or may not be associated with this collection.
+ * Get full entry specified by entry edit URI. Note that entry may or may not be associated with this collection.
+ *
* @return ClientEntry or ClientMediaEntry specified by URI.
*/
- public ClientEntry getEntry(String uri) throws ProponoException {
- GetMethod method = new GetMethod(uri);
+ public ClientEntry getEntry(final String uri) throws ProponoException {
+ final GetMethod method = new GetMethod(uri);
authStrategy.addAuthentication(httpClient, method);
try {
- httpClient.executeMethod(method);
+ httpClient.executeMethod(method);
if (method.getStatusCode() != 200) {
throw new ProponoException("ERROR HTTP status code=" + method.getStatusCode());
}
- Entry romeEntry = Atom10Parser.parseEntry(
- new InputStreamReader(method.getResponseBodyAsStream()), uri);
+ final Entry romeEntry = Atom10Parser.parseEntry(new InputStreamReader(method.getResponseBodyAsStream()), uri);
if (!romeEntry.isMediaEntry()) {
return new ClientEntry(service, this, romeEntry, false);
} else {
return new ClientMediaEntry(service, this, romeEntry, false);
}
- } catch (Exception e) {
+ } catch (final Exception e) {
throw new ProponoException("ERROR: getting or parsing entry/media, HTTP code: ", e);
} finally {
method.releaseConnection();
}
}
-
+
/**
* Get workspace or null if collection is not associated with a workspace.
*/
public Workspace getWorkspace() {
return workspace;
}
-
+
/**
* Determines if collection is writable.
*/
public boolean isWritable() {
return writable;
}
-
- /**
+
+ /**
* Create new entry associated with collection, but do not save to server.
+ *
* @throws ProponoException if collecton is not writable.
*/
public ClientEntry createEntry() throws ProponoException {
- if (!isWritable()) throw new ProponoException("Collection is not writable");
+ if (!isWritable()) {
+ throw new ProponoException("Collection is not writable");
+ }
return new ClientEntry(service, this);
}
/**
- * 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
+ * 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.
- * @param bytes Data to be uploaded as byte array.
+ * @param bytes Data to be uploaded as byte array.
* @throws ProponoException if collecton is not writable
*/
- public ClientMediaEntry createMediaEntry(
- String title, String slug, String contentType, byte[] bytes)
- throws ProponoException {
- if (!isWritable()) throw new ProponoException("Collection is not writable");
+ public ClientMediaEntry createMediaEntry(final String title, final String slug, final String contentType, final byte[] bytes) throws ProponoException {
+ if (!isWritable()) {
+ throw new ProponoException("Collection is not writable");
+ }
return new ClientMediaEntry(service, this, title, slug, contentType, bytes);
}
-
+
/**
- * 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
+ * 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.
- * @param is Data to be uploaded as InputStream.
+ * @param is Data to be uploaded as InputStream.
* @throws ProponoException if collecton is not writable
*/
- public ClientMediaEntry createMediaEntry(
- String title, String slug, String contentType, InputStream is)
- throws ProponoException {
- if (!isWritable()) throw new ProponoException("Collection is not writable");
+ public ClientMediaEntry createMediaEntry(final String title, final String slug, final String contentType, final InputStream is) throws ProponoException {
+ if (!isWritable()) {
+ throw new ProponoException("Collection is not writable");
+ }
return new ClientMediaEntry(service, this, title, slug, contentType, is);
}
-
+
/**
- * 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.
*/
- public void addEntry(ClientEntry entry) throws ProponoException {
- if (!isWritable()) throw new ProponoException("Collection is not writable");
+ public void addEntry(final ClientEntry entry) throws ProponoException {
+ if (!isWritable()) {
+ throw new ProponoException("Collection is not writable");
+ }
entry.addToCollection(this);
}
- protected void parseCollectionElement(Element element) throws ProponoException {
- if (workspace == null) return;
-
+ @Override
+ protected void parseCollectionElement(final Element element) throws ProponoException {
+ if (workspace == null) {
+ return;
+ }
+
setHref(element.getAttribute("href").getValue());
-
- Element titleElem = element.getChild("title", AtomService.ATOM_FORMAT);
+
+ final Element titleElem = element.getChild("title", AtomService.ATOM_FORMAT);
if (titleElem != null) {
setTitle(titleElem.getText());
if (titleElem.getAttribute("type", AtomService.ATOM_FORMAT) != null) {
setTitleType(titleElem.getAttribute("type", AtomService.ATOM_FORMAT).getValue());
}
}
-
- List acceptElems = element.getChildren("accept", AtomService.ATOM_PROTOCOL);
+
+ final List acceptElems = element.getChildren("accept", AtomService.ATOM_PROTOCOL);
if (acceptElems != null && acceptElems.size() > 0) {
- for (Iterator it = acceptElems.iterator(); it.hasNext();) {
- Element acceptElem = (Element)it.next();
+ for (final Iterator it = acceptElems.iterator(); it.hasNext();) {
+ final Element acceptElem = (Element) it.next();
addAccept(acceptElem.getTextTrim());
}
}
-
+
// Loop to parse getEntry()
- * 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 getEntry()
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 {
- if (partial) throw new ProponoException("ERROR: attempt to update partial entry");
- EntityEnclosingMethod method = new PutMethod(getEditURI());
+ if (partial) {
+ throw new ProponoException("ERROR: attempt to update partial entry");
+ }
+ final EntityEnclosingMethod method = new PutMethod(getEditURI());
addAuthentication(method);
- StringWriter sw = new StringWriter();
- int code = -1;
+ final StringWriter sw = new StringWriter();
+ final int code = -1;
try {
Atom10Generator.serializeEntry(this, sw);
method.setRequestEntity(new StringRequestEntity(sw.toString()));
- method.setRequestHeader(
- "Content-type", "application/atom+xml; charset=utf-8");
+ method.setRequestHeader("Content-type", "application/atom+xml; charset=utf-8");
getHttpClient().executeMethod(method);
- InputStream is = method.getResponseBodyAsStream();
+ final InputStream is = method.getResponseBodyAsStream();
if (method.getStatusCode() != 200 && method.getStatusCode() != 201) {
- throw new ProponoException(
- "ERROR HTTP status=" + method.getStatusCode() + " : " + Utilities.streamToString(is));
+ throw new ProponoException("ERROR HTTP status=" + method.getStatusCode() + " : " + Utilities.streamToString(is));
}
- } catch (Exception e) {
- String msg = "ERROR: updating entry, HTTP code: " + code;
+ } catch (final Exception e) {
+ final String msg = "ERROR: updating entry, HTTP code: " + code;
logger.debug(msg, e);
throw new ProponoException(msg, e);
} finally {
method.releaseConnection();
- }
+ }
}
-
+
/**
* Remove entry from server.
*/
@@ -165,18 +161,18 @@ public class ClientEntry extends Entry {
if (getEditURI() == null) {
throw new ProponoException("ERROR: cannot delete unsaved entry");
}
- DeleteMethod method = new DeleteMethod(getEditURI());
+ final DeleteMethod method = new DeleteMethod(getEditURI());
addAuthentication(method);
try {
getHttpClient().executeMethod(method);
- } catch (IOException ex) {
+ } catch (final IOException ex) {
throw new ProponoException("ERROR: removing entry, HTTP code", ex);
} finally {
method.releaseConnection();
}
}
-
- void setCollection(ClientCollection collection) {
+
+ void setCollection(final ClientCollection collection) {
this.collection = collection;
}
@@ -186,67 +182,64 @@ public class ClientEntry extends Entry {
/**
* Get the URI that can be used to edit the entry via HTTP PUT or DELETE.
- */
+ */
public String getEditURI() {
- for (int i=0; iAppModule
form.
+ * Parses APP module information from a JDOM element and into AppModule
form.
*/
public class AppModuleParser implements ModuleParser {
/** Get URI of module namespace */
+ @Override
public String getNamespaceUri() {
return AppModule.URI;
}
@@ -41,26 +41,31 @@ public class AppModuleParser implements ModuleParser {
public Namespace getContentNamespace() {
return Namespace.getNamespace(AppModule.URI);
}
-
+
/** Parse JDOM element into module */
- public Module parse(Element elem) {
- boolean foundSomething = false;
- AppModule m = new AppModuleImpl();
- Element control = elem.getChild("control", getContentNamespace());
+ @Override
+ public Module parse(final Element elem) {
+ final boolean foundSomething = false;
+ final AppModule m = new AppModuleImpl();
+ final Element control = elem.getChild("control", getContentNamespace());
if (control != null) {
- Element draftElem = control.getChild("draft", getContentNamespace());
+ final Element draftElem = control.getChild("draft", getContentNamespace());
if (draftElem != null) {
- if ("yes".equals(draftElem.getText())) m.setDraft(Boolean.TRUE);
- if ("no".equals(draftElem.getText())) m.setDraft(Boolean.FALSE);
+ if ("yes".equals(draftElem.getText())) {
+ m.setDraft(Boolean.TRUE);
+ }
+ if ("no".equals(draftElem.getText())) {
+ m.setDraft(Boolean.FALSE);
+ }
}
}
- Element edited = elem.getChild("edited", getContentNamespace());
+ final Element edited = elem.getChild("edited", getContentNamespace());
if (edited != null) {
try {
m.setEdited(DateParser.parseW3CDateTime(edited.getTextTrim()));
- } catch (Exception ignored) {}
+ } catch (final Exception ignored) {
+ }
}
return m;
}
}
-
diff --git a/src/main/java/org/rometools/propono/atom/server/AtomException.java b/src/main/java/org/rometools/propono/atom/server/AtomException.java
index 7b88a1f..6e7848f 100644
--- a/src/main/java/org/rometools/propono/atom/server/AtomException.java
+++ b/src/main/java/org/rometools/propono/atom/server/AtomException.java
@@ -21,28 +21,30 @@ 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 {
/** Construct new exception */
public AtomException() {
super();
}
+
/** Construct new exception with message */
- public AtomException(String msg) {
+ public AtomException(final String msg) {
super(msg);
}
+
/** Contruct new exception with message and wrapping existing exception */
- public AtomException(String msg, Throwable t) {
+ public AtomException(final String msg, final Throwable t) {
super(msg, t);
}
+
/** Construct new exception to wrap existing one. */
- public AtomException(Throwable t) {
+ public AtomException(final Throwable t) {
super(t);
}
+
/* Get HTTP status code associated with exception (HTTP 500 server error) */
/**
* Get HTTP status associated with exception.
diff --git a/src/main/java/org/rometools/propono/atom/server/AtomHandler.java b/src/main/java/org/rometools/propono/atom/server/AtomHandler.java
index 9480b32..eaafc29 100644
--- a/src/main/java/org/rometools/propono/atom/server/AtomHandler.java
+++ b/src/main/java/org/rometools/propono/atom/server/AtomHandler.java
@@ -19,37 +19,32 @@
*/
package org.rometools.propono.atom.server;
-import com.sun.syndication.feed.atom.Entry;
-import com.sun.syndication.feed.atom.Feed;
import org.rometools.propono.atom.common.AtomService;
import org.rometools.propono.atom.common.Categories;
+import com.sun.syndication.feed.atom.Entry;
+import com.sun.syndication.feed.atom.Feed;
+
/**
* Interface for handling single Atom protocol requests.
- *
- * AtomHandlerFactory
. This static
- * method creates a new factory instance. This method uses the following
- * ordered lookup procedure to determine the AtomHandlerFactory
- * implementation class to load:
+ * Obtain a new instance of a AtomHandlerFactory
. This static method creates a new factory instance. This method uses the following ordered
+ * lookup procedure to determine the AtomHandlerFactory
implementation class to load:
*
- *
- *
- * Once an application has obtained a reference to a com.sun.syndication.propono.atom.server.AtomHandlerFactory
- * system property.
- * java.util.Properties
- * format and contains the fully qualified name of the implementation
- * class with the key being the system property defined above.
- *
- * The propono.properties file is read only once by Propono and it's
- * values are then cached for future use. If the file does not exist
- * when the first attempt is made to read from it, no further attempts
- * are made to check for its existence. It is not possible to change
- * the value of any property in propono.properties after it has been
- * read for the first time.
- * META-INF/services/com.sun.syndication.AtomHandlerFactory
- * in jars available to the runtime.
- * AtomHandlerFactory
instance.
- * com.sun.syndication.propono.atom.server.AtomHandlerFactory
system property.java.util.Properties
format and
+ * contains the fully qualified name of the implementation class with the key being the system property defined above.
+ *
+ * The propono.properties file is read only once by Propono and it's values are then cached for future use. If the file does not exist when the first
+ * attempt is made to read from it, no further attempts are made to check for its existence. It is not possible to change the value of any property in
+ * propono.properties after it has been read for the first time.META-INF/services/com.sun.syndication.AtomHandlerFactory
in jars available to the runtime.AtomHandlerFactory
instance.AtomHandlerFactory
- * it can use the factory to configure and obtain parser instances.
- *
+ *
+ * Once an application has obtained a reference to a AtomHandlerFactory
it can use the factory to configure and obtain parser instances.
+ *
* @return New instance of a AtomHandlerFactory
- *
- * @throws FactoryConfigurationError if the implementation is not available
- * or cannot be instantiated.
+ *
+ * @throws FactoryConfigurationError if the implementation is not available or cannot be instantiated.
*/
public static AtomHandlerFactory newInstance() {
try {
- return (AtomHandlerFactory)
- FactoryFinder.find(DEFAULT_PROPERTY_NAME, FALLBACK_IMPL_NAME);
- } catch (FactoryFinder.ConfigurationError e) {
+ return (AtomHandlerFactory) FactoryFinder.find(DEFAULT_PROPERTY_NAME, FALLBACK_IMPL_NAME);
+ } catch (final FactoryFinder.ConfigurationError e) {
log.error("ERROR: finding factory", e);
throw new FactoryConfigurationError(e.getException(), e.getMessage());
}
}
/**
- * Creates a new instance of a {@link com.sun.syndication.propono.atom.server.AtomHandler}
- * using the currently configured parameters.
- *
+ * Creates a new instance of a {@link com.sun.syndication.propono.atom.server.AtomHandler} using the currently configured parameters.
+ *
* @return A new instance of a AtomHandler.
- *
- * @throws AtomConfigurationException if a AtomHandler cannot be created
- * which satisfies the configuration requested.
+ *
+ * @throws AtomConfigurationException if a AtomHandler cannot be created which satisfies the configuration requested.
*/
- public abstract AtomHandler newAtomHandler(
- HttpServletRequest req, HttpServletResponse res);
+ public abstract AtomHandler newAtomHandler(HttpServletRequest req, HttpServletResponse res);
}
diff --git a/src/main/java/org/rometools/propono/atom/server/AtomMediaResource.java b/src/main/java/org/rometools/propono/atom/server/AtomMediaResource.java
index 41d1cf3..c742305 100644
--- a/src/main/java/org/rometools/propono/atom/server/AtomMediaResource.java
+++ b/src/main/java/org/rometools/propono/atom/server/AtomMediaResource.java
@@ -12,7 +12,7 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.rometools.propono.atom.server;
@@ -21,6 +21,7 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;
+
import javax.activation.FileTypeMap;
import javax.activation.MimetypesFileTypeMap;
@@ -28,42 +29,42 @@ import javax.activation.MimetypesFileTypeMap;
* Represents a media link entry.
*/
public class AtomMediaResource {
- private String contentType = null;
- private long contentLength = 0;
+ private String contentType = null;
+ private long contentLength = 0;
private InputStream inputStream = null;
- private Date lastModified = null;
+ private Date lastModified = null;
private static FileTypeMap map = null;
-
+
static {
- // TODO: figure out why PNG is missing from Java MIME types
+ // TODO: figure out why PNG is missing from Java MIME types
map = FileTypeMap.getDefaultFileTypeMap();
if (map instanceof MimetypesFileTypeMap) {
try {
- ((MimetypesFileTypeMap)map).addMimeTypes("image/png png PNG");
- } catch (Exception ignored) {}
- }
+ ((MimetypesFileTypeMap) map).addMimeTypes("image/png png PNG");
+ } catch (final Exception ignored) {
+ }
+ }
}
-
- public AtomMediaResource(File resource) throws FileNotFoundException {
+
+ public AtomMediaResource(final File resource) throws FileNotFoundException {
contentType = map.getContentType(resource.getName());
contentLength = resource.length();
lastModified = new Date(resource.lastModified());
inputStream = new FileInputStream(resource);
}
-
- public AtomMediaResource(String name, long length, Date lastModified, InputStream is)
- throws FileNotFoundException {
- this.contentType = map.getContentType(name);
- this.contentLength = length;
- this.lastModified = lastModified;
- this.inputStream = is;
+
+ public AtomMediaResource(final String name, final long length, final Date lastModified, final InputStream is) throws FileNotFoundException {
+ contentType = map.getContentType(name);
+ contentLength = length;
+ this.lastModified = lastModified;
+ inputStream = is;
}
-
+
public String getContentType() {
return contentType;
}
- public void setContentType(String contentType) {
+ public void setContentType(final String contentType) {
this.contentType = contentType;
}
@@ -71,7 +72,7 @@ public class AtomMediaResource {
return contentLength;
}
- public void setContentLength(long contentLength) {
+ public void setContentLength(final long contentLength) {
this.contentLength = contentLength;
}
@@ -79,7 +80,7 @@ public class AtomMediaResource {
return inputStream;
}
- public void setInputStream(InputStream inputStream) {
+ public void setInputStream(final InputStream inputStream) {
this.inputStream = inputStream;
}
@@ -87,9 +88,8 @@ public class AtomMediaResource {
return lastModified;
}
- public void setLastModified(Date lastModified) {
+ public void setLastModified(final Date lastModified) {
this.lastModified = lastModified;
}
-
}
diff --git a/src/main/java/org/rometools/propono/atom/server/AtomNotAuthorizedException.java b/src/main/java/org/rometools/propono/atom/server/AtomNotAuthorizedException.java
index c5ce57a..0879dc7 100644
--- a/src/main/java/org/rometools/propono/atom/server/AtomNotAuthorizedException.java
+++ b/src/main/java/org/rometools/propono/atom/server/AtomNotAuthorizedException.java
@@ -22,27 +22,31 @@ package org.rometools.propono.atom.server;
import javax.servlet.http.HttpServletResponse;
/**
- * Exception to be thrown by AtomHandler
implementations in the
- * case that a user is not authorized to access a resource.
+ * Exception to be thrown by AtomHandler
implementations in the case that a user is not authorized to access a resource.
*/
public class AtomNotAuthorizedException extends AtomException {
/** Construct new exception */
public AtomNotAuthorizedException() {
super();
}
+
/** Construct new exception with message */
- public AtomNotAuthorizedException(String msg) {
+ public AtomNotAuthorizedException(final String msg) {
super(msg);
}
+
/** Construct new exception with message and root cause */
- public AtomNotAuthorizedException(String msg, Throwable t) {
+ public AtomNotAuthorizedException(final String msg, final Throwable t) {
super(msg, t);
}
- /** Construct new exception to wrap root cause*/
- public AtomNotAuthorizedException(Throwable t) {
+
+ /** Construct new exception to wrap root cause */
+ public AtomNotAuthorizedException(final Throwable t) {
super(t);
}
+
/** Get HTTP status code of exception (HTTP 403 unauthorized) */
+ @Override
public int getStatus() {
return HttpServletResponse.SC_UNAUTHORIZED;
}
diff --git a/src/main/java/org/rometools/propono/atom/server/AtomNotFoundException.java b/src/main/java/org/rometools/propono/atom/server/AtomNotFoundException.java
index ec6f779..6a8c8d2 100644
--- a/src/main/java/org/rometools/propono/atom/server/AtomNotFoundException.java
+++ b/src/main/java/org/rometools/propono/atom/server/AtomNotFoundException.java
@@ -29,19 +29,24 @@ public class AtomNotFoundException extends AtomException {
public AtomNotFoundException() {
super();
}
+
/** Construct new exception with message */
- public AtomNotFoundException(String msg) {
+ public AtomNotFoundException(final String msg) {
super(msg);
}
+
/** Construct new exception with message and root cause */
- public AtomNotFoundException(String msg, Throwable t) {
+ public AtomNotFoundException(final String msg, final Throwable t) {
super(msg, t);
}
+
/** Construct new exception with root cause */
- public AtomNotFoundException(Throwable t) {
+ public AtomNotFoundException(final Throwable t) {
super(t);
}
+
/** Get HTTP status code associated with exception (404 not found) */
+ @Override
public int getStatus() {
return HttpServletResponse.SC_NOT_FOUND;
}
diff --git a/src/main/java/org/rometools/propono/atom/server/AtomRequest.java b/src/main/java/org/rometools/propono/atom/server/AtomRequest.java
index 1610684..33b20dc 100644
--- a/src/main/java/org/rometools/propono/atom/server/AtomRequest.java
+++ b/src/main/java/org/rometools/propono/atom/server/AtomRequest.java
@@ -30,110 +30,98 @@ import java.util.Map;
*/
public interface AtomRequest {
- /**
- * Returns any extra path information associated with the URL the client
- * sent when it made this request.
+ /**
+ * Returns any extra path information associated with the URL the client sent when it made this request.
*/
public String getPathInfo();
- /**
- * Returns the query string that is contained in the request URL after
- * the path.
+ /**
+ * Returns the query string that is contained in the request URL after the path.
*/
public String getQueryString();
- /**
- * Returns the login of the user making this request, if the user has
- * been authenticated, or null if the user has not been authenticated.
+ /**
+ * Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.
*/
public String getRemoteUser();
- /**
- * Returns a boolean indicating whether the authenticated user is included
- * in the specified logical "role".
+ /**
+ * Returns a boolean indicating whether the authenticated user is included in the specified logical "role".
*/
public boolean isUserInRole(String arg0);
- /**
- * Returns a java.security.Principal object containing the name of the
- * current authenticated user.
+ /**
+ * Returns a java.security.Principal object containing the name of the current authenticated user.
*/
public Principal getUserPrincipal();
- /**
- * Returns the part of this request's URL from the protocol name up to the
- * query string in the first line of the HTTP request.
+ /**
+ * Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request.
*/
public String getRequestURI();
- /**
- * Reconstructs the URL the client used to make the request.
+ /**
+ * Reconstructs the URL the client used to make the request.
*/
public StringBuffer getRequestURL();
- /**
- * Returns the length, in bytes, of the request body and made available by
- * the input stream, or -1 if the length is not known.
+ /**
+ * Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known.
*/
public int getContentLength();
- /**
- * Returns the MIME type of the body of the request, or null if the type
- * is not known. */
+ /**
+ * Returns the MIME type of the body of the request, or null if the type is not known.
+ */
public String getContentType();
- /**
- * Returns the value of a request parameter as a String, or null if the
- * parameter does not exist.
+ /**
+ * Returns the value of a request parameter as a String, or null if the parameter does not exist.
*/
public String getParameter(String arg0);
- /**
- * Returns an Enumeration of String objects containing the names of the
- * parameters contained in this request.
+ /**
+ * Returns an Enumeration of String objects containing the names of the parameters contained in this request.
*/
public Enumeration getParameterNames();
- /**
- * Returns an array of String objects containing all of the values the
- * given request parameter has, or null if the parameter does not exist.
+ /**
+ * Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.
*/
public String[] getParameterValues(String arg0);
- /**
- * Returns a java.util.Map of the parameters of this request.
+ /**
+ * Returns a java.util.Map of the parameters of this request.
*/
public Map getParameterMap();
- /**
- * Retrieves the body of the request as binary data using a
- * ServletInputStream.
+ /**
+ * Retrieves the body of the request as binary data using a ServletInputStream.
*/
public InputStream getInputStream() throws IOException;
- /**
- * Returns the value of the specified request header as a long value that
- * represents a Date object. */
+ /**
+ * Returns the value of the specified request header as a long value that represents a Date object.
+ */
public long getDateHeader(String arg0);
- /**
- * Returns the value of the specified request header as a String.
+ /**
+ * Returns the value of the specified request header as a String.
*/
public String getHeader(String arg0);
- /**
- * Returns all the values of the specified request header as an Enumeration
- * of String objects.
+ /**
+ * Returns all the values of the specified request header as an Enumeration of String objects.
*/
public Enumeration getHeaders(String arg0);
- /**
- * Returns an enumeration of all the header names this request contains.
+ /**
+ * Returns an enumeration of all the header names this request contains.
*/
public Enumeration getHeaderNames();
- /**
- * Returns the value of the specified request header as an int.
+ /**
+ * Returns the value of the specified request header as an int.
*/
public int getIntHeader(String arg0);
}
diff --git a/src/main/java/org/rometools/propono/atom/server/AtomRequestImpl.java b/src/main/java/org/rometools/propono/atom/server/AtomRequestImpl.java
index 0efcdf9..ce75614 100644
--- a/src/main/java/org/rometools/propono/atom/server/AtomRequestImpl.java
+++ b/src/main/java/org/rometools/propono/atom/server/AtomRequestImpl.java
@@ -24,6 +24,7 @@ import java.io.InputStream;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Map;
+
import javax.servlet.http.HttpServletRequest;
/**
@@ -31,84 +32,103 @@ import javax.servlet.http.HttpServletRequest;
*/
public class AtomRequestImpl implements AtomRequest {
private HttpServletRequest wrapped = null;
-
- public AtomRequestImpl(HttpServletRequest wrapped) {
+
+ public AtomRequestImpl(final HttpServletRequest wrapped) {
this.wrapped = wrapped;
}
+ @Override
public String getPathInfo() {
return wrapped.getPathInfo() != null ? wrapped.getPathInfo() : "";
}
+ @Override
public String getQueryString() {
return wrapped.getQueryString();
}
+ @Override
public String getRemoteUser() {
return wrapped.getRemoteUser();
}
- public boolean isUserInRole(String arg0) {
+ @Override
+ public boolean isUserInRole(final String arg0) {
return wrapped.isUserInRole(arg0);
}
+ @Override
public Principal getUserPrincipal() {
return wrapped.getUserPrincipal();
}
+ @Override
public String getRequestURI() {
return wrapped.getRequestURI();
}
+ @Override
public StringBuffer getRequestURL() {
return wrapped.getRequestURL();
}
+ @Override
public int getContentLength() {
return wrapped.getContentLength();
}
+ @Override
public String getContentType() {
return wrapped.getContentType();
}
- public String getParameter(String arg0) {
+ @Override
+ public String getParameter(final String arg0) {
return wrapped.getParameter(arg0);
}
+ @Override
public Enumeration getParameterNames() {
return wrapped.getParameterNames();
}
- public String[] getParameterValues(String arg0) {
+ @Override
+ public String[] getParameterValues(final String arg0) {
return wrapped.getParameterValues(arg0);
}
+ @Override
public Map getParameterMap() {
return wrapped.getParameterMap();
}
-
- public InputStream getInputStream() throws IOException {
- return wrapped.getInputStream();
- }
- public long getDateHeader(String arg0) {
+ @Override
+ public InputStream getInputStream() throws IOException {
+ return wrapped.getInputStream();
+ }
+
+ @Override
+ public long getDateHeader(final String arg0) {
return wrapped.getDateHeader(arg0);
}
- public String getHeader(String arg0) {
+ @Override
+ public String getHeader(final String arg0) {
return wrapped.getHeader(arg0);
}
- public Enumeration getHeaders(String arg0) {
+ @Override
+ public Enumeration getHeaders(final String arg0) {
return wrapped.getHeaders(arg0);
}
+ @Override
public Enumeration getHeaderNames() {
return wrapped.getHeaderNames();
}
- public int getIntHeader(String arg0) {
+ @Override
+ public int getIntHeader(final String arg0) {
return wrapped.getIntHeader(arg0);
}
}
diff --git a/src/main/java/org/rometools/propono/atom/server/AtomServlet.java b/src/main/java/org/rometools/propono/atom/server/AtomServlet.java
index 707a4f6..1ff7a2a 100644
--- a/src/main/java/org/rometools/propono/atom/server/AtomServlet.java
+++ b/src/main/java/org/rometools/propono/atom/server/AtomServlet.java
@@ -19,143 +19,134 @@
*/
package org.rometools.propono.atom.server;
-import com.sun.syndication.feed.atom.Content;
+import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
+import java.util.Collections;
+
+import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom2.Document;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
+import org.rometools.propono.atom.common.AtomService;
+import org.rometools.propono.atom.common.Categories;
+import org.rometools.propono.utils.Utilities;
+
+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.io.WireFeedOutput;
import com.sun.syndication.io.impl.Atom10Generator;
import com.sun.syndication.io.impl.Atom10Parser;
-import org.rometools.propono.atom.common.AtomService;
-import org.rometools.propono.atom.common.Categories;
-import org.rometools.propono.utils.Utilities;
-import java.io.BufferedReader;
-import java.util.Collections;
-import java.util.Iterator;
-import javax.servlet.ServletConfig;
/**
- * 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 {
-
+
/**
* Get feed type support by Servlet, "atom_1.0"
*/
public static final String FEED_TYPE = "atom_1.0";
private static String contextDirPath = null;
- private static Log log =
- LogFactory.getFactory().getInstance(AtomServlet.class);
-
+ private static Log log = LogFactory.getFactory().getInstance(AtomServlet.class);
+
static {
Atom10Parser.setResolveURIs(true);
}
-
- //-----------------------------------------------------------------------------
+
+ // -----------------------------------------------------------------------------
/**
- * Create an Atom request handler.
- * TODO: make AtomRequestHandler implementation configurable.
+ * Create an Atom request handler. TODO: make AtomRequestHandler implementation configurable.
*/
- private AtomHandler createAtomRequestHandler(
- HttpServletRequest request, HttpServletResponse response)
- throws ServletException {
- AtomHandlerFactory ahf = AtomHandlerFactory.newInstance();
+ private AtomHandler createAtomRequestHandler(final HttpServletRequest request, final HttpServletResponse response) throws ServletException {
+ final AtomHandlerFactory ahf = AtomHandlerFactory.newInstance();
return ahf.newAtomHandler(request, response);
}
- //-----------------------------------------------------------------------------
+ // -----------------------------------------------------------------------------
/**
* Handles an Atom GET by calling handler and writing results to response.
*/
- protected void doGet(HttpServletRequest req, HttpServletResponse res)
- throws ServletException, IOException {
+ @Override
+ protected void doGet(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException {
log.debug("Entering");
- AtomHandler handler = createAtomRequestHandler(req, res);
- String userName = handler.getAuthenticatedUsername();
+ final AtomHandler handler = createAtomRequestHandler(req, res);
+ final String userName = handler.getAuthenticatedUsername();
if (userName != null) {
- AtomRequest areq = new AtomRequestImpl(req);
+ final AtomRequest areq = new AtomRequestImpl(req);
try {
if (handler.isAtomServiceURI(areq)) {
// return an Atom Service document
- AtomService service = handler.getAtomService(areq);
- Document doc = service.serviceToDocument();
+ final AtomService service = handler.getAtomService(areq);
+ final Document doc = service.serviceToDocument();
res.setContentType("application/atomsvc+xml; charset=utf-8");
- Writer writer = res.getWriter();
- XMLOutputter outputter = new XMLOutputter();
+ final Writer writer = res.getWriter();
+ final XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
outputter.output(doc, writer);
writer.close();
res.setStatus(HttpServletResponse.SC_OK);
- }
- else if (handler.isCategoriesURI(areq)) {
- Categories cats = handler.getCategories(areq);
+ } else if (handler.isCategoriesURI(areq)) {
+ final Categories cats = handler.getCategories(areq);
res.setContentType("application/xml");
- Writer writer = res.getWriter();
- Document catsDoc = new Document();
+ final Writer writer = res.getWriter();
+ final Document catsDoc = new Document();
catsDoc.setRootElement(cats.categoriesToElement());
- XMLOutputter outputter = new XMLOutputter();
+ final XMLOutputter outputter = new XMLOutputter();
outputter.output(catsDoc, writer);
writer.close();
res.setStatus(HttpServletResponse.SC_OK);
- }
- else if (handler.isCollectionURI(areq)) {
+ } else if (handler.isCollectionURI(areq)) {
// return a collection
- Feed col = handler.getCollection(areq);
+ final Feed col = handler.getCollection(areq);
col.setFeedType(FEED_TYPE);
- WireFeedOutput wireFeedOutput = new WireFeedOutput();
- Document feedDoc = wireFeedOutput.outputJDom(col);
+ final WireFeedOutput wireFeedOutput = new WireFeedOutput();
+ final Document feedDoc = wireFeedOutput.outputJDom(col);
res.setContentType("application/atom+xml; charset=utf-8");
- Writer writer = res.getWriter();
- XMLOutputter outputter = new XMLOutputter();
+ final Writer writer = res.getWriter();
+ final XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
outputter.output(feedDoc, writer);
writer.close();
res.setStatus(HttpServletResponse.SC_OK);
- }
- else if (handler.isEntryURI(areq)) {
+ } else if (handler.isEntryURI(areq)) {
// return an entry
- Entry entry = handler.getEntry(areq);
+ final Entry entry = handler.getEntry(areq);
if (entry != null) {
res.setContentType("application/atom+xml; type=entry; charset=utf-8");
- Writer writer = res.getWriter();
+ final Writer writer = res.getWriter();
Atom10Generator.serializeEntry(entry, writer);
writer.close();
} else {
res.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
- }
- else if (handler.isMediaEditURI(areq)) {
- AtomMediaResource entry = handler.getMediaResource(areq);
+ } else if (handler.isMediaEditURI(areq)) {
+ final AtomMediaResource entry = handler.getMediaResource(areq);
res.setContentType(entry.getContentType());
- res.setContentLength((int)entry.getContentLength());
+ res.setContentLength((int) entry.getContentLength());
Utilities.copyInputToOutput(entry.getInputStream(), res.getOutputStream());
res.getOutputStream().flush();
res.getOutputStream().close();
- }
- else {
+ } else {
res.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
- } catch (AtomException ae) {
+ } catch (final AtomException ae) {
res.sendError(ae.getStatus(), ae.getMessage());
log.debug("ERROR processing GET", ae);
- } catch (Exception e) {
+ } catch (final Exception e) {
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
log.debug("ERROR processing GET", e);
}
@@ -165,41 +156,39 @@ public class AtomServlet extends HttpServlet {
}
log.debug("Exiting");
}
-
- //-----------------------------------------------------------------------------
+
+ // -----------------------------------------------------------------------------
/**
- * 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.
*/
- protected void doPost(HttpServletRequest req, HttpServletResponse res)
- throws ServletException, IOException {
+ @Override
+ protected void doPost(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException {
log.debug("Entering");
- AtomHandler handler = createAtomRequestHandler(req, res);
- String userName = handler.getAuthenticatedUsername();
+ final AtomHandler handler = createAtomRequestHandler(req, res);
+ final String userName = handler.getAuthenticatedUsername();
if (userName != null) {
- AtomRequest areq = new AtomRequestImpl(req);
+ final AtomRequest areq = new AtomRequestImpl(req);
try {
if (handler.isCollectionURI(areq)) {
-
+
if (req.getContentType().startsWith("application/atom+xml")) {
// parse incoming entry
- Entry entry = Atom10Parser.parseEntry(new BufferedReader(
- new InputStreamReader(req.getInputStream(), "UTF-8")), null);
+ final Entry entry = Atom10Parser.parseEntry(new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8")), null);
// call handler to post it
- Entry newEntry = handler.postEntry(areq, entry);
+ final Entry newEntry = handler.postEntry(areq, entry);
- // set Location and Content-Location headers
- for (Iterator it = newEntry.getOtherLinks().iterator(); it.hasNext();) {
- Link link = (Link) it.next();
+ // set Location and Content-Location headers
+ for (final Object element : newEntry.getOtherLinks()) {
+ final Link link = (Link) element;
if ("edit".equals(link.getRel())) {
res.addHeader("Location", link.getHrefResolved());
break;
}
}
- for (Iterator it = newEntry.getAlternateLinks().iterator(); it.hasNext();) {
- Link link = (Link) it.next();
+ for (final Object element : newEntry.getAlternateLinks()) {
+ final Link link = (Link) element;
if ("alternate".equals(link.getRel())) {
res.addHeader("Content-Location", link.getHrefResolved());
break;
@@ -209,62 +198,60 @@ public class AtomServlet extends HttpServlet {
// write entry back out to response
res.setStatus(HttpServletResponse.SC_CREATED);
res.setContentType("application/atom+xml; type=entry; charset=utf-8");
-
- Writer writer = res.getWriter();
+
+ final Writer writer = res.getWriter();
Atom10Generator.serializeEntry(newEntry, writer);
- writer.close();
-
+ writer.close();
+
} else if (req.getContentType() != null) {
-
+
// get incoming title and slug from HTTP header
- String title = areq.getHeader("Title");
+ final String title = areq.getHeader("Title");
// create new entry for resource, set title and type
- Entry resource = new Entry();
+ final Entry resource = new Entry();
resource.setTitle(title);
- Content content = new Content();
+ final Content content = new Content();
content.setType(areq.getContentType());
resource.setContents(Collections.singletonList(content));
-
+
// hand input stream off to hander to post file
- Entry newEntry = handler.postMedia(areq, resource);
+ final Entry newEntry = handler.postMedia(areq, resource);
// set Location and Content-Location headers
- for (Iterator it = newEntry.getOtherLinks().iterator(); it.hasNext();) {
- Link link = (Link) it.next();
+ for (final Object element : newEntry.getOtherLinks()) {
+ final Link link = (Link) element;
if ("edit".equals(link.getRel())) {
res.addHeader("Location", link.getHrefResolved());
break;
}
}
- for (Iterator it = newEntry.getAlternateLinks().iterator(); it.hasNext();) {
- Link link = (Link) it.next();
+ for (final Object element : newEntry.getAlternateLinks()) {
+ final Link link = (Link) element;
if ("alternate".equals(link.getRel())) {
res.addHeader("Content-Location", link.getHrefResolved());
break;
}
}
-
- res.setStatus(HttpServletResponse.SC_CREATED);
+
+ res.setStatus(HttpServletResponse.SC_CREATED);
res.setContentType("application/atom+xml; type=entry; charset=utf-8");
-
- Writer writer = res.getWriter();
+
+ final Writer writer = res.getWriter();
Atom10Generator.serializeEntry(newEntry, writer);
- writer.close();
-
+ writer.close();
+
} else {
- res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
- "No content-type specified in request");
+ res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "No content-type specified in request");
}
-
+
} else {
- res.sendError(HttpServletResponse.SC_NOT_FOUND,
- "Invalid collection specified in request");
+ res.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid collection specified in request");
}
- } catch (AtomException ae) {
+ } catch (final AtomException ae) {
res.sendError(ae.getStatus(), ae.getMessage());
log.debug("ERROR processing POST", ae);
- } catch (Exception e) {
+ } catch (final Exception e) {
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
log.debug("ERROR processing POST", e);
}
@@ -274,101 +261,99 @@ public class AtomServlet extends HttpServlet {
}
log.debug("Exiting");
}
-
- //-----------------------------------------------------------------------------
+
+ // -----------------------------------------------------------------------------
/**
- * 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.
*/
- protected void doPut(HttpServletRequest req, HttpServletResponse res)
- throws ServletException, IOException {
+ @Override
+ protected void doPut(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException {
log.debug("Entering");
- AtomHandler handler = createAtomRequestHandler(req, res);
- String userName = handler.getAuthenticatedUsername();
+ final AtomHandler handler = createAtomRequestHandler(req, res);
+ final String userName = handler.getAuthenticatedUsername();
if (userName != null) {
- AtomRequest areq = new AtomRequestImpl(req);
+ final AtomRequest areq = new AtomRequestImpl(req);
try {
if (handler.isEntryURI(areq)) {
-
+
// parse incoming entry
- Entry unsavedEntry = Atom10Parser.parseEntry(new BufferedReader(
- new InputStreamReader(req.getInputStream(), "UTF-8")), null);
-
+ final Entry unsavedEntry = Atom10Parser.parseEntry(new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8")), null);
+
// call handler to put entry
handler.putEntry(areq, unsavedEntry);
-
+
res.setStatus(HttpServletResponse.SC_OK);
-
+
} else if (handler.isMediaEditURI(areq)) {
-
+
// hand input stream to handler
handler.putMedia(areq);
-
+
res.setStatus(HttpServletResponse.SC_OK);
-
+
} else {
res.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
- } catch (AtomException ae) {
+ } catch (final AtomException ae) {
res.sendError(ae.getStatus(), ae.getMessage());
log.debug("ERROR processing PUT", ae);
- } catch (Exception e) {
+ } catch (final Exception e) {
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
log.debug("ERROR processing PUT", e);
}
} else {
res.setHeader("WWW-Authenticate", "BASIC realm=\"AtomPub\"");
- // Wanted to use sendError() here but Tomcat sends 403 forbidden
+ // Wanted to use sendError() here but Tomcat sends 403 forbidden
// when I do that, so sticking with setStatus() for time being.
res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
log.debug("Exiting");
}
-
- //-----------------------------------------------------------------------------
+
+ // -----------------------------------------------------------------------------
/**
* Handle Atom DELETE by calling appropriate handler.
*/
- protected void doDelete(HttpServletRequest req, HttpServletResponse res)
- throws ServletException, IOException {
+ @Override
+ protected void doDelete(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException {
log.debug("Entering");
- AtomHandler handler = createAtomRequestHandler(req, res);
- String userName = handler.getAuthenticatedUsername();
+ final AtomHandler handler = createAtomRequestHandler(req, res);
+ final String userName = handler.getAuthenticatedUsername();
if (userName != null) {
- AtomRequest areq = new AtomRequestImpl(req);
+ final AtomRequest areq = new AtomRequestImpl(req);
try {
if (handler.isEntryURI(areq)) {
handler.deleteEntry(areq);
res.setStatus(HttpServletResponse.SC_OK);
- }
- else {
+ } else {
res.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
- } catch (AtomException ae) {
+ } catch (final AtomException ae) {
res.sendError(ae.getStatus(), ae.getMessage());
log.debug("ERROR processing DELETE", ae);
- } catch (Exception e) {
+ } catch (final Exception e) {
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
log.debug("ERROR processing DELETE", e);
}
} else {
res.setHeader("WWW-Authenticate", "BASIC realm=\"AtomPub\"");
- // Wanted to use sendError() here but Tomcat sends 403 forbidden
+ // Wanted to use sendError() here but Tomcat sends 403 forbidden
// when I do that, so sticking with setStatus() for time being.
res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
log.debug("Exiting");
}
-
+
/**
* Initialize servlet.
*/
- public void init( ServletConfig config ) throws ServletException {
- super.init( config );
+ @Override
+ public void init(final ServletConfig config) throws ServletException {
+ super.init(config);
contextDirPath = getServletContext().getRealPath("/");
-
+
}
-
+
/**
* Get absolute path to Servlet context directory.
*/
diff --git a/src/main/java/org/rometools/propono/atom/server/FactoryConfigurationError.java b/src/main/java/org/rometools/propono/atom/server/FactoryConfigurationError.java
index 2ae8c6a..ccd2c59 100644
--- a/src/main/java/org/rometools/propono/atom/server/FactoryConfigurationError.java
+++ b/src/main/java/org/rometools/propono/atom/server/FactoryConfigurationError.java
@@ -12,94 +12,81 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
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 {
-
+
/**
* Exception
that represents the error.
*/
- private Exception exception;
-
+ private final Exception exception;
+
/**
- * Create a new FactoryConfigurationError
with no
- * detail mesage.
- */
+ * Create a new FactoryConfigurationError
with no detail mesage.
+ */
public FactoryConfigurationError() {
super();
- this.exception = null;
+ exception = null;
}
-
+
/**
- * Create a new FactoryConfigurationError
with
- * the String
specified as an error message.
- *
+ * Create a new FactoryConfigurationError
with the String
specified as an error message.
+ *
* @param msg The error message for the exception.
- */
- public FactoryConfigurationError(String msg) {
+ */
+ public FactoryConfigurationError(final String msg) {
super(msg);
- this.exception = null;
+ exception = null;
}
-
-
+
/**
- * Create a new FactoryConfigurationError
with a
- * given Exception
base cause of the error.
- *
- * @param e The exception to be encapsulated in a
- * FactoryConfigurationError.
- */
- public FactoryConfigurationError(Exception e) {
+ * Create a new FactoryConfigurationError
with a given Exception
base cause of the error.
+ *
+ * @param e The exception to be encapsulated in a FactoryConfigurationError.
+ */
+ public FactoryConfigurationError(final Exception e) {
super(e.toString());
- this.exception = e;
+ exception = e;
}
-
+
/**
- * Create a new FactoryConfigurationError
with the
- * given Exception
base cause and detail message.
- *
- * @param e The exception to be encapsulated in a
- * FactoryConfigurationError
+ * Create a new FactoryConfigurationError
with the given Exception
base cause and detail message.
+ *
+ * @param e The exception to be encapsulated in a FactoryConfigurationError
* @param msg The detail message.
- */
- public FactoryConfigurationError(Exception e, String msg) {
+ */
+ public FactoryConfigurationError(final Exception e, final String msg) {
super(msg);
- this.exception = e;
+ exception = e;
}
-
-
+
/**
- * 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
public String getMessage() {
- String message = super.getMessage();
-
+ final String message = super.getMessage();
+
if (message == null && exception != null) {
return exception.getMessage();
}
-
+
return message;
}
-
+
/**
- * Return the actual exception (if any) that caused this exception to
- * be raised.
- *
+ * 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() {
return exception;
}
diff --git a/src/main/java/org/rometools/propono/atom/server/FactoryFinder.java b/src/main/java/org/rometools/propono/atom/server/FactoryFinder.java
index 2545703..ff46f75 100644
--- a/src/main/java/org/rometools/propono/atom/server/FactoryFinder.java
+++ b/src/main/java/org/rometools/propono/atom/server/FactoryFinder.java
@@ -15,48 +15,38 @@
*/
package org.rometools.propono.atom.server;
-import java.io.File;
-import java.io.FileInputStream;
-
-import java.util.Properties;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
-import java.net.URL;
+import java.util.Properties;
/**
* 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 Properties cacheProps = new Properties();
+ static SecuritySupport ss = new SecuritySupport();
static boolean firstTime = true;
-
- private static void dPrint(String msg) {
+
+ private static void dPrint(final String msg) {
if (debug) {
System.err.println("Propono: " + msg);
}
}
-
+
/**
- * 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
+ * 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
*/
- private static Object newInstance(
- String className, ClassLoader cl, boolean doFallback)
- throws ConfigurationError {
-
+ private static Object newInstance(final String className, ClassLoader cl, final boolean doFallback) throws ConfigurationError {
+
try {
Class providerClass;
if (cl == null) {
@@ -67,7 +57,7 @@ class FactoryFinder {
} else {
try {
providerClass = cl.loadClass(className);
- } catch (ClassNotFoundException x) {
+ } catch (final ClassNotFoundException x) {
if (doFallback) {
// Fall back to current classloader
cl = FactoryFinder.class.getClassLoader();
@@ -77,119 +67,114 @@ class FactoryFinder {
}
}
}
-
- Object instance = providerClass.newInstance();
- dPrint("created new instance of " + providerClass +
- " using ClassLoader: " + cl);
+
+ final Object instance = providerClass.newInstance();
+ dPrint("created new instance of " + providerClass + " using ClassLoader: " + cl);
return instance;
- } catch (ClassNotFoundException x) {
- throw new ConfigurationError(
- "Provider " + className + " not found", x);
- } catch (Exception x) {
- throw new ConfigurationError(
- "Provider " + className + " could not be instantiated: " + x, x);
+ } catch (final ClassNotFoundException x) {
+ throw new ConfigurationError("Provider " + className + " not found", x);
+ } catch (final Exception x) {
+ throw new ConfigurationError("Provider " + className + " could not be instantiated: " + x, x);
}
}
-
+
/**
- * Finds the implementation Class object in the specified order. Main
- * entry point.
+ * 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.
- *
- * Package private so this code can be shared.
+ *
+ * @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.
+ *
+ * Package private so this code can be shared.
*/
- static Object find(String factoryId, String fallbackClassName)
- throws ConfigurationError {
-
+ static Object find(final String factoryId, final String fallbackClassName) throws ConfigurationError {
+
// Figure out which ClassLoader to use for loading the provider
- // class. If there is a Context ClassLoader then use it.
-
+ // class. If there is a Context ClassLoader then use it.
+
ClassLoader classLoader = ss.getContextClassLoader();
-
+
if (classLoader == null) {
// if we have no Context ClassLoader
// so use the current ClassLoader
classLoader = FactoryFinder.class.getClassLoader();
}
-
+
dPrint("find factoryId =" + factoryId);
-
+
// Use the system property first
try {
- String systemProp = ss.getSystemProperty(factoryId);
- if( systemProp!=null) {
+ final String systemProp = ss.getSystemProperty(factoryId);
+ if (systemProp != null) {
dPrint("found system property, value=" + systemProp);
- return newInstance(systemProp, classLoader, true );
+ return newInstance(systemProp, classLoader, true);
}
- } catch (SecurityException se) {
- //if first option fails due to any reason we should try next option in the
- //look up algorithm.
+ } catch (final SecurityException se) {
+ // if first option fails due to any reason we should try next option in the
+ // look up algorithm.
}
-
+
// try to read from /propono.properties
try {
- String javah = ss.getSystemProperty("java.home");
- String configFile = "/propono.properties";
+ final String javah = ss.getSystemProperty("java.home");
+ final String configFile = "/propono.properties";
String factoryClassName = null;
- if(firstTime){
- synchronized(cacheProps){
+ if (firstTime) {
+ synchronized (cacheProps) {
if (firstTime) {
try {
- InputStream is = FactoryFinder.class.getResourceAsStream(configFile);
- firstTime = false;
- if (is != null) {
- dPrint("Read properties file: " + configFile);
- cacheProps.load(is);
- }
- } catch (Exception intentionallyIgnored) {}
+ final InputStream is = FactoryFinder.class.getResourceAsStream(configFile);
+ firstTime = false;
+ if (is != null) {
+ dPrint("Read properties file: " + configFile);
+ cacheProps.load(is);
+ }
+ } catch (final Exception intentionallyIgnored) {
+ }
}
}
}
factoryClassName = cacheProps.getProperty(factoryId);
-
- if(factoryClassName != null){
+
+ if (factoryClassName != null) {
dPrint("found in $java.home/propono.properties, value=" + factoryClassName);
return newInstance(factoryClassName, classLoader, true);
}
- } catch(Exception ex) {
- if( debug ) ex.printStackTrace();
+ } catch (final Exception ex) {
+ if (debug) {
+ ex.printStackTrace();
+ }
}
-
+
// Try Jar Service Provider Mechanism
- Object provider = findJarServiceProvider(factoryId);
+ final Object provider = findJarServiceProvider(factoryId);
if (provider != null) {
return provider;
}
if (fallbackClassName == null) {
- throw new ConfigurationError(
- "Provider for " + factoryId + " cannot be found", null);
+ throw new ConfigurationError("Provider for " + factoryId + " cannot be found", null);
}
-
+
dPrint("loaded from fallback value: " + fallbackClassName);
return newInstance(fallbackClassName, classLoader, true);
}
-
+
/*
* Try to find provider using Jar Service Provider Mechanism
- *
+ *
* @return instance of provider class if found or null
*/
- private static Object findJarServiceProvider(String factoryId)
- throws ConfigurationError {
-
- String serviceId = "META-INF/services/" + factoryId;
+ private static Object findJarServiceProvider(final String factoryId) throws ConfigurationError {
+
+ final String serviceId = "META-INF/services/" + factoryId;
InputStream is = null;
-
+
// First try the Context ClassLoader
ClassLoader cl = ss.getContextClassLoader();
if (cl != null) {
is = ss.getResourceAsStream(cl, serviceId);
-
+
// If no provider found then try the current ClassLoader
if (is == null) {
cl = FactoryFinder.class.getClassLoader();
@@ -201,21 +186,20 @@ class FactoryFinder {
cl = FactoryFinder.class.getClassLoader();
is = ss.getResourceAsStream(cl, serviceId);
}
-
+
if (is == null) {
// No provider found
return null;
}
-
- dPrint("found jar resource=" + serviceId +
- " using ClassLoader: " + cl);
-
+
+ dPrint("found jar resource=" + serviceId + " using ClassLoader: " + cl);
+
// Read the service provider name in UTF-8 as specified in
- // the jar spec. Unfortunately this fails in Microsoft
+ // the jar spec. Unfortunately this fails in Microsoft
// VJ++, which does not implement the UTF-8
// encoding. Theoretically, we should simply let it fail in
// that case, since the JVM is obviously broken if it
- // doesn't support such a basic standard. But since there
+ // doesn't support such a basic standard. But since there
// are still some users attempting to use VJ++ for
// development, we have dropped in a fallback which makes a
// second attempt using the platform's default encoding. In
@@ -229,52 +213,49 @@ class FactoryFinder {
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
- } catch (java.io.UnsupportedEncodingException e) {
+ } catch (final java.io.UnsupportedEncodingException e) {
rd = new BufferedReader(new InputStreamReader(is));
}
-
+
String factoryClassName = null;
try {
// XXX Does not handle all possible input as specified by the
// Jar Service Provider specification
factoryClassName = rd.readLine();
rd.close();
- } catch (IOException x) {
+ } catch (final IOException x) {
// No provider found
return null;
}
-
- if (factoryClassName != null &&
- ! "".equals(factoryClassName)) {
- dPrint("found in resource, value="
- + factoryClassName);
-
+
+ if (factoryClassName != null && !"".equals(factoryClassName)) {
+ dPrint("found in resource, value=" + factoryClassName);
+
// Note: here we do not want to fall back to the current
// ClassLoader because we want to avoid the case where the
// resource file was found using one ClassLoader and the
// provider class was instantiated using a different one.
return newInstance(factoryClassName, cl, false);
}
-
+
// No provider found
return null;
}
-
+
static class ConfigurationError extends Error {
- private Exception exception;
-
+ private final Exception exception;
+
/**
- * Construct a new instance with the specified detail string and
- * exception.
+ * Construct a new instance with the specified detail string and exception.
*/
- ConfigurationError(String msg, Exception x) {
+ ConfigurationError(final String msg, final Exception x) {
super(msg);
- this.exception = x;
+ exception = x;
}
-
+
Exception getException() {
return exception;
}
}
-
+
}
diff --git a/src/main/java/org/rometools/propono/atom/server/SecuritySupport.java b/src/main/java/org/rometools/propono/atom/server/SecuritySupport.java
index 3d603d9..824b1d1 100644
--- a/src/main/java/org/rometools/propono/atom/server/SecuritySupport.java
+++ b/src/main/java/org/rometools/propono/atom/server/SecuritySupport.java
@@ -12,60 +12,62 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.rometools.propono.atom.server;
-import java.security.*;
-import java.net.*;
-import java.io.*;
-import java.util.*;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+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 {
-
+class SecuritySupport {
+
ClassLoader getContextClassLoader() {
- return (ClassLoader)
- AccessController.doPrivileged(new PrivilegedAction() {
+ return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
+ @Override
public Object run() {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
- } catch (SecurityException ex) { }
+ } catch (final SecurityException ex) {
+ }
return cl;
}
});
}
-
+
String getSystemProperty(final String propName) {
- return (String)
- AccessController.doPrivileged(new PrivilegedAction() {
+ return (String) AccessController.doPrivileged(new PrivilegedAction() {
+ @Override
public Object run() {
return System.getProperty(propName);
}
});
}
-
- FileInputStream getFileInputStream(final File file)
- throws FileNotFoundException {
+
+ FileInputStream getFileInputStream(final File file) throws FileNotFoundException {
try {
- return (FileInputStream)
- AccessController.doPrivileged(new PrivilegedExceptionAction() {
+ return (FileInputStream) AccessController.doPrivileged(new PrivilegedExceptionAction() {
+ @Override
public Object run() throws FileNotFoundException {
return new FileInputStream(file);
}
});
- } catch (PrivilegedActionException e) {
- throw (FileNotFoundException)e.getException();
+ } catch (final PrivilegedActionException e) {
+ throw (FileNotFoundException) e.getException();
}
}
-
- InputStream getResourceAsStream(final ClassLoader cl,
- final String name) {
- return (InputStream)
- AccessController.doPrivileged(new PrivilegedAction() {
+
+ InputStream getResourceAsStream(final ClassLoader cl, final String name) {
+ return (InputStream) AccessController.doPrivileged(new PrivilegedAction() {
+ @Override
public Object run() {
InputStream ris;
if (cl == null) {
@@ -77,14 +79,14 @@ class SecuritySupport {
}
});
}
-
+
boolean doesFileExist(final File f) {
- return ((Boolean)
- AccessController.doPrivileged(new PrivilegedAction() {
+ return ((Boolean) AccessController.doPrivileged(new PrivilegedAction() {
+ @Override
public Object run() {
return new Boolean(f.exists());
}
})).booleanValue();
}
-
+
}
diff --git a/src/main/java/org/rometools/propono/atom/server/impl/FileBasedAtomHandler.java b/src/main/java/org/rometools/propono/atom/server/impl/FileBasedAtomHandler.java
index 7d8a8fe..d1c3c33 100644
--- a/src/main/java/org/rometools/propono/atom/server/impl/FileBasedAtomHandler.java
+++ b/src/main/java/org/rometools/propono/atom/server/impl/FileBasedAtomHandler.java
@@ -12,314 +12,331 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.rometools.propono.atom.server.impl;
-import org.rometools.propono.atom.server.AtomMediaResource;
-import org.apache.commons.codec.binary.Base64;
-import org.rometools.propono.atom.server.AtomHandler;
-import org.rometools.propono.atom.server.AtomException;
-import org.rometools.propono.atom.server.AtomServlet;
-import com.sun.syndication.feed.atom.Entry;
-import com.sun.syndication.feed.atom.Feed;
-import org.rometools.propono.atom.common.AtomService;
-import org.rometools.propono.atom.common.Categories;
-import org.rometools.propono.atom.server.AtomRequest;
import java.io.File;
import java.util.StringTokenizer;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import javax.servlet.http.HttpServletRequest;
-import org.apache.commons.lang.StringUtils;
+import org.rometools.propono.atom.common.AtomService;
+import org.rometools.propono.atom.common.Categories;
+import org.rometools.propono.atom.server.AtomException;
+import org.rometools.propono.atom.server.AtomHandler;
+import org.rometools.propono.atom.server.AtomMediaResource;
+import org.rometools.propono.atom.server.AtomRequest;
+import org.rometools.propono.atom.server.AtomServlet;
+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 {@link com.sun.syndication.propono.atom.server.impl.FileBasedAtomService}.
+ * 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 Log log = LogFactory.getFactory().getInstance(FileBasedAtomHandler.class);
+
private static String fileStoreDir = null;
private String userName = null;
private String atomProtocolURL = null;
- private String contextURI = null;
- private String uploadurl = null;
-
+ private String contextURI = null;
+ private final String uploadurl = null;
+
private FileBasedAtomService service = null;
-
+
/**
* Construct handler to handle one request.
+ *
* @param req Request to be handled.
*/
- public FileBasedAtomHandler( HttpServletRequest req ) {
+ public FileBasedAtomHandler(final HttpServletRequest req) {
this(req, AtomServlet.getContextDirPath());
- }
-
+ }
+
/**
* Contruct handler for one request, using specified file storage directory.
- * @param req Request to be handled.
+ *
+ * @param req Request to be handled.
* @param uploaddir File storage upload dir.
*/
- public FileBasedAtomHandler(HttpServletRequest req, String uploaddir) {
+ public FileBasedAtomHandler(final HttpServletRequest req, final String uploaddir) {
log.debug("ctor");
-
- userName = authenticateBASIC(req);
-
- atomProtocolURL = req.getScheme() + "://" + req.getServerName() + ":"
- + req.getServerPort() + req.getContextPath() + req.getServletPath();
-
- contextURI = req.getScheme() + "://" + req.getServerName() + ":"
- + req.getServerPort() + req.getContextPath();
-
+
+ userName = authenticateBASIC(req);
+
+ atomProtocolURL = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + req.getServletPath();
+
+ contextURI = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath();
+
try {
- service = new FileBasedAtomService(userName, uploaddir,
- contextURI, req.getContextPath(), req.getServletPath());
- } catch (Throwable t) {
+ service = new FileBasedAtomService(userName, uploaddir, contextURI, req.getContextPath(), req.getServletPath());
+ } catch (final Throwable t) {
throw new RuntimeException("ERROR creating FileBasedAtomService", t);
}
}
-
- /**
- * 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
+
+ /**
+ * 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
*/
- public boolean validateUser(String login, String password) {
+ public boolean validateUser(final String login, final String password) {
return true;
}
-
+
/**
* Get username of authenticated user
+ *
* @return User name.
*/
+ @Override
public String getAuthenticatedUsername() {
// For now return userName as the login id entered for authorization
return userName;
}
-
+
/**
* Get base URI of Atom protocol implementation.
+ *
* @return Base URI of Atom protocol implemenation.
*/
- public String getAtomProtocolURL( ) {
- if ( atomProtocolURL == null ) {
+ public String getAtomProtocolURL() {
+ if (atomProtocolURL == null) {
return "app";
} else {
- return atomProtocolURL;
+ return atomProtocolURL;
}
}
-
+
/**
* Return introspection document
+ *
* @throws com.sun.syndication.propono.atom.server.AtomException Unexpected exception.
* @return AtomService object with workspaces and collections.
*/
- public AtomService getAtomService(AtomRequest areq) throws AtomException {
+ @Override
+ public AtomService getAtomService(final AtomRequest areq) throws AtomException {
return service;
}
-
+
/**
* Returns null because we use in-line categories.
+ *
* @throws com.sun.syndication.propono.atom.server.AtomException Unexpected exception.
* @return Categories object
*/
- public Categories getCategories(AtomRequest areq) throws AtomException {
+ @Override
+ public Categories getCategories(final AtomRequest areq) throws AtomException {
log.debug("getCollection");
- String[] pathInfo = StringUtils.split(areq.getPathInfo(),"/");
- String handle = pathInfo[0];
- String collection = pathInfo[1];
- FileBasedCollection col = service.findCollectionByHandle(handle, collection);
- return (Categories)col.getCategories(true).get(0);
+ final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
+ final String handle = pathInfo[0];
+ final String collection = pathInfo[1];
+ final FileBasedCollection col = service.findCollectionByHandle(handle, collection);
+ return (Categories) col.getCategories(true).get(0);
}
-
+
/**
* Get collection specified by pathinfo.
+ *
* @param areq Details of HTTP request
* @return ROME feed representing collection.
* @throws com.sun.syndication.propono.atom.server.AtomException Invalid collection or other exception.
*/
- public Feed getCollection(AtomRequest areq) throws AtomException {
+ @Override
+ public Feed getCollection(final AtomRequest areq) throws AtomException {
log.debug("getCollection");
- String[] pathInfo = StringUtils.split(areq.getPathInfo(),"/");
- String handle = pathInfo[0];
- String collection = pathInfo[1];
- FileBasedCollection col = service.findCollectionByHandle(handle, collection);
- return col.getFeedDocument();
+ final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
+ final String handle = pathInfo[0];
+ final String collection = pathInfo[1];
+ final FileBasedCollection col = service.findCollectionByHandle(handle, collection);
+ return col.getFeedDocument();
}
-
+
/**
- * 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.
* @return Entry as represented on server.
*/
- public Entry postEntry(AtomRequest areq, Entry entry) throws AtomException {
+ @Override
+ public Entry postEntry(final AtomRequest areq, final Entry entry) throws AtomException {
log.debug("postEntry");
-
- String[] pathInfo = StringUtils.split(areq.getPathInfo(),"/");
- String handle = pathInfo[0];
- String collection = pathInfo[1];
- FileBasedCollection col = service.findCollectionByHandle(handle, collection);
+
+ final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
+ final String handle = pathInfo[0];
+ final String collection = pathInfo[1];
+ final FileBasedCollection col = service.findCollectionByHandle(handle, collection);
try {
- return col.addEntry(entry);
-
- } catch (Exception fe) {
+ return col.addEntry(entry);
+
+ } catch (final Exception fe) {
fe.printStackTrace();
- throw new AtomException( fe );
+ throw new AtomException(fe);
}
}
-
+
/**
* 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.
* @return ROME Entry object.
*/
- public Entry getEntry(AtomRequest areq) throws AtomException {
+ @Override
+ public Entry getEntry(final AtomRequest areq) throws AtomException {
log.debug("getEntry");
- String[] pathInfo = StringUtils.split(areq.getPathInfo(),"/");
- String handle = pathInfo[0];
- String collection = pathInfo[1];
- String fileName = pathInfo[2];
- FileBasedCollection col = service.findCollectionByHandle(handle, collection);
- try {
+ final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
+ final String handle = pathInfo[0];
+ final String collection = pathInfo[1];
+ final String fileName = pathInfo[2];
+ final FileBasedCollection col = service.findCollectionByHandle(handle, collection);
+ try {
return col.getEntry(fileName);
-
- } catch (Exception re) {
- if (re instanceof AtomException) throw (AtomException)re;
+
+ } catch (final Exception re) {
+ if (re instanceof AtomException) {
+ throw (AtomException) re;
+ }
throw new AtomException("ERROR: getting entry", re);
}
}
-
+
/**
* Update entry specified by pathInfo and posted entry.
*
- * @param entry
+ * @param entry
* @param areq Details of HTTP request
- * @throws com.sun.syndication.propono.atom.server.AtomException
+ * @throws com.sun.syndication.propono.atom.server.AtomException
*/
- public void putEntry(AtomRequest areq, Entry entry) throws AtomException {
+ @Override
+ public void putEntry(final AtomRequest areq, final Entry entry) throws AtomException {
log.debug("putEntry");
- String[] pathInfo = StringUtils.split(areq.getPathInfo(),"/");
- String handle = pathInfo[0];
- String collection = pathInfo[1];
- String fileName = pathInfo[2];
- FileBasedCollection col = service.findCollectionByHandle(handle, collection);
- try {
+ final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
+ final String handle = pathInfo[0];
+ final String collection = pathInfo[1];
+ final String fileName = pathInfo[2];
+ final FileBasedCollection col = service.findCollectionByHandle(handle, collection);
+ try {
col.updateEntry(entry, fileName);
-
- } catch ( Exception fe ) {
- throw new AtomException( fe );
+
+ } catch (final Exception fe) {
+ throw new AtomException(fe);
}
}
-
-
+
/**
* Delete entry specified by pathInfo.
+ *
* @param areq Details of HTTP request
*/
- public void deleteEntry(AtomRequest areq) throws AtomException {
+ @Override
+ public void deleteEntry(final AtomRequest areq) throws AtomException {
log.debug("deleteEntry");
- String[] pathInfo = StringUtils.split(areq.getPathInfo(),"/");
- String handle = pathInfo[0];
- String collection = pathInfo[1];
- String fileName = pathInfo[2];
- FileBasedCollection col = service.findCollectionByHandle(handle, collection);
+ final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
+ final String handle = pathInfo[0];
+ final String collection = pathInfo[1];
+ final String fileName = pathInfo[2];
+ final FileBasedCollection col = service.findCollectionByHandle(handle, collection);
try {
- col.deleteEntry(fileName);
+ col.deleteEntry(fileName);
- } catch (Exception e) {
- String msg = "ERROR in atom.deleteResource";
- log.error(msg,e);
+ } catch (final Exception e) {
+ final String msg = "ERROR in atom.deleteResource";
+ log.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
+ * @param entry New entry initialzied with only title and content type
* @return Location URL of new media entry
*/
- public Entry postMedia(AtomRequest areq, Entry entry) throws AtomException {
-
+ @Override
+ public Entry postMedia(final AtomRequest areq, final Entry entry) throws AtomException {
+
// get incoming slug from HTTP header
- String slug = areq.getHeader("Slug");
-
+ final String slug = areq.getHeader("Slug");
+
if (log.isDebugEnabled()) {
- log.debug("postMedia - title: "+entry.getTitle()+" slug:"+slug);
- }
-
+ log.debug("postMedia - title: " + entry.getTitle() + " slug:" + slug);
+ }
+
try {
- File tempFile = null;
- String[] pathInfo = StringUtils.split(areq.getPathInfo(),"/");
- String handle = pathInfo[0];
- String collection = pathInfo[1];
- FileBasedCollection col = service.findCollectionByHandle(handle, collection);
+ final File tempFile = null;
+ final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
+ final String handle = pathInfo[0];
+ final String collection = pathInfo[1];
+ final FileBasedCollection col = service.findCollectionByHandle(handle, collection);
try {
col.addMediaEntry(entry, slug, areq.getInputStream());
- } catch (Exception e) {
+ } catch (final Exception e) {
e.printStackTrace();
- String msg = "ERROR reading posted file";
- log.error(msg,e);
+ final String msg = "ERROR reading posted file";
+ log.error(msg, e);
throw new AtomException(msg, e);
} finally {
- if (tempFile != null) tempFile.delete();
+ if (tempFile != null) {
+ tempFile.delete();
+ }
}
-
- } catch (Exception re) {
+
+ } catch (final Exception re) {
throw new AtomException("ERROR: posting media");
}
return entry;
- }
-
+ }
+
/**
* 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
*/
- public void putMedia(AtomRequest areq) throws AtomException {
-
+ @Override
+ public void putMedia(final AtomRequest areq) throws AtomException {
+
log.debug("putMedia");
- String[] pathInfo = StringUtils.split(areq.getPathInfo(),"/");
- String handle = pathInfo[0];
- String collection = pathInfo[1];
- String fileName = pathInfo[3];
- FileBasedCollection col = service.findCollectionByHandle(handle, collection);
+ final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
+ final String handle = pathInfo[0];
+ final String collection = pathInfo[1];
+ final String fileName = pathInfo[3];
+ final FileBasedCollection col = service.findCollectionByHandle(handle, collection);
try {
col.updateMediaEntry(fileName, areq.getContentType(), areq.getInputStream());
-
- } catch (Exception re) {
+
+ } catch (final Exception re) {
throw new AtomException("ERROR: posting media");
}
}
-
- public AtomMediaResource getMediaResource(AtomRequest areq) throws AtomException {
+
+ @Override
+ public AtomMediaResource getMediaResource(final AtomRequest areq) throws AtomException {
log.debug("putMedia");
- String[] pathInfo = StringUtils.split(areq.getPathInfo(),"/");
- String handle = pathInfo[0];
- String collection = pathInfo[1];
- String fileName = pathInfo[3];
- FileBasedCollection col = service.findCollectionByHandle(handle, collection);
+ final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
+ final String handle = pathInfo[0];
+ final String collection = pathInfo[1];
+ final String fileName = pathInfo[3];
+ final FileBasedCollection col = service.findCollectionByHandle(handle, collection);
try {
return col.getMediaResource(fileName);
-
- } catch (Exception re) {
+
+ } catch (final Exception re) {
throw new AtomException("ERROR: posting media");
}
}
@@ -327,115 +344,122 @@ public class FileBasedAtomHandler implements AtomHandler {
/**
* Return true if specified pathinfo represents URI of service doc.
*/
- public boolean isAtomServiceURI(AtomRequest areq) {
- String[] pathInfo = StringUtils.split(areq.getPathInfo(),"/");
- if (pathInfo.length==0) return true;
+ @Override
+ public boolean isAtomServiceURI(final AtomRequest areq) {
+ final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
+ if (pathInfo.length == 0) {
+ return true;
+ }
return false;
}
-
+
/**
* Return true if specified pathinfo represents URI of category doc.
*/
- public boolean isCategoriesURI(AtomRequest areq) {
+ @Override
+ public boolean isCategoriesURI(final AtomRequest areq) {
log.debug("isCategoriesDocumentURI");
- String[] pathInfo = StringUtils.split(areq.getPathInfo(),"/");
+ final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
if (pathInfo.length == 3 && "categories".equals(pathInfo[2])) {
return true;
}
return false;
}
-
+
/**
* Return true if specified pathinfo represents URI of a collection.
*/
- public boolean isCollectionURI(AtomRequest areq) {
+ @Override
+ public boolean isCollectionURI(final AtomRequest areq) {
log.debug("isCollectionURI");
// workspace/collection-plural
// if length is 2 and points to a valid collection then YES
- String[] pathInfo = StringUtils.split(areq.getPathInfo(),"/");
+ final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
if (pathInfo.length == 2) {
- String handle = pathInfo[0];
- String collection = pathInfo[1];
+ final String handle = pathInfo[0];
+ final String collection = pathInfo[1];
if (service.findCollectionByHandle(handle, collection) != null) {
return true;
}
}
return false;
-
+
}
-
+
/**
* Return true if specified pathinfo represents URI of an Atom entry.
*/
- public boolean isEntryURI(AtomRequest areq) {
+ @Override
+ public boolean isEntryURI(final AtomRequest areq) {
log.debug("isEntryURI");
// workspace/collection-singular/fsid
// if length is 3 and points to a valid collection then YES
- String[] pathInfo = StringUtils.split(areq.getPathInfo(),"/");
+ final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
if (pathInfo.length == 3) {
- String handle = pathInfo[0];
- String collection = pathInfo[1];
+ final String handle = pathInfo[0];
+ final String collection = pathInfo[1];
if (service.findCollectionByHandle(handle, collection) != null) {
return true;
}
}
return false;
}
-
+
/**
* Return true if specified pathinfo represents media-edit URI.
*/
- public boolean isMediaEditURI(AtomRequest areq) {
+ @Override
+ public boolean isMediaEditURI(final AtomRequest areq) {
log.debug("isMediaEditURI");
// workspace/collection-singular/fsid/media/fsid
// if length is 4, points to a valid collection and fsid is mentioned twice then YES
- String[] pathInfo = StringUtils.split(areq.getPathInfo(),"/");
+ final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
if (pathInfo.length == 4) {
- String handle = pathInfo[0];
- String collection = pathInfo[1];
- String media = pathInfo[2];
- String fsid = pathInfo[3];
+ final String handle = pathInfo[0];
+ final String collection = pathInfo[1];
+ final String media = pathInfo[2];
+ final String fsid = pathInfo[3];
if (service.findCollectionByHandle(handle, collection) != null && media.equals("media")) {
return true;
}
}
return false;
-
+
}
-
+
/**
* BASIC authentication.
*/
- public String authenticateBASIC(HttpServletRequest request) {
+ public String authenticateBASIC(final HttpServletRequest request) {
log.debug("authenticateBASIC");
boolean valid = false;
String userID = null;
String password = null;
try {
- String authHeader = request.getHeader("Authorization");
+ final String authHeader = request.getHeader("Authorization");
if (authHeader != null) {
- StringTokenizer st = new StringTokenizer(authHeader);
+ final StringTokenizer st = new StringTokenizer(authHeader);
if (st.hasMoreTokens()) {
- String basic = st.nextToken();
+ final String basic = st.nextToken();
if (basic.equalsIgnoreCase("Basic")) {
- String credentials = st.nextToken();
- String userPass = new String(Base64.decodeBase64(credentials.getBytes()));
- int p = userPass.indexOf(":");
+ final String credentials = st.nextToken();
+ final String userPass = new String(Base64.decodeBase64(credentials.getBytes()));
+ final int p = userPass.indexOf(":");
if (p != -1) {
userID = userPass.substring(0, p);
- password = userPass.substring(p+1);
-
- // Validate the User.
- valid = validateUser( userID, password );
+ password = userPass.substring(p + 1);
+
+ // Validate the User.
+ valid = validateUser(userID, password);
}
}
}
}
- } catch (Exception e) {
+ } catch (final Exception e) {
log.debug(e);
}
if (valid) {
- //For now assume userID as userName
+ // For now assume userID as userName
return userID;
}
return null;
diff --git a/src/main/java/org/rometools/propono/atom/server/impl/FileBasedAtomHandlerFactory.java b/src/main/java/org/rometools/propono/atom/server/impl/FileBasedAtomHandlerFactory.java
index 12070db..f905f83 100644
--- a/src/main/java/org/rometools/propono/atom/server/impl/FileBasedAtomHandlerFactory.java
+++ b/src/main/java/org/rometools/propono/atom/server/impl/FileBasedAtomHandlerFactory.java
@@ -12,26 +12,26 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.rometools.propono.atom.server.impl;
-import org.rometools.propono.atom.server.AtomHandlerFactory;
-import org.rometools.propono.atom.server.AtomHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import org.rometools.propono.atom.server.AtomHandler;
+import org.rometools.propono.atom.server.AtomHandlerFactory;
+
/**
- * Extends {@link com.sun.syndication.propono.atom.server.AtomHandlerFactory} to create and return
+ * Extends {@link com.sun.syndication.propono.atom.server.AtomHandlerFactory} to create and return
* {@link com.sun.syndication.propono.atom.server.impl.FileBasedAtomHandler}.
*/
public class FileBasedAtomHandlerFactory extends AtomHandlerFactory {
-
+
/**
* Create new AtomHandler.
*/
- public AtomHandler newAtomHandler(
- HttpServletRequest req, HttpServletResponse res ) {
+ @Override
+ public AtomHandler newAtomHandler(final HttpServletRequest req, final HttpServletResponse res) {
return new FileBasedAtomHandler(req);
- }
+ }
}
-
diff --git a/src/main/java/org/rometools/propono/atom/server/impl/FileBasedAtomService.java b/src/main/java/org/rometools/propono/atom/server/impl/FileBasedAtomService.java
index 5f2eeec..1a2c176 100644
--- a/src/main/java/org/rometools/propono/atom/server/impl/FileBasedAtomService.java
+++ b/src/main/java/org/rometools/propono/atom/server/impl/FileBasedAtomService.java
@@ -12,32 +12,31 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.rometools.propono.atom.server.impl;
-import org.rometools.propono.atom.common.AtomService;
-import org.rometools.propono.utils.Utilities;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
+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:
+ *
*
* # 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
@@ -45,144 +44,147 @@ import java.util.TreeMap;
* propono.atomserver.filebased.collection.gifimages.accept=image/gif
* propono.atomserver.filebased.collection.gifimages.categories=general,category1,category2
*
- *
- * If no such properties are found, then service will fall back to two
- * collections: 'entries' for Atom entries and 'resources' for any content-type.
*
- *
- *
- * [servlet-context-uri]/app/[workspace-handle]/[collection-plural]
+ *
+ *
- * [servlet-context-uri]/app/[workspace-handle]/[collection-singular]/[entryid]
+ *
+ * [servlet-context-uri]/app/[workspace-handle]/[collection-plural]
*
- * [servlet-context-uri]/app/[workspace-handle]/[collection-singular]/media/[entryid]
+ *
+ * [servlet-context-uri]/app/[workspace-handle]/[collection-singular]/[entryid]
*
- * [servlet-context-uri]/app/[workspace-handle]/[collection-plural]/categories
+ *
+ * [servlet-context-uri]/app/[workspace-handle]/[collection-singular]/media/[entryid]
*
- * [servlet-context-dir]/[workspace-handle]/[collection-plural]/feed.xml
+ *
+ * [servlet-context-uri]/app/[workspace-handle]/[collection-plural]/categories
*
- * [servlet-context-dir]/[workspace-handle]/[collection-plural]/id/entry.xml
+ *
+ *
+ *
- * [servlet-context-dir]/[workspace-handle]/[collection-plural]/id/media/id
+ *
+ *
+ * [servlet-context-dir]/[workspace-handle]/[collection-plural]/feed.xml
+ *
+ * [servlet-context-dir]/[workspace-handle]/[collection-plural]/id/entry.xml
+ *
+ * [servlet-context-dir]/[workspace-handle]/[collection-plural]/id/media/id
* [collection-plural]/[entryid]/entry.xml
.
- * 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 [collection-plural]/[entryid]/media/[entryid]
. An Atom entry will be created to store
+ * metadata for the entry and it will exist at the path [collection-plural]/[entryid]/entry.xml
. 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
* @throws java.lang.Exception On Error
* @return Location URI of entry
*/
- public String addMediaEntry(Entry entry, String slug, InputStream is) throws Exception {
- synchronized (FileStore.getFileStore()) {
+ public String addMediaEntry(final Entry entry, final String slug, final InputStream is) throws Exception {
+ synchronized (FileStore.getFileStore()) {
// Save media file temp file
- Content content = (Content)entry.getContents().get(0);
+ final Content content = entry.getContents().get(0);
if (entry.getTitle() == null) {
entry.setTitle(slug);
}
- String fileName = createFileName((slug != null) ? slug : entry.getTitle(), content.getType());
- File tempFile = File.createTempFile(fileName, "tmp");
- FileOutputStream fos = new FileOutputStream(tempFile);
+ final String fileName = createFileName(slug != null ? slug : entry.getTitle(), content.getType());
+ final File tempFile = File.createTempFile(fileName, "tmp");
+ final FileOutputStream fos = new FileOutputStream(tempFile);
Utilities.copyInputToOutput(is, fos);
fos.close();
// Save media file
- FileInputStream fis = new FileInputStream(tempFile);
+ final FileInputStream fis = new FileInputStream(tempFile);
saveMediaFile(fileName, content.getType(), tempFile.length(), fis);
fis.close();
- File resourceFile = new File(getEntryMediaPath(fileName));
+ final File resourceFile = new File(getEntryMediaPath(fileName));
// Create media-link entry
- updateTimestamps(entry);
+ updateTimestamps(entry);
// Save media-link entry
- String entryPath = getEntryPath(fileName);
- OutputStream os = FileStore.getFileStore().getFileOutputStream(entryPath);
+ final String entryPath = getEntryPath(fileName);
+ final OutputStream os = FileStore.getFileStore().getFileOutputStream(entryPath);
updateMediaEntryAppLinks(entry, resourceFile.getName(), true);
Atom10Generator.serializeEntry(entry, new OutputStreamWriter(os, "UTF-8"));
os.flush();
os.close();
// Update feed with new entry
- Feed f = getFeedDocument();
+ final Feed f = getFeedDocument();
updateMediaEntryAppLinks(entry, resourceFile.getName(), false);
updateFeedDocumentWithNewEntry(f, entry);
return getEntryEditURI(fileName, false, true);
}
}
-
+
/**
* 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
@@ -285,14 +268,14 @@ public class FileBasedCollection extends Collection {
fsid = fsid.substring(0, fsid.length() - ".media-link".length());
}
- String entryPath = getEntryPath(fsid);
+ final String entryPath = getEntryPath(fsid);
checkExistence(entryPath);
- InputStream in = FileStore.getFileStore().getFileInputStream(entryPath);
+ final InputStream in = FileStore.getFileStore().getFileInputStream(entryPath);
final Entry entry;
- String filePath = getEntryMediaPath(fsid);
- File resource = new File(fsid);
+ final String filePath = getEntryMediaPath(fsid);
+ final File resource = new File(fsid);
if (resource.exists()) {
entry = loadAtomResourceEntry(in, resource);
updateMediaEntryAppLinks(entry, fsid, true);
@@ -302,26 +285,27 @@ public class FileBasedCollection extends Collection {
}
return entry;
}
-
+
/**
* Get media resource wrapping a file.
*/
- public AtomMediaResource getMediaResource(String fileName) throws Exception {
- String filePath = getEntryMediaPath(fileName);
- File resource = new File(filePath);
+ public AtomMediaResource getMediaResource(final String fileName) throws Exception {
+ final String filePath = getEntryMediaPath(fileName);
+ final File resource = new File(filePath);
return new AtomMediaResource(resource);
}
-
+
/**
* 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
*/
- public void updateEntry(Entry entry, String fsid) throws Exception {
- synchronized (FileStore.getFileStore()) {
+ public void updateEntry(final Entry entry, String fsid) throws Exception {
+ synchronized (FileStore.getFileStore()) {
- Feed f = getFeedDocument();
+ final Feed f = getFeedDocument();
if (fsid.endsWith(".media-link")) {
fsid = fsid.substring(0, fsid.length() - ".media-link".length());
@@ -332,93 +316,98 @@ public class FileBasedCollection extends Collection {
updateEntryAppLinks(entry, fsid, false);
updateFeedDocumentWithExistingEntry(f, entry);
- String entryPath = getEntryPath(fsid);
- OutputStream os = FileStore.getFileStore().getFileOutputStream(entryPath);
+ final String entryPath = getEntryPath(fsid);
+ final OutputStream os = FileStore.getFileStore().getFileOutputStream(entryPath);
updateEntryAppLinks(entry, fsid, true);
Atom10Generator.serializeEntry(entry, new OutputStreamWriter(os, "UTF-8"));
os.flush();
os.close();
}
}
-
+
/**
* 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
* @throws java.lang.Exception On error
* @return Updated Entry as it exists on server
*/
- public Entry updateMediaEntry(String fileName, String contentType, InputStream is) throws Exception {
- synchronized (FileStore.getFileStore()) {
+ public Entry updateMediaEntry(final String fileName, final String contentType, final InputStream is) throws Exception {
+ synchronized (FileStore.getFileStore()) {
- File tempFile = File.createTempFile(fileName, "tmp");
- FileOutputStream fos = new FileOutputStream(tempFile);
+ final File tempFile = File.createTempFile(fileName, "tmp");
+ final FileOutputStream fos = new FileOutputStream(tempFile);
Utilities.copyInputToOutput(is, fos);
fos.close();
// Update media file
- FileInputStream fis = new FileInputStream(tempFile);
+ final FileInputStream fis = new FileInputStream(tempFile);
saveMediaFile(fileName, contentType, tempFile.length(), fis);
fis.close();
- File resourceFile = new File(getEntryMediaPath(fileName));
+ final File resourceFile = new File(getEntryMediaPath(fileName));
// Load media-link entry to return
- String entryPath = getEntryPath(fileName);
- InputStream in = FileStore.getFileStore().getFileInputStream(entryPath);
- Entry atomEntry = loadAtomResourceEntry(in, resourceFile);
+ final String entryPath = getEntryPath(fileName);
+ final InputStream in = FileStore.getFileStore().getFileInputStream(entryPath);
+ final Entry atomEntry = loadAtomResourceEntry(in, resourceFile);
updateTimestamps(atomEntry);
updateMediaEntryAppLinks(atomEntry, fileName, false);
// Update feed with new entry
- Feed f = getFeedDocument();
+ final Feed f = getFeedDocument();
updateFeedDocumentWithExistingEntry(f, atomEntry);
// Save updated media-link entry
- OutputStream os = FileStore.getFileStore().getFileOutputStream(entryPath);
+ final OutputStream os = FileStore.getFileStore().getFileOutputStream(entryPath);
updateMediaEntryAppLinks(atomEntry, fileName, true);
Atom10Generator.serializeEntry(atomEntry, new OutputStreamWriter(os, "UTF-8"));
os.flush();
- os.close();
+ os.close();
return atomEntry;
}
}
-
+
/**
* Delete an entry and any associated media file.
+ *
* @param fsid Internal ID of entry
* @throws java.lang.Exception On error
*/
- public void deleteEntry(String fsid) throws Exception {
+ public void deleteEntry(final String fsid) throws Exception {
synchronized (FileStore.getFileStore()) {
// Remove entry from Feed
- Feed feed = getFeedDocument();
+ final Feed feed = getFeedDocument();
updateFeedDocumentRemovingEntry(feed, fsid);
- String entryFilePath = this.getEntryPath(fsid);
+ final String entryFilePath = getEntryPath(fsid);
FileStore.getFileStore().deleteFile(entryFilePath);
-
- String entryMediaPath = this.getEntryMediaPath(fsid);
+
+ final String entryMediaPath = getEntryMediaPath(fsid);
if (entryMediaPath != null) {
FileStore.getFileStore().deleteFile(entryMediaPath);
}
-
- String entryDirPath = getEntryDirPath(fsid);
- FileStore.getFileStore().deleteDirectory(entryDirPath);
-
- try {Thread.sleep(500L);}catch(Exception ignored){}
+
+ final String entryDirPath = getEntryDirPath(fsid);
+ FileStore.getFileStore().deleteDirectory(entryDirPath);
+
+ try {
+ Thread.sleep(500L);
+ } catch (final Exception ignored) {
+ }
}
}
-
- private void updateFeedDocumentWithNewEntry(Feed f, Entry e) throws AtomException {
+
+ private void updateFeedDocumentWithNewEntry(final Feed f, final Entry e) throws AtomException {
boolean inserted = false;
- for (int i=0; i
+ * 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. + *
*/ 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. * @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; - + /** * Get collection by token. + * * @param token Token from a collection's getToken() method. * @throws BlogClientException On error fetching collection. * @return Blog.Collection object. */ public Collection getCollection(String token) throws BlogClientException; - + /** * Represents an entry or resource collection on a blog server. */ public interface Collection { - + /** * 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(); - + /** * 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. */ public boolean accepts(String contentType); - + /** * 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; - + /** - * Create but do not save new entry in collection. - * To save entry, call its save() method. + * Create but do not save new entry in collection. To save entry, call its save() method. + * * @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. - * @param name Name of new resource. + * 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. + * @param bytes Data for new resource. * @throws BlogClientException On error creating entry. * @return New BlogResource object, */ public BlogResource newResource(String name, String contentType, byte[] bytes) throws BlogClientException; - + /** * 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; - + /** - * 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. @@ -143,71 +153,74 @@ 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. */ public String saveResource(BlogResource resource) throws BlogClientException; } - - + // 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; /** - * 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; - /** - * 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. - * @param name Name of resource to be saved. - * @param type MIME content type of resource data. + * 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. */ - public BlogResource newResource(String name, String type, byte[] bytes) - throws BlogClientException; + @Deprecated + public BlogResource newResource(String name, String type, byte[] bytes) throws BlogClientException; /** * 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. */ - public List getCategories() throws BlogClientException; + @Deprecated + public List getCategories() throws BlogClientException; } diff --git a/src/main/java/org/rometools/propono/blogclient/BlogClientException.java b/src/main/java/org/rometools/propono/blogclient/BlogClientException.java index d0b304a..af27e8a 100644 --- a/src/main/java/org/rometools/propono/blogclient/BlogClientException.java +++ b/src/main/java/org/rometools/propono/blogclient/BlogClientException.java @@ -12,29 +12,30 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ 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 { - - /** - * Construct a new exception + + /** + * Construct a new exception + * * @param msg Text message that explains exception */ - public BlogClientException(String msg) { + public BlogClientException(final String msg) { super(msg); } - - /** + + /** * Construct a new exception which wraps a throwable. + * * @param msg Text message that explains exception - * @param t Throwable to be wrapped by exception + * @param t Throwable to be wrapped by exception */ - public BlogClientException(String msg, Throwable t) { + public BlogClientException(final String msg, final Throwable t) { super(msg, t); } } diff --git a/src/main/java/org/rometools/propono/blogclient/BlogConnection.java b/src/main/java/org/rometools/propono/blogclient/BlogConnection.java index 817ebc6..ffb5f1f 100644 --- a/src/main/java/org/rometools/propono/blogclient/BlogConnection.java +++ b/src/main/java/org/rometools/propono/blogclient/BlogConnection.java @@ -12,23 +12,22 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ 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(); - + /** Get blog by token */ public abstract Blog getBlog(String token); - + /** Set appkey (optional, needed by some blog servers) */ public void setAppkey(String appkey); } \ No newline at end of file diff --git a/src/main/java/org/rometools/propono/blogclient/BlogConnectionFactory.java b/src/main/java/org/rometools/propono/blogclient/BlogConnectionFactory.java index 1e8e5b7..af11b23 100644 --- a/src/main/java/org/rometools/propono/blogclient/BlogConnectionFactory.java +++ b/src/main/java/org/rometools/propono/blogclient/BlogConnectionFactory.java @@ -12,7 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.rometools.propono.blogclient; import java.lang.reflect.Constructor; @@ -20,61 +20,53 @@ import java.lang.reflect.Constructor; /** * Entry point to the Blogapps blog client library. */ -public class BlogConnectionFactory { - +public class BlogConnectionFactory { + // BlogConnection implementations must: // 1) implement BlogConnection // 2) privide contructor that accepts three strings args: url, username and password. - + // TODO: make implementations configurable - private static String ATOMPROTOCOL_IMPL_CLASS = - "com.sun.syndication.propono.blogclient.atomprotocol.AtomConnection"; - - private static String METAWEBLOG_IMPL_CLASS = - "com.sun.syndication.propono.blogclient.metaweblog.MetaWeblogConnection"; - - /** - * 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 - * @param password Password for login to blog server - */ - public static BlogConnection getBlogConnection( - String type, String url, String username, String password) - throws BlogClientException { - BlogConnection blogConnection = null; - if (type == null || type.equals("metaweblog")) { - blogConnection = createBlogConnection( - METAWEBLOG_IMPL_CLASS, url, username, password); - } else if (type.equals("atom")) { - blogConnection = createBlogConnection( - ATOMPROTOCOL_IMPL_CLASS, url, username, password); - } else { - throw new BlogClientException("Type must be 'atom' or 'metaweblog'"); - } - return blogConnection; - } - - private static BlogConnection createBlogConnection( - String className, String url, String username, String password) - throws BlogClientException { - Class conClass; - try { - conClass = Class.forName(className); - } catch (ClassNotFoundException ex) { - throw new BlogClientException( - "BlogConnection impl. class not found: "+className, ex); - } - 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}); - } catch (Throwable t) { - throw new BlogClientException( - "ERROR instantiating BlogConnection impl.", t); - } - } + private static String ATOMPROTOCOL_IMPL_CLASS = "com.sun.syndication.propono.blogclient.atomprotocol.AtomConnection"; + + private static String METAWEBLOG_IMPL_CLASS = "com.sun.syndication.propono.blogclient.metaweblog.MetaWeblogConnection"; + + /** + * 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 + * @param password Password for login to blog server + */ + public static BlogConnection getBlogConnection(final String type, final String url, final String username, final String password) + throws BlogClientException { + BlogConnection blogConnection = null; + if (type == null || type.equals("metaweblog")) { + blogConnection = createBlogConnection(METAWEBLOG_IMPL_CLASS, url, username, password); + } else if (type.equals("atom")) { + blogConnection = createBlogConnection(ATOMPROTOCOL_IMPL_CLASS, url, username, password); + } else { + throw new BlogClientException("Type must be 'atom' or 'metaweblog'"); + } + return blogConnection; + } + + private static BlogConnection createBlogConnection(final String className, final String url, final String username, final String password) + throws BlogClientException { + 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; + try { + ctor = conClass.getConstructor(args); + return (BlogConnection) ctor.newInstance(new Object[] { url, username, password }); + } catch (final Throwable t) { + throw new BlogClientException("ERROR instantiating BlogConnection impl.", t); + } + } } diff --git a/src/main/java/org/rometools/propono/blogclient/BlogEntry.java b/src/main/java/org/rometools/propono/blogclient/BlogEntry.java index 7bf2c1d..facd101 100644 --- a/src/main/java/org/rometools/propono/blogclient/BlogEntry.java +++ b/src/main/java/org/rometools/propono/blogclient/BlogEntry.java @@ -12,39 +12,37 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.rometools.propono.blogclient; import java.util.Date; import java.util.List; -import java.io.InputStream; - -/** + +/** * Represents a single blog entry. */ public interface BlogEntry { - + /** Get token, which can be used to fetch the blog entry */ 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; - + /** Delete this entry from blog server */ public void delete() throws BlogClientException; /** Permanent link to this entry (assigned by server) */ - public String getPermalink(); - + public String getPermalink(); + /** Blog is associated with a blog */ public Blog getBlog(); - + /** Get categories, a list of BlogEntry.Category objects */ public List getCategories(); - + /** Set categories, a list of BlogEntry.Category objects */ public void setCategories(List categories); @@ -56,84 +54,89 @@ public interface BlogEntry { /** Set title of this blog entry */ public void setTitle(String title); - + /** Get summary of this blog entry */ public String getSummary(); - + /** Set summary of this blog entry */ public void setSummary(String summary); - + /** Get content of this blog entry */ public Content getContent(); /** Set content of this blog entry */ public void setContent(Content content); - + /** Get draft status of this entry */ public boolean getDraft(); /** Set draft status of this entry */ public void setDraft(boolean draft); - + /** Get author of this entry */ public Person getAuthor(); - + /** Set author of this entry */ public void setAuthor(Person author); - + /** Set publish date of this entry */ public Date getPublicationDate(); - + /** Get publish date of this entry */ - public void setPublicationDate(Date date); - + public void setPublicationDate(Date date); + /** Get update date of this entry */ public Date getModificationDate(); - + /** Set update date of this entry */ public void setModificationDate(Date date); - + /** Represents blog entry content */ public class Content { String type = "html"; String value = null; String src = null; - + /** Construct content */ - public Content() {} - + public Content() { + } + /** Construct content with value (and type="html") */ - public Content(String value) { + public Content(final String value) { this.value = value; } + /** Get value of content if in-line */ public String getValue() { return value; } + /** Set value of content if in-line */ - public void setValue(String value) { + public void setValue(final String value) { this.value = value; } + /** - * 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(String type) { + public void setType(final String type) { this.type = type; } + /** Get URI of content if out-of-line */ public String getSrc() { return src; } + /** Set URI of content if out-of-line */ - public void setSrc(String src) { + public void setSrc(final String src) { this.src = src; } } @@ -143,89 +146,113 @@ public interface BlogEntry { String name; String email; String url; + /** Get person's email */ public String getEmail() { return email; } - /** Set person's email */ - public void setEmail(String email) { + + /** Set person's email */ + public void setEmail(final String email) { this.email = email; } + /** Get person's name */ public String getName() { return name; } + /** Set person's name */ - public void setName(String name) { + public void setName(final String name) { this.name = name; } + /** Get person's URL */ public String getUrl() { return url; } + /** Set person's URL */ - public void setUrl(String url) { + public void setUrl(final String url) { this.url = url; } + /** Returns person's name */ + @Override public String toString() { return name; } } - + /** Represents a weblog category */ public class Category { String id; String name; String url; + /** * Create new Catetory */ - public Category() {} + public Category() { + } + /** * Create new category with name. */ - public Category(String id) { + public Category(final String id) { this.id = id; - this.name = id; + name = id; } + /** * Determines if categories are equal based on id. */ - public boolean equals(Object obj) { - Category other = (Category)obj; - if (obj == null) return false; - if (getId() != null && other.getId() != null - && getId().equals(other.getId())) return true; + @Override + public boolean equals(final Object obj) { + final Category other = (Category) obj; + if (obj == null) { + return false; + } + if (getId() != null && other.getId() != null && getId().equals(other.getId())) { + return true; + } return false; } + /** Get category id */ public String getId() { return id; } + /** Set category id */ - public void setId(String id) { + public void setId(final String id) { this.id = id; } + /** Get category display name */ public String getName() { return name; } + /** Set category display name */ - public void setName(String name) { + public void setName(final String name) { this.name = name; } + /** Get URL of category domain */ public String getUrl() { return url; } + /** Set URL of category domain */ - public void setUrl(String url) { + public void setUrl(final String url) { this.url = url; } + /** Return category's name or id for display */ + @Override public String toString() { - return name!=null ? name : id; + return name != null ? name : id; } - } + } } diff --git a/src/main/java/org/rometools/propono/blogclient/BlogResource.java b/src/main/java/org/rometools/propono/blogclient/BlogResource.java index 80a5478..5dc6893 100644 --- a/src/main/java/org/rometools/propono/blogclient/BlogResource.java +++ b/src/main/java/org/rometools/propono/blogclient/BlogResource.java @@ -12,28 +12,25 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.rometools.propono.blogclient; import java.io.InputStream; -/** - * Represents a file that has been uploaded to a blog. +/** + * Represents a file that has been uploaded to a blog. * - * Resources are modeled as a type of BlogEntry, but be aware: not all servers - * can save resource metadata (i.e. title, category, author, etc.). MetaWeblog - * based servers can't save metadata at all and Atom protocol servers are not - * required to preserve uploaded file metadata. + * Resources are modeled as a type of BlogEntry, but be aware: not all servers can save resource metadata (i.e. title, category, author, etc.). MetaWeblog based + * servers can't save metadata at all and Atom protocol servers are not required to preserve uploaded file metadata. */ public interface BlogResource extends BlogEntry { /** Get resource name (name is required) */ public String getName(); - + /** Get resource as stream, using content.src as URL */ public InputStream getAsStream() throws BlogClientException; - + /** Update resource by immediately uploading new bytes to server */ public void update(byte[] newBytes) throws BlogClientException; } - diff --git a/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomBlog.java b/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomBlog.java index 3565775..07899de 100644 --- a/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomBlog.java +++ b/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomBlog.java @@ -12,170 +12,195 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.rometools.propono.blogclient.atomprotocol; -import org.rometools.propono.utils.ProponoException; import java.util.ArrayList; import java.util.Iterator; 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.blogclient.Blog; -import org.rometools.propono.blogclient.BlogClientException; -import org.rometools.propono.blogclient.BlogEntry; -import org.rometools.propono.blogclient.BlogResource; import org.rometools.propono.atom.client.ClientAtomService; import org.rometools.propono.atom.client.ClientCollection; import org.rometools.propono.atom.client.ClientEntry; import org.rometools.propono.atom.client.ClientMediaEntry; import org.rometools.propono.atom.client.ClientWorkspace; -import java.util.Map; -import java.util.TreeMap; +import org.rometools.propono.blogclient.Blog; +import org.rometools.propono.blogclient.BlogClientException; +import org.rometools.propono.blogclient.BlogEntry; +import org.rometools.propono.blogclient.BlogResource; +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 HttpClient httpClient = null; - private String name = null; + 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 Map collections = new TreeMap(); - + private ClientWorkspace workspace = null; + private AtomCollection entriesCollection = null; + private AtomCollection resourcesCollection = null; + private final Map collections = new TreeMap(); + /** - * 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(ClientAtomService service, ClientWorkspace workspace) { - this.setService(service); - this.setWorkspace(workspace); - this.name = workspace.getTitle(); - Iterator members = workspace.getCollections().iterator(); - + AtomBlog(final ClientAtomService service, final ClientWorkspace workspace) { + setService(service); + setWorkspace(workspace); + name = workspace.getTitle(); + final Iterator members = workspace.getCollections().iterator(); + while (members.hasNext()) { - ClientCollection col = (ClientCollection) members.next(); + final ClientCollection col = (ClientCollection) members.next(); if (col.accepts("entry") && entriesCollection == null) { - // first entry collection is primary entry collection + // first entry collection is primary entry collection entriesCollection = new AtomCollection(this, col); - } - else if (!col.accepts("entry") && resourcesCollection == null) { + } else if (!col.accepts("entry") && resourcesCollection == null) { // first non-entry collection is primary resource collection resourcesCollection = new AtomCollection(this, col); - } + } collections.put(col.getHrefResolved(), new AtomCollection(this, col)); - } - } - + } + } + /** - * {@inheritDoc} + * {@inheritDoc} */ - public String getName() { return name; } + @Override + public String getName() { + return name; + } /** * String display of blog, returns name. */ - public String toString() { return getName(); } - - /** - * {@inheritDoc} - */ - public String getToken() { return entriesCollection.getToken(); } + @Override + public String toString() { + return getName(); + } - /** - * {@inheritDoc} - */ - public BlogEntry newEntry() throws BlogClientException { - if (entriesCollection == null) throw new BlogClientException("No entry collection"); - return entriesCollection.newEntry(); - } - /** * {@inheritDoc} */ - public BlogEntry getEntry(String token) throws BlogClientException { + @Override + public String getToken() { + return entriesCollection.getToken(); + } + + /** + * {@inheritDoc} + */ + @Override + public BlogEntry newEntry() throws BlogClientException { + if (entriesCollection == null) { + throw new BlogClientException("No entry collection"); + } + return entriesCollection.newEntry(); + } + + /** + * {@inheritDoc} + */ + @Override + public BlogEntry getEntry(final String token) throws BlogClientException { ClientEntry clientEntry = null; - AtomEntry atomEntry = null; + final AtomEntry atomEntry = null; try { - clientEntry = getService().getEntry(token); - } catch (ProponoException ex) { + clientEntry = getService().getEntry(token); + } catch (final ProponoException ex) { throw new BlogClientException("ERROR: fetching entry", ex); } if (clientEntry != null && clientEntry instanceof ClientMediaEntry) { - return new AtomResource(this, (ClientMediaEntry)clientEntry); + return new AtomResource(this, (ClientMediaEntry) clientEntry); } else if (clientEntry != null && clientEntry instanceof ClientEntry) { return new AtomEntry(this, clientEntry); } else { throw new BlogClientException("ERROR: unknown object type returned"); } } - + /** - * {@inheritDoc} + * {@inheritDoc} */ + @Override public Iterator getEntries() throws BlogClientException { - if (entriesCollection == null) throw new BlogClientException("No primary entry collection"); + if (entriesCollection == null) { + throw new BlogClientException("No primary entry collection"); + } return new AtomEntryIterator(entriesCollection); - } - - /** - * {@inheritDoc} - */ - public Iterator getResources() throws BlogClientException { - if (resourcesCollection == null) throw new BlogClientException("No primary entry collection"); - return new AtomEntryIterator(resourcesCollection); - } - - String saveEntry(BlogEntry entry) throws BlogClientException { - if (entriesCollection == null) throw new BlogClientException("No primary entry collection"); - return entriesCollection.saveEntry(entry); - } - - void deleteEntry(BlogEntry entry) throws BlogClientException { - if (entriesCollection == null) throw new BlogClientException("No primary entry collection"); - entriesCollection.deleteEntry(entry); } /** * {@inheritDoc} */ - public List getCategories() throws BlogClientException { - if (entriesCollection == null) throw new BlogClientException("No primary entry collection"); - return entriesCollection.getCategories(); + @Override + public Iterator getResources() throws BlogClientException { + if (resourcesCollection == null) { + throw new BlogClientException("No primary entry collection"); + } + return new AtomEntryIterator(resourcesCollection); } - + + String saveEntry(final BlogEntry entry) throws BlogClientException { + if (entriesCollection == null) { + throw new BlogClientException("No primary entry collection"); + } + return entriesCollection.saveEntry(entry); + } + + void deleteEntry(final BlogEntry entry) throws BlogClientException { + if (entriesCollection == null) { + throw new BlogClientException("No primary entry collection"); + } + entriesCollection.deleteEntry(entry); + } + /** * {@inheritDoc} */ - public BlogResource newResource( - String name, String contentType, byte[] bytes) throws BlogClientException { - if (resourcesCollection == null) { + @Override + public List getCategories() throws BlogClientException { + if (entriesCollection == null) { + throw new BlogClientException("No primary entry collection"); + } + return entriesCollection.getCategories(); + } + + /** + * {@inheritDoc} + */ + @Override + public BlogResource newResource(final String name, final String contentType, final byte[] bytes) throws BlogClientException { + if (resourcesCollection == null) { throw new BlogClientException("No resource collection"); } return resourcesCollection.newResource(name, contentType, bytes); } - - String saveResource(BlogResource res) throws BlogClientException { - if (resourcesCollection == null) throw new BlogClientException("No primary resource collection"); + String saveResource(final BlogResource res) throws BlogClientException { + if (resourcesCollection == null) { + throw new BlogClientException("No primary resource collection"); + } return resourcesCollection.saveResource(res); } - - void deleteResource(BlogResource resource) throws BlogClientException { - deleteEntry((BlogEntry)resource); - } - + + void deleteResource(final BlogResource resource) throws BlogClientException { + deleteEntry(resource); + } + /** * {@inheritDoc} */ + @Override public List getCollections() throws BlogClientException { return new ArrayList(collections.values()); } @@ -183,15 +208,16 @@ public class AtomBlog implements Blog { /** * {@inheritDoc} */ - public Blog.Collection getCollection(String token) throws BlogClientException { - return (Blog.Collection)collections.get(token); - } - + @Override + public Blog.Collection getCollection(final String token) throws BlogClientException { + return (Blog.Collection) collections.get(token); + } + ClientAtomService getService() { return service; } - void setService(ClientAtomService service) { + void setService(final ClientAtomService service) { this.service = service; } @@ -199,7 +225,7 @@ public class AtomBlog implements Blog { return workspace; } - void setWorkspace(ClientWorkspace workspace) { + void setWorkspace(final ClientWorkspace workspace) { this.workspace = workspace; } diff --git a/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomCollection.java b/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomCollection.java index 3758bc5..3c16f78 100644 --- a/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomCollection.java +++ b/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomCollection.java @@ -12,44 +12,45 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.rometools.propono.blogclient.atomprotocol; -import com.sun.syndication.feed.atom.Category; -import org.rometools.propono.atom.client.ClientAtomService; -import org.rometools.propono.atom.common.Categories; -import org.rometools.propono.atom.client.ClientCollection; -import org.rometools.propono.atom.client.ClientEntry; import java.util.ArrayList; import java.util.Iterator; -import java.util.List; +import java.util.List; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.rometools.propono.atom.client.ClientAtomService; +import org.rometools.propono.atom.client.ClientCollection; +import org.rometools.propono.atom.client.ClientEntry; +import org.rometools.propono.atom.common.Categories; import org.rometools.propono.blogclient.Blog; import org.rometools.propono.blogclient.BlogClientException; import org.rometools.propono.blogclient.BlogEntry; import org.rometools.propono.blogclient.BlogResource; +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 ClientCollection clientCollection = null; - - AtomCollection(AtomBlog blog, ClientCollection col) { - this.blog = blog; - this.clientCollection = col; - for (Iterator catsIter = col.getCategories().iterator(); catsIter.hasNext();) { - Categories cats = (Categories)catsIter.next(); - for (Iterator catIter = cats.getCategories().iterator(); catIter.hasNext();) { - Category cat = (Category)catIter.next(); - BlogEntry.Category blogCat = new BlogEntry.Category(cat.getTerm()); + 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(); + final BlogEntry.Category blogCat = new BlogEntry.Category(cat.getTerm()); blogCat.setName(cat.getLabel()); blogCat.setUrl(cat.getScheme()); getCategories().add(blogCat); @@ -60,6 +61,7 @@ public class AtomCollection implements Blog.Collection { /** * {@inheritDoc} */ + @Override public String getTitle() { return getClientCollection().getTitle(); } @@ -67,6 +69,7 @@ public class AtomCollection implements Blog.Collection { /** * {@inheritDoc} */ + @Override public String getToken() { return getClientCollection().getHrefResolved(); } @@ -74,6 +77,7 @@ public class AtomCollection implements Blog.Collection { /** * {@inheritDoc} */ + @Override public List getAccepts() { return getClientCollection().getAccepts(); } @@ -81,38 +85,43 @@ public class AtomCollection implements Blog.Collection { /** * {@inheritDoc} */ - public boolean accepts(String ct) { + @Override + public boolean accepts(final String ct) { return getClientCollection().accepts(ct); } /** * {@inheritDoc} */ + @Override public Iterator getEntries() throws BlogClientException { - return new AtomEntryIterator(this); + return new AtomEntryIterator(this); } - + /** * {@inheritDoc} */ + @Override public BlogEntry newEntry() throws BlogClientException { - AtomBlog atomBlog = (AtomBlog)getBlog(); - BlogEntry entry = new AtomEntry(atomBlog, this); - return entry; + final AtomBlog atomBlog = (AtomBlog) getBlog(); + final BlogEntry entry = new AtomEntry(atomBlog, this); + return entry; } - + /** * {@inheritDoc} */ - public BlogResource newResource(String name, String contentType, byte[] bytes) throws BlogClientException { + @Override + public BlogResource newResource(final String name, final String contentType, final byte[] bytes) throws BlogClientException { return new AtomResource(this, name, contentType, bytes); } /** * {@inheritDoc} */ - public String saveResource(BlogResource res) throws BlogClientException { - ((AtomResource)res).setCollection(this); + @Override + public String saveResource(final BlogResource res) throws BlogClientException { + ((AtomResource) res).setCollection(this); res.save(); return res.getContent().getSrc(); } @@ -120,42 +129,45 @@ public class AtomCollection implements Blog.Collection { /** * {@inheritDoc} */ - public String saveEntry(BlogEntry entry) throws BlogClientException { - ((AtomEntry)entry).setCollection(this); + @Override + public String saveEntry(final BlogEntry entry) throws BlogClientException { + ((AtomEntry) entry).setCollection(this); entry.save(); return entry.getPermalink(); } - void deleteEntry(BlogEntry entry) throws BlogClientException { - try { - ClientAtomService service = ((AtomBlog)getBlog()).getService(); - ClientEntry clientEntry = service.getEntry(entry.getToken()); + void deleteEntry(final BlogEntry entry) throws BlogClientException { + try { + final ClientAtomService service = ((AtomBlog) getBlog()).getService(); + final ClientEntry clientEntry = service.getEntry(entry.getToken()); clientEntry.remove(); - } catch (Exception e) { + } catch (final Exception e) { throw new BlogClientException("ERROR deleting entry", e); } } - + /** * {@inheritDoc} */ + @Override public Blog getBlog() { return blog; } - void setBlog(AtomBlog blog) { + void setBlog(final AtomBlog blog) { this.blog = blog; } /** * {@inheritDoc} */ + @Override public List getCategories() { return categories; } - void setCategories(List categories) { + void setCategories(final List categories) { this.categories = categories; } diff --git a/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomConnection.java b/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomConnection.java index 37deabc..83dc917 100644 --- a/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomConnection.java +++ b/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomConnection.java @@ -12,81 +12,80 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.rometools.propono.blogclient.atomprotocol; +import java.util.ArrayList; +import java.util.HashMap; +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 java.util.List; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -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.blogclient.BlogConnection; 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 HttpClient httpClient = null; - private Map blogs = new HashMap(); - + private final HttpClient httpClient = null; + private final Map blogs = new HashMap(); + /** * 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 uri End-point URL of Atom service + * @param username Username of account * @param password Password of account */ - public AtomConnection(String uri, String username, String password) - throws BlogClientException { - - Document doc = null; + public AtomConnection(final String uri, final String username, final String password) throws BlogClientException { + + final Document doc = null; try { - ClientAtomService service = (ClientAtomService) - AtomClientFactory.getAtomService(uri, new BasicAuthStrategy(username, password)); - Iterator iter = service.getWorkspaces().iterator(); - int count = 0; + final ClientAtomService service = AtomClientFactory.getAtomService(uri, new BasicAuthStrategy(username, password)); + final Iterator iter = service.getWorkspaces().iterator(); + final int count = 0; while (iter.hasNext()) { - ClientWorkspace workspace = (ClientWorkspace)iter.next(); - Blog blog = new AtomBlog(service, workspace); + final ClientWorkspace workspace = (ClientWorkspace) iter.next(); + final Blog blog = new AtomBlog(service, workspace); blogs.put(blog.getToken(), blog); - } - } catch (Throwable t) { + } + } catch (final Throwable t) { throw new BlogClientException("Error connecting to blog server", t); } } - - /** - * {@inheritDoc} - */ - public List getBlogs() { - return new ArrayList(blogs.values()); - } - - /** - * {@inheritDoc} - */ - public Blog getBlog(String token) { - return (AtomBlog)blogs.get(token); - } /** * {@inheritDoc} */ - public void setAppkey(String appkey) { + @Override + public List getBlogs() { + return new ArrayList(blogs.values()); + } + + /** + * {@inheritDoc} + */ + @Override + public Blog getBlog(final String token) { + return (AtomBlog) blogs.get(token); + } + + /** + * {@inheritDoc} + */ + @Override + public void setAppkey(final String appkey) { } } diff --git a/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomEntry.java b/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomEntry.java index 29242a5..5618336 100644 --- a/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomEntry.java +++ b/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomEntry.java @@ -12,154 +12,158 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.rometools.propono.blogclient.atomprotocol; -import org.rometools.propono.utils.ProponoException; -import org.rometools.propono.atom.common.rome.AppModule; -import org.rometools.propono.atom.common.rome.AppModuleImpl; -import org.rometools.propono.blogclient.BlogClientException; -import org.rometools.propono.blogclient.BlogEntry; -import org.rometools.propono.blogclient.BaseBlogEntry; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; -import com.sun.syndication.feed.atom.Entry; -import com.sun.syndication.feed.atom.Link; -import org.rometools.propono.atom.client.ClientEntry; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.rometools.propono.blogclient.BlogEntry.Person; +import org.rometools.propono.atom.client.ClientEntry; +import org.rometools.propono.atom.common.rome.AppModule; +import org.rometools.propono.atom.common.rome.AppModuleImpl; +import org.rometools.propono.blogclient.BaseBlogEntry; +import org.rometools.propono.blogclient.BlogClientException; +import org.rometools.propono.blogclient.BlogEntry; +import org.rometools.propono.utils.ProponoException; + +import com.sun.syndication.feed.atom.Entry; +import com.sun.syndication.feed.atom.Link; /** * Atom protocol implementation of BlogEntry. */ public class AtomEntry extends BaseBlogEntry implements BlogEntry { static final Log logger = LogFactory.getLog(AtomCollection.class); - + String editURI = null; AtomCollection collection = null; - - AtomEntry(AtomBlog blog, AtomCollection collection) throws BlogClientException { + + AtomEntry(final AtomBlog blog, final AtomCollection collection) throws BlogClientException { super(blog); this.collection = collection; } - - AtomEntry(AtomCollection collection, ClientEntry entry) throws BlogClientException { - this((AtomBlog)collection.getBlog(), collection); - //clientEntry = entry; + + AtomEntry(final AtomCollection collection, final ClientEntry entry) throws BlogClientException { + this((AtomBlog) collection.getBlog(), collection); + // clientEntry = entry; copyFromRomeEntry(entry); } - - AtomEntry(AtomBlog blog, ClientEntry entry) throws BlogClientException { + + AtomEntry(final AtomBlog blog, final ClientEntry entry) throws BlogClientException { super(blog); - //clientEntry = entry; + // clientEntry = entry; copyFromRomeEntry(entry); } - + /** * {@inheritDoc} */ + @Override public String getToken() { return editURI; } - + AtomCollection getCollection() { return collection; } - void setCollection(AtomCollection collection) { + void setCollection(final AtomCollection collection) { this.collection = collection; } /** * True if entry's token's are equal. */ - public boolean equals(Object o) { + @Override + public boolean equals(final Object o) { if (o instanceof AtomEntry) { - AtomEntry other = (AtomEntry)o; + final AtomEntry other = (AtomEntry) o; if (other.getToken() != null && getToken() != null) { return other.getToken().equals(getToken()); } } return false; } - + /** * {@inheritDoc} */ + @Override public void save() throws BlogClientException { - boolean create = (getToken() == null); + final boolean create = getToken() == null; if (create && getCollection() == null) { throw new BlogClientException("Cannot save entry, no collection"); } else if (create) { try { - ClientEntry clientEntry = collection.getClientCollection().createEntry(); + final ClientEntry clientEntry = collection.getClientCollection().createEntry(); copyToRomeEntry(clientEntry); collection.getClientCollection().addEntry(clientEntry); copyFromRomeEntry(clientEntry); - } catch (ProponoException ex) { - throw new BlogClientException("Error saving entry", ex); + } catch (final ProponoException ex) { + throw new BlogClientException("Error saving entry", ex); } } else { try { - ClientEntry clientEntry = ((AtomBlog)getBlog()).getService().getEntry(getToken()); + final ClientEntry clientEntry = ((AtomBlog) getBlog()).getService().getEntry(getToken()); copyToRomeEntry(clientEntry); clientEntry.update(); copyFromRomeEntry(clientEntry); - } catch (ProponoException ex) { - throw new BlogClientException("Error updating entry", ex); + } catch (final ProponoException ex) { + throw new BlogClientException("Error updating entry", ex); } - } + } } - + /** * {@inheritDoc} */ + @Override public void delete() throws BlogClientException { if (getToken() == null) { throw new BlogClientException("Cannot delete unsaved entry"); } try { - ClientEntry clientEntry = ((AtomBlog)getBlog()).getService().getEntry(editURI); + final ClientEntry clientEntry = ((AtomBlog) getBlog()).getService().getEntry(editURI); clientEntry.remove(); - } catch (ProponoException ex) { - throw new BlogClientException("Error removing entry", ex); + } catch (final ProponoException ex) { + throw new BlogClientException("Error removing entry", ex); } } - - void copyFromRomeEntry(ClientEntry entry) { + + void copyFromRomeEntry(final ClientEntry entry) { id = entry.getId(); - title = entry.getTitle(); + title = entry.getTitle(); editURI = entry.getEditURI(); - List altlinks = entry.getAlternateLinks(); + final List altlinks = entry.getAlternateLinks(); if (altlinks != null) { - for (Iterator iter = altlinks.iterator(); iter.hasNext();) { - Link link = (Link)iter.next(); - if ("alternate".equals(link.getRel()) || link.getRel()==null) { + for (final Iterator iter = altlinks.iterator(); iter.hasNext();) { + final Link link = (Link) iter.next(); + if ("alternate".equals(link.getRel()) || link.getRel() == null) { permalink = link.getHrefResolved(); break; } } } - List contents = entry.getContents(); + final List 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 = (com.sun.syndication.feed.atom.Content) contents.get(0); } if (romeContent != null) { content = new BlogEntry.Content(romeContent.getValue()); content.setType(romeContent.getType()); content.setSrc(romeContent.getSrc()); - } + } if (entry.getCategories() != null) { - List cats = new ArrayList(); - List romeCats = entry.getCategories(); - for (Iterator iter=romeCats.iterator(); iter.hasNext();) { - com.sun.syndication.feed.atom.Category romeCat = - (com.sun.syndication.feed.atom.Category)iter.next(); - BlogEntry.Category cat = new BlogEntry.Category(); + 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 BlogEntry.Category cat = new BlogEntry.Category(); cat.setId(romeCat.getTerm()); cat.setUrl(romeCat.getScheme()); cat.setName(romeCat.getLabel()); @@ -167,57 +171,54 @@ public class AtomEntry extends BaseBlogEntry implements BlogEntry { } categories = cats; } - List authors = entry.getAuthors(); - if (authors!=null && authors.size() > 0) { - com.sun.syndication.feed.atom.Person romeAuthor = - (com.sun.syndication.feed.atom.Person)authors.get(0); + final List 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) { author = new Person(); author.setName(romeAuthor.getName()); author.setEmail(romeAuthor.getEmail()); author.setUrl(romeAuthor.getUrl()); - } - } + } + } publicationDate = entry.getPublished(); modificationDate = entry.getModified(); - - AppModule control = (AppModule)entry.getModule(AppModule.URI); - if (control != null && control.getDraft() != null) { - draft = control.getDraft().booleanValue(); + + final AppModule control = (AppModule) entry.getModule(AppModule.URI); + if (control != null && control.getDraft() != null) { + draft = control.getDraft().booleanValue(); } else { draft = false; } } - Entry copyToRomeEntry(ClientEntry entry) { + + Entry copyToRomeEntry(final ClientEntry entry) { if (id != null) { entry.setId(id); } - entry.setTitle(title); + entry.setTitle(title); if (author != null) { - com.sun.syndication.feed.atom.Person person = - new com.sun.syndication.feed.atom.Person(); + final com.sun.syndication.feed.atom.Person person = new com.sun.syndication.feed.atom.Person(); person.setName(author.getName()); person.setEmail(author.getEmail()); person.setUrl(author.getUrl()); - List authors = new ArrayList(); + final List authors = new ArrayList(); authors.add(person); entry.setAuthors(authors); } if (content != null) { - com.sun.syndication.feed.atom.Content romeContent = - new com.sun.syndication.feed.atom.Content(); + final com.sun.syndication.feed.atom.Content romeContent = new com.sun.syndication.feed.atom.Content(); romeContent.setValue(content.getValue()); romeContent.setType(content.getType()); - List contents = new ArrayList(); + final List contents = new ArrayList(); contents.add(romeContent); entry.setContents(contents); } if (categories != null) { - List romeCats = new ArrayList(); - for (Iterator iter=categories.iterator(); iter.hasNext();) { - BlogEntry.Category cat = (BlogEntry.Category)iter.next(); - com.sun.syndication.feed.atom.Category romeCategory = - new com.sun.syndication.feed.atom.Category(); + final List romeCats = new ArrayList(); + for (final Iterator iter = categories.iterator(); iter.hasNext();) { + final BlogEntry.Category cat = (BlogEntry.Category) 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()); romeCategory.setLabel(cat.getName()); @@ -225,15 +226,15 @@ public class AtomEntry extends BaseBlogEntry implements BlogEntry { } entry.setCategories(romeCats); } - entry.setPublished((publicationDate == null) ? new Date() : publicationDate); - entry.setModified((modificationDate == null) ? new Date() : modificationDate); - - List modules = new ArrayList(); - AppModule control = new AppModuleImpl(); + entry.setPublished(publicationDate == null ? new Date() : publicationDate); + entry.setModified(modificationDate == null ? new Date() : modificationDate); + + final List modules = new ArrayList(); + final AppModule control = new AppModuleImpl(); control.setDraft(new Boolean(draft)); modules.add(control); entry.setModules(modules); - + return entry; } diff --git a/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomEntryIterator.java b/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomEntryIterator.java index 20c30aa..9829cf7 100644 --- a/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomEntryIterator.java +++ b/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomEntryIterator.java @@ -12,14 +12,15 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.rometools.propono.blogclient.atomprotocol; -import org.rometools.propono.atom.client.ClientEntry; -import org.rometools.propono.atom.client.ClientMediaEntry; import java.util.Iterator; + import org.apache.commons.logging.Log; 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; /** @@ -29,43 +30,46 @@ public class AtomEntryIterator implements Iterator { static final Log logger = LogFactory.getLog(AtomEntryIterator.class); private Iterator iterator = null; private AtomCollection collection = null; - - AtomEntryIterator(AtomCollection collection) throws BlogClientException { + + AtomEntryIterator(final AtomCollection collection) throws BlogClientException { try { this.collection = collection; iterator = collection.getClientCollection().getEntries(); - } catch (Exception e) { + } catch (final Exception e) { throw new BlogClientException("ERROR fetching collection", e); } } - + /** * True if more entries are available. */ + @Override public boolean hasNext() { return iterator.hasNext(); } - + /** * Get next entry. */ + @Override public Object next() { try { - ClientEntry entry = (ClientEntry)iterator.next(); + final ClientEntry entry = (ClientEntry) iterator.next(); if (entry instanceof ClientMediaEntry) { - return new AtomResource(collection, (ClientMediaEntry)entry); + return new AtomResource(collection, (ClientMediaEntry) entry); } else { return new AtomEntry(collection, entry); } - } catch (Exception e) { + } catch (final Exception e) { logger.error("ERROR fetching entry", e); } return null; } - + /** * Remove is not supported. */ + @Override public void remove() { // optional method, not implemented } diff --git a/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomResource.java b/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomResource.java index e20cee8..3a5380e 100644 --- a/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomResource.java +++ b/src/main/java/org/rometools/propono/blogclient/atomprotocol/AtomResource.java @@ -12,21 +12,22 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.rometools.propono.blogclient.atomprotocol; import java.io.InputStream; +import java.util.Iterator; +import java.util.List; -import org.rometools.propono.blogclient.BlogClientException; -import org.rometools.propono.blogclient.BlogEntry; -import org.rometools.propono.blogclient.BlogResource; -import com.sun.syndication.feed.atom.Link; import org.rometools.propono.atom.client.ClientAtomService; import org.rometools.propono.atom.client.ClientCollection; import org.rometools.propono.atom.client.ClientEntry; import org.rometools.propono.atom.client.ClientMediaEntry; -import java.util.Iterator; -import java.util.List; +import org.rometools.propono.blogclient.BlogClientException; +import org.rometools.propono.blogclient.BlogEntry; +import org.rometools.propono.blogclient.BlogResource; + +import com.sun.syndication.feed.atom.Link; /** * Atom protocol implementation of BlogResource. @@ -35,100 +36,100 @@ public class AtomResource extends AtomEntry implements BlogResource { private AtomCollection collection; private byte[] bytes; - AtomResource(AtomCollection collection, String name, String contentType, byte[] bytes) - throws BlogClientException { - super((AtomBlog)collection.getBlog(), collection); + AtomResource(final AtomCollection collection, final String name, final String contentType, final byte[] bytes) throws BlogClientException { + super((AtomBlog) collection.getBlog(), collection); this.collection = collection; this.bytes = bytes; - BlogEntry.Content rcontent = new BlogEntry.Content(); + final BlogEntry.Content rcontent = new BlogEntry.Content(); rcontent.setType(contentType); setContent(rcontent); - } - - AtomResource(AtomCollection collection, ClientMediaEntry entry) - throws BlogClientException { + } + + AtomResource(final AtomCollection collection, final ClientMediaEntry entry) throws BlogClientException { super(collection, entry); - } - - AtomResource(AtomBlog blog, ClientMediaEntry entry) throws BlogClientException { + } + + AtomResource(final AtomBlog blog, final ClientMediaEntry entry) throws BlogClientException { super(blog, entry); } /** * {@inheritDoc} */ + @Override public String getName() { return getTitle(); } - + byte[] getBytes() { return bytes; } - + /** * {@inheritDoc} */ + @Override public InputStream getAsStream() throws BlogClientException { try { - return null; //((ClientMediaEntry)clientEntry).getAsStream(); - } catch (Exception e) { + return null; // ((ClientMediaEntry)clientEntry).getAsStream(); + } catch (final Exception e) { throw new BlogClientException("Error creating entry", e); } } - + /** * {@inheritDoc} */ + @Override public void save() throws BlogClientException { try { if (getToken() == null) { - ClientAtomService clientService = ((AtomBlog)getBlog()).getService(); - ClientCollection clientCollection = collection.getClientCollection(); - - ClientMediaEntry clientEntry = - new ClientMediaEntry(clientService, clientCollection, getTitle(), - "", getContent().getType(), getBytes()); - + final ClientAtomService clientService = ((AtomBlog) getBlog()).getService(); + final ClientCollection clientCollection = collection.getClientCollection(); + + final ClientMediaEntry clientEntry = new ClientMediaEntry(clientService, clientCollection, getTitle(), "", getContent().getType(), getBytes()); + copyToRomeEntry(clientEntry); - collection.getClientCollection().addEntry(clientEntry); - this.editURI = clientEntry.getEditURI(); - + collection.getClientCollection().addEntry(clientEntry); + editURI = clientEntry.getEditURI(); + } else { - ClientAtomService clientService = ((AtomBlog)getBlog()).getService(); - ClientMediaEntry clientEntry = (ClientMediaEntry)clientService.getEntry(editURI); - clientEntry.update(); + final ClientAtomService clientService = ((AtomBlog) getBlog()).getService(); + final ClientMediaEntry clientEntry = (ClientMediaEntry) clientService.getEntry(editURI); + clientEntry.update(); } - } catch (Exception e) { + } catch (final Exception e) { throw new BlogClientException("Error creating entry", e); } } - + /** * {@inheritDoc} */ - public void update(byte[] newBytes) throws BlogClientException { + @Override + public void update(final byte[] newBytes) throws BlogClientException { try { - //((ClientMediaEntry)clientEntry).setBytes(newBytes); - //clientEntry.update(); - } catch (Exception e) { + // ((ClientMediaEntry)clientEntry).setBytes(newBytes); + // clientEntry.update(); + } catch (final Exception e) { throw new BlogClientException("Error creating entry", e); } } - - void copyFromRomeEntry(ClientEntry entry) { + + @Override + void copyFromRomeEntry(final ClientEntry entry) { super.copyFromRomeEntry(entry); - - List links = entry.getOtherLinks(); + + final List links = entry.getOtherLinks(); if (links != null) { - for (Iterator iter = links.iterator(); iter.hasNext();) { - Link link = (Link)iter.next(); + for (final Iterator iter = links.iterator(); iter.hasNext();) { + final Link link = (Link) iter.next(); if ("edit-media".equals(link.getRel())) { id = link.getHrefResolved(); break; } } } - - + } } diff --git a/src/main/java/org/rometools/propono/blogclient/metaweblog/MetaWeblogBlog.java b/src/main/java/org/rometools/propono/blogclient/metaweblog/MetaWeblogBlog.java index 5c70d40..08b88b2 100644 --- a/src/main/java/org/rometools/propono/blogclient/metaweblog/MetaWeblogBlog.java +++ b/src/main/java/org/rometools/propono/blogclient/metaweblog/MetaWeblogBlog.java @@ -12,81 +12,87 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ + */ package org.rometools.propono.blogclient.metaweblog; import java.net.URL; import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Iterator; -import org.rometools.propono.blogclient.BlogEntry; -import org.rometools.propono.blogclient.Blog; -import org.rometools.propono.blogclient.BlogClientException; -import org.rometools.propono.blogclient.BlogResource; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; import java.util.Map; import java.util.TreeMap; + import org.apache.xmlrpc.client.XmlRpcClient; 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.BlogResource; /** * Blog implementation that uses a mix of Blogger and MetaWeblog API methods. */ public class MetaWeblogBlog implements Blog { - private String blogid; - private String name; - private URL url; - private String userName; - private String password; + 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 Map collections; - + private final Map collections; + private XmlRpcClient xmlRpcClient = null; /** * {@inheritDoc} */ - public String getName() { return name; } - + @Override + public String getName() { + return name; + } + /** * {@inheritDoc} */ - public String getToken() { return blogid; } - + @Override + public String getToken() { + return blogid; + } + /** * String representation of blog, returns the name. */ - public String toString() { return getName(); } - - private XmlRpcClient getXmlRpcClient() { - + @Override + public String toString() { + return getName(); + } + + private XmlRpcClient getXmlRpcClient() { + if (xmlRpcClient == null) { - XmlRpcClientConfigImpl xmlrpcConfig = new XmlRpcClientConfigImpl(); + final XmlRpcClientConfigImpl xmlrpcConfig = new XmlRpcClientConfigImpl(); xmlrpcConfig.setServerURL(url); xmlRpcClient = new XmlRpcClient(); xmlRpcClient.setConfig(xmlrpcConfig); } - return xmlRpcClient; + return xmlRpcClient; } - - MetaWeblogBlog(String blogid, String name, - URL url, String userName, String password) { + + MetaWeblogBlog(final String blogid, final String name, final URL url, final String userName, final String password) { this.blogid = blogid; this.name = name; this.url = url; this.userName = userName; this.password = password; - this.collections = new TreeMap(); - collections.put("entries", - new MetaWeblogBlogCollection(this, "entries", "Entries", "entry")); - collections.put("resources", - new MetaWeblogBlogCollection(this, "resources", "Resources", "*")); + collections = new TreeMap(); + collections.put("entries", new MetaWeblogBlogCollection(this, "entries", "Entries", "entry")); + collections.put("resources", new MetaWeblogBlogCollection(this, "resources", "Resources", "*")); } - MetaWeblogBlog(String blogId, String name, - URL url, String userName, String password, String appkey) { + MetaWeblogBlog(final String blogId, final String name, final URL url, final String userName, final String password, final String appkey) { this(blogId, name, url, userName, password); this.appkey = appkey; } @@ -94,33 +100,33 @@ public class MetaWeblogBlog implements Blog { /** * {@inheritDoc} */ + @Override public BlogEntry newEntry() { return new MetaWeblogEntry(this, new HashMap()); } - String saveEntry(BlogEntry entry) throws BlogClientException { - Blog.Collection col = (Blog.Collection)collections.get("entries"); + String saveEntry(final BlogEntry entry) throws BlogClientException { + final Blog.Collection col = (Blog.Collection) collections.get("entries"); return col.saveEntry(entry); } /** * {@inheritDoc} */ - public BlogEntry getEntry(String id) throws BlogClientException { + @Override + public BlogEntry getEntry(final String id) throws BlogClientException { try { - Map result = (Map) - getXmlRpcClient().execute("metaWeblog.getPost", new Object[] {id, userName, password}); + final Map result = (Map) getXmlRpcClient().execute("metaWeblog.getPost", new Object[] { id, userName, password }); return new MetaWeblogEntry(this, result); - } catch (Exception e) { + } catch (final Exception e) { throw new BlogClientException("ERROR: XML-RPC error getting entry", e); } } - void deleteEntry(String id) throws BlogClientException { + void deleteEntry(final String id) throws BlogClientException { try { - getXmlRpcClient().execute("blogger.deletePost", - new Object[] {appkey, id, userName, password, Boolean.FALSE}); - } catch (Exception e) { + getXmlRpcClient().execute("blogger.deletePost", new Object[] { appkey, id, userName, password, Boolean.FALSE }); + } catch (final Exception e) { throw new BlogClientException("ERROR: XML-RPC error getting entry", e); } } @@ -128,6 +134,7 @@ public class MetaWeblogBlog implements Blog { /** * {@inheritDoc} */ + @Override public Iterator getEntries() throws BlogClientException { return new EntryIterator(); } @@ -135,78 +142,80 @@ public class MetaWeblogBlog implements Blog { /** * {@inheritDoc} */ - public BlogResource newResource(String name, String contentType, byte[] bytes) throws BlogClientException { + @Override + public BlogResource newResource(final String name, final String contentType, final byte[] bytes) throws BlogClientException { return new MetaWeblogResource(this, name, contentType, bytes); } - - String saveResource(MetaWeblogResource resource) throws BlogClientException { - Blog.Collection col = (Blog.Collection)collections.get("resources"); + + String saveResource(final MetaWeblogResource resource) throws BlogClientException { + final Blog.Collection col = (Blog.Collection) collections.get("resources"); return col.saveResource(resource); } - - BlogResource getResource(String token) throws BlogClientException { + + BlogResource getResource(final String token) throws BlogClientException { return null; } - + /** * {@inheritDoc} */ + @Override public Iterator getResources() throws BlogClientException { return new NoOpIterator(); } - - void deleteResource(BlogResource resource) throws BlogClientException { + + void deleteResource(final BlogResource resource) throws BlogClientException { // no-op } - + /** * {@inheritDoc} */ + @Override public List getCategories() throws BlogClientException { - - ArrayList ret = new ArrayList(); + + final ArrayList ret = new ArrayList(); try { - Object result = - getXmlRpcClient().execute ("metaWeblog.getCategories", - new Object[] {blogid, userName, password}); + final Object result = getXmlRpcClient().execute("metaWeblog.getCategories", new Object[] { blogid, userName, password }); if (result != null && result instanceof HashMap) { // Standard MetaWeblog API style: struct of struts - Map catsmap = (Map)result; - Iterator keys = catsmap.keySet().iterator(); + final Map catsmap = (Map) result; + final Iterator keys = catsmap.keySet().iterator(); while (keys.hasNext()) { - String key = (String)keys.next(); - Map catmap = (Map)catsmap.get(key); - BlogEntry.Category category = new BlogEntry.Category(key); - category.setName((String)catmap.get("description")); - // catmap.get("htmlUrl"); + final String key = (String) keys.next(); + final Map catmap = (Map) catsmap.get(key); + final BlogEntry.Category category = new BlogEntry.Category(key); + category.setName((String) catmap.get("description")); + // catmap.get("htmlUrl"); // catmap.get("rssUrl"); ret.add(category); - } + } } else if (result != null && result instanceof Object[]) { // Wordpress style: array of structs - Object[] resultArray = (Object[])result; - for (int i=0; iAtomClientTest
to start Jetty server, run tests and then stop
- * the Jetty server.
+ * Test Propono Atom Client against Atom Server via Jetty. Extends AtomClientTest
to start Jetty server, run tests and then stop the Jetty server.
*/
public class AtomClientServerTest { // extends AtomClientTest {
@@ -40,8 +39,8 @@ public class AtomClientServerTest { // extends AtomClientTest {
public static final String USERNAME = "admin";
public static final String PASSWORD = "admin";
- public AtomClientServerTest(String s) {
- //super(s);
+ public AtomClientServerTest(final String s) {
+ // super(s);
}
public String getEndpoint() {
@@ -57,7 +56,7 @@ public class AtomClientServerTest { // extends AtomClientTest {
}
public static Test suite() {
- TestSuite suite = new TestSuite(AtomClientServerTest.class);
+ final TestSuite suite = new TestSuite(AtomClientServerTest.class);
return suite;
}
@@ -66,14 +65,14 @@ public class AtomClientServerTest { // extends AtomClientTest {
}
protected void setUp() throws Exception {
- ConsoleHandler handler = new ConsoleHandler();
- Logger logger = Logger.getLogger("com.sun.syndication.propono");
+ final ConsoleHandler handler = new ConsoleHandler();
+ final Logger logger = Logger.getLogger("com.sun.syndication.propono");
logger.setLevel(Level.FINEST);
logger.addHandler(handler);
setupServer();
- HttpContext context = createContext();
- ServletHandler servlets = createServletHandler();
+ final HttpContext context = createContext();
+ final ServletHandler servlets = createServletHandler();
context.addHandler(servlets);
server.addContext(context);
server.start();
@@ -88,24 +87,20 @@ public class AtomClientServerTest { // extends AtomClientTest {
server = new HttpServer();
// Create a port listener
- SocketListener listener = new SocketListener();
+ final SocketListener listener = new SocketListener();
listener.setPort(TESTPORT);
server.addListener(listener);
}
private ServletHandler createServletHandler() {
- System.setProperty(
- "com.sun.syndication.propono.atom.server.AtomHandlerFactory",
- "com.sun.syndication.propono.atom.server.TestAtomHandlerFactory");
- ServletHandler servlets = new ServletHandler();
- servlets.addServlet(
- "app", "/app/*",
- "com.sun.syndication.propono.atom.server.AtomServlet");
+ System.setProperty("com.sun.syndication.propono.atom.server.AtomHandlerFactory", "com.sun.syndication.propono.atom.server.TestAtomHandlerFactory");
+ final ServletHandler servlets = new ServletHandler();
+ servlets.addServlet("app", "/app/*", "com.sun.syndication.propono.atom.server.AtomServlet");
return servlets;
}
private HttpContext createContext() {
- HttpContext context = new HttpContext();
+ final HttpContext context = new HttpContext();
context.setContextPath("/rome/*");
return context;
}
@@ -118,5 +113,3 @@ public class AtomClientServerTest { // extends AtomClientTest {
}
}
}
-
-
diff --git a/src/test/java/org/rometools/propono/atom/server/TestAtomHandlerFactory.java b/src/test/java/org/rometools/propono/atom/server/TestAtomHandlerFactory.java
index d4d5c52..97e58ec 100644
--- a/src/test/java/org/rometools/propono/atom/server/TestAtomHandlerFactory.java
+++ b/src/test/java/org/rometools/propono/atom/server/TestAtomHandlerFactory.java
@@ -16,14 +16,13 @@
*/
package org.rometools.propono.atom.server;
-import org.rometools.propono.atom.server.AtomHandlerFactory;
-import org.rometools.propono.atom.server.AtomHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestAtomHandlerFactory extends AtomHandlerFactory {
-
- public AtomHandler newAtomHandler(HttpServletRequest req, HttpServletResponse res) {
+
+ @Override
+ public AtomHandler newAtomHandler(final HttpServletRequest req, final HttpServletResponse res) {
return new TestAtomHandlerImpl(req, "build/testuploaddir");
}
}
diff --git a/src/test/java/org/rometools/propono/atom/server/TestAtomHandlerImpl.java b/src/test/java/org/rometools/propono/atom/server/TestAtomHandlerImpl.java
index 83b047d..b047a16 100644
--- a/src/test/java/org/rometools/propono/atom/server/TestAtomHandlerImpl.java
+++ b/src/test/java/org/rometools/propono/atom/server/TestAtomHandlerImpl.java
@@ -16,16 +16,18 @@
*/
package org.rometools.propono.atom.server;
-import org.rometools.propono.atom.server.impl.FileBasedAtomHandler;
import javax.servlet.http.HttpServletRequest;
+import org.rometools.propono.atom.server.impl.FileBasedAtomHandler;
+
public class TestAtomHandlerImpl extends FileBasedAtomHandler {
-
- public TestAtomHandlerImpl(HttpServletRequest req, String uploaddir) {
+
+ public TestAtomHandlerImpl(final HttpServletRequest req, final String uploaddir) {
super(req, uploaddir);
}
- public boolean validateUser( String loginId, String password ) {
- return AtomClientServerTest.USERNAME.equals(loginId)
- && AtomClientServerTest.PASSWORD.equals(password);
- }
+
+ @Override
+ public boolean validateUser(final String loginId, final String password) {
+ return AtomClientServerTest.USERNAME.equals(loginId) && AtomClientServerTest.PASSWORD.equals(password);
+ }
}
\ No newline at end of file
diff --git a/src/test/java/org/rometools/propono/blogclient/SimpleBlogClientTest.java b/src/test/java/org/rometools/propono/blogclient/SimpleBlogClientTest.java
index bdb1d34..e66972d 100644
--- a/src/test/java/org/rometools/propono/blogclient/SimpleBlogClientTest.java
+++ b/src/test/java/org/rometools/propono/blogclient/SimpleBlogClientTest.java
@@ -12,114 +12,109 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- */
+ */
package org.rometools.propono.blogclient;
-import org.rometools.propono.blogclient.BlogConnection;
-import org.rometools.propono.blogclient.BlogResource;
-import org.rometools.propono.blogclient.Blog;
-import org.rometools.propono.blogclient.BlogConnectionFactory;
-import org.rometools.propono.blogclient.BlogEntry;
-import com.sun.syndication.io.impl.Atom10Parser;
-import org.rometools.propono.utils.Utilities;
import java.io.File;
import java.util.Iterator;
+
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
+import org.rometools.propono.utils.Utilities;
+import com.sun.syndication.io.impl.Atom10Parser;
/**
- * 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.
*/
public class SimpleBlogClientTest extends TestCase {
-
- private String metaweblogEndpoint = "http://localhost:8080/roller/roller-services/xmlrpc";
- //private String atomEndpoint = "http://localhost:8080/roller/roller-services/app";
- private String atomEndpoint = "http://localhost:8080/sample-atomserver/app";
-
- private String endpoint = "http://localhost:8080/atom-fileserver/app";
- private String username = "admin";
- private String password = "admin";
-
- public SimpleBlogClientTest(String testName) {
+
+ private final String metaweblogEndpoint = "http://localhost:8080/roller/roller-services/xmlrpc";
+ // 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 username = "admin";
+ private final String password = "admin";
+
+ public SimpleBlogClientTest(final String testName) {
super(testName);
}
+ @Override
protected void setUp() throws Exception {
}
+ @Override
protected void tearDown() throws Exception {
}
-
+
public void testBlogClientAtom() throws Exception {
testBlogClient("atom", atomEndpoint);
}
-
- public void testBlogClientMetaWeblog() throws Exception{
+
+ public void testBlogClientMetaWeblog() throws Exception {
testBlogClient("metaweblog", metaweblogEndpoint);
}
-
- public void testBlogClient(String type, String endpoint) throws Exception {
- BlogConnection conn = BlogConnectionFactory
- .getBlogConnection(type, endpoint, username, password);
-
+
+ public void testBlogClient(final String type, final String endpoint) throws Exception {
+ final BlogConnection conn = BlogConnectionFactory.getBlogConnection(type, endpoint, username, password);
+
int blogCount = 0;
- for (Iterator it = conn.getBlogs().iterator(); it.hasNext();) {
- Blog blog = (Blog) it.next();
+ for (final Iterator it = conn.getBlogs().iterator(); it.hasNext();) {
+ final Blog blog = (Blog) it.next();
System.out.println(blog.getName());
blogCount++;
}
- assertTrue(blogCount > 0);
+ assertTrue(blogCount > 0);
}
public void testPostAndDeleteAtom() throws Exception {
testPostAndDelete("atom", atomEndpoint);
}
-
+
public void testPostAndDeleteMetaWeblog() throws Exception {
testPostAndDelete("metaweblog", metaweblogEndpoint);
}
-
+
public void testMediaPostAtom() throws Exception {
testMediaPost("atom", atomEndpoint);
}
-
+
public void testMediaPostMetaWeblog() throws Exception {
testMediaPost("metaweblog", metaweblogEndpoint);
}
-
- public void testPostAndDelete(String type, String endpoint) throws Exception {
- BlogConnection conn = BlogConnectionFactory
- .getBlogConnection(type, endpoint, username, password);
+
+ public void testPostAndDelete(final String type, final String endpoint) throws Exception {
+ final BlogConnection conn = BlogConnectionFactory.getBlogConnection(type, endpoint, username, password);
assertNotNull(conn);
-
- String title1 = "Test content";
- String content1 = "Test content";
-
- Blog blog = (Blog)conn.getBlogs().get(0);
+
+ final String title1 = "Test content";
+ final String content1 = "Test content";
+
+ final Blog blog = (Blog) conn.getBlogs().get(0);
BlogEntry entry = blog.newEntry();
entry.setTitle(title1);
entry.setContent(new BlogEntry.Content(content1));
entry.save();
- String token = entry.getToken();
+ final String token = entry.getToken();
assertNotNull(token);
-
+
entry = blog.getEntry(token);
-
+
assertEquals(title1, entry.getTitle());
assertEquals(content1, entry.getContent().getValue());
-
+
assertNotNull(entry);
entry.delete();
entry = null;
-
+
boolean notFound = false;
try {
entry = blog.getEntry(token);
- } catch (Exception e) {
+ } catch (final Exception e) {
notFound = true;
}
assertTrue(notFound);
@@ -128,30 +123,29 @@ public class SimpleBlogClientTest extends TestCase {
/**
* Post media entry to every media colletion avialable on server, then cleanup.
*/
- public void testMediaPost(String type, String endpoint) throws Exception {
- BlogConnection conn = BlogConnectionFactory
- .getBlogConnection(type, endpoint, username, password);
+ public void testMediaPost(final String type, final String endpoint) throws Exception {
+ final BlogConnection conn = BlogConnectionFactory.getBlogConnection(type, endpoint, username, password);
assertNotNull(conn);
-
- assertTrue(conn.getBlogs().size() > 0);
+
+ assertTrue(conn.getBlogs().size() > 0);
int count = 0;
- for (Iterator it = conn.getBlogs().iterator(); it.hasNext();) {
- Blog blog = (Blog) it.next();
+ for (final Iterator it = conn.getBlogs().iterator(); it.hasNext();) {
+ final Blog blog = (Blog) it.next();
assertNotNull(blog.getName());
-
- for (Iterator colit = blog.getCollections().iterator(); colit.hasNext();) {
- Blog.Collection col = (Blog.Collection) colit.next();
+
+ for (final Iterator colit = blog.getCollections().iterator(); colit.hasNext();) {
+ final Blog.Collection col = (Blog.Collection) colit.next();
if (col.accepts("image/gif")) {
-
+
// we found a collection that accepts GIF, so post one
- BlogResource m1 = col.newResource("duke"+count, "image/gif",
- Utilities.getBytesFromFile(new File("test/testdata/duke-wave-shadow.gif")));
+ final BlogResource m1 = col.newResource("duke" + count, "image/gif",
+ Utilities.getBytesFromFile(new File("test/testdata/duke-wave-shadow.gif")));
col.saveResource(m1);
-
+
if ("atom".equals(type)) { // additional tests for Atom
// entry should now exist on server
- BlogResource m2 = (BlogResource)blog.getEntry(m1.getToken());
+ final BlogResource m2 = (BlogResource) blog.getEntry(m1.getToken());
assertNotNull(m2);
// remove entry
@@ -160,8 +154,8 @@ public class SimpleBlogClientTest extends TestCase {
// fetching entry now should result in exception
boolean failed = false;
try {
- blog.getEntry(m1.getToken());
- } catch (Exception e) {
+ blog.getEntry(m1.getToken());
+ } catch (final Exception e) {
failed = true;
}
assertTrue(failed);
@@ -169,52 +163,46 @@ public class SimpleBlogClientTest extends TestCase {
count++;
}
}
- }
+ }
assertTrue(count > 0);
}
-
public void testEntryIterationAtom() throws Exception {
testEntryIteration("atom", atomEndpoint);
}
-
+
public void testEntryIterationMetaWeblog() throws Exception {
testEntryIteration("metaweblog", metaweblogEndpoint);
}
- public void testEntryIteration(String type, String endpoint) throws Exception {
- BlogConnection conn = BlogConnectionFactory
- .getBlogConnection(type, endpoint, username, password);
+ public void testEntryIteration(final String type, final String endpoint) throws Exception {
+ final BlogConnection conn = BlogConnectionFactory.getBlogConnection(type, endpoint, username, password);
assertNotNull(conn);
-
- String title1 = "Test content";
- String content1 = "Test content";
-
- Blog blog = (Blog)conn.getBlogs().get(0);
-
- for (int i=0; i<10; i++) {
- BlogEntry entry = blog.newEntry();
+
+ final String title1 = "Test content";
+ final String content1 = "Test content";
+
+ final Blog blog = (Blog) conn.getBlogs().get(0);
+
+ for (int i = 0; i < 10; i++) {
+ final BlogEntry entry = blog.newEntry();
entry.setTitle(title1);
entry.setContent(new BlogEntry.Content(content1));
entry.save();
- String token = entry.getToken();
+ final String token = entry.getToken();
assertTrue(Atom10Parser.isAbsoluteURI(token));
assertNotNull(token);
}
- for (Iterator it = blog.getEntries(); it.hasNext();) {
- BlogEntry blogEntry = (BlogEntry)it.next();
+ for (final Iterator it = blog.getEntries(); it.hasNext();) {
+ final BlogEntry blogEntry = (BlogEntry) it.next();
assertTrue(Atom10Parser.isAbsoluteURI(blogEntry.getToken()));
blogEntry.delete();
- }
+ }
}
-
-
+
public static Test suite() {
- TestSuite suite = new TestSuite(SimpleBlogClientTest.class);
+ final TestSuite suite = new TestSuite(SimpleBlogClientTest.class);
return suite;
}
}
-
-
-