KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > roller > webservices > xmlrpc > MetaWeblogAPIHandler


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. The ASF licenses this file to You
4  * under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License. For additional information regarding
15  * copyright in this work, please see the NOTICE file in the top level
16  * directory of this distribution.
17  */

18
19 package org.apache.roller.webservices.xmlrpc;
20
21 import java.io.ByteArrayInputStream JavaDoc;
22 import java.sql.Timestamp JavaDoc;
23 import java.util.Date JavaDoc;
24 import java.util.Hashtable JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.List JavaDoc;
27 import java.util.Vector JavaDoc;
28
29 import javax.servlet.http.HttpServletRequest JavaDoc;
30
31 import org.apache.commons.lang.StringUtils;
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34 import org.apache.roller.RollerException;
35 import org.apache.roller.config.RollerRuntimeConfig;
36 import org.apache.roller.model.FileManager;
37 import org.apache.roller.model.Roller;
38 import org.apache.roller.model.RollerFactory;
39 import org.apache.roller.model.WeblogManager;
40 import org.apache.roller.pojos.UserData;
41 import org.apache.roller.pojos.WeblogCategoryData;
42 import org.apache.roller.pojos.WeblogEntryData;
43 import org.apache.roller.pojos.WebsiteData;
44 import org.apache.roller.ui.core.RollerContext;
45 import org.apache.roller.util.RollerMessages;
46 import org.apache.roller.util.URLUtilities;
47 import org.apache.roller.util.Utilities;
48 import org.apache.struts.util.RequestUtils;
49 import org.apache.xmlrpc.XmlRpcException;
50
51 /**
52  * Roller XML-RPC Handler for the MetaWeblog API.
53  *
54  * MetaWeblog API spec can be found at http://www.xmlrpc.com/metaWeblogApi
55  *
56  * @author David M Johnson
57  */

58 public class MetaWeblogAPIHandler extends BloggerAPIHandler {
59     
60     static final long serialVersionUID = -1364456614935668629L;
61     
62     private static Log mLogger = LogFactory.getLog(MetaWeblogAPIHandler.class);
63     
64     public MetaWeblogAPIHandler() {
65         super();
66     }
67     
68     
69     /**
70      * Authenticates a user and returns the categories available in the website
71      *
72      * @param blogid Dummy Value for Roller
73      * @param userid Login for a MetaWeblog user who has permission to post to the blog
74      * @param password Password for said username
75      * @throws Exception
76      * @return
77      */

78     public Object JavaDoc getCategories(String JavaDoc blogid, String JavaDoc userid, String JavaDoc password)
79     throws Exception JavaDoc {
80         
81         mLogger.debug("getCategories() Called =====[ SUPPORTED ]=====");
82         mLogger.debug(" BlogId: " + blogid);
83         mLogger.debug(" UserId: " + userid);
84         
85         WebsiteData website = validate(blogid, userid,password);
86         Roller roller = RollerFactory.getRoller();
87         try {
88             Hashtable JavaDoc result = new Hashtable JavaDoc();
89             WeblogManager weblogMgr = roller.getWeblogManager();
90             List JavaDoc cats = weblogMgr.getWeblogCategories(website, false);
91             for (Iterator JavaDoc wbcItr = cats.iterator(); wbcItr.hasNext();) {
92                 WeblogCategoryData category = (WeblogCategoryData) wbcItr.next();
93                 result.put(category.getPath(),
94                         createCategoryStruct(category, userid));
95             }
96             return result;
97         } catch (Exception JavaDoc e) {
98             String JavaDoc msg = "ERROR in MetaWeblogAPIHandler.getCategories";
99             mLogger.error(msg,e);
100             throw new XmlRpcException(UNKNOWN_EXCEPTION, msg);
101         }
102     }
103     
104     
105     /**
106      * Edits a given post. Optionally, will publish the blog after making the edit
107      *
108      * @param postid Unique identifier of the post to be changed
109      * @param userid Login for a MetaWeblog user who has permission to post to the blog
110      * @param password Password for said username
111      * @param struct Contents of the post
112      * @param publish If true, the blog will be published immediately after the post is made
113      * @throws org.apache.xmlrpc.XmlRpcException
114      * @return
115      */

116     public boolean editPost(String JavaDoc postid, String JavaDoc userid, String JavaDoc password,
117             Hashtable JavaDoc struct, int publish) throws Exception JavaDoc {
118         
119         return editPost(postid, userid, password, struct, publish > 0);
120     }
121     
122     
123     public boolean editPost(String JavaDoc postid, String JavaDoc userid, String JavaDoc password,
124             Hashtable JavaDoc struct, boolean publish) throws Exception JavaDoc {
125         
126         mLogger.debug("editPost() Called ========[ SUPPORTED ]=====");
127         mLogger.debug(" PostId: " + postid);
128         mLogger.debug(" UserId: " + userid);
129         mLogger.debug(" Publish: " + publish);
130         
131         Roller roller = RollerFactory.getRoller();
132         WeblogManager weblogMgr = roller.getWeblogManager();
133         WeblogEntryData entry = weblogMgr.getWeblogEntry(postid);
134         
135         validate(entry.getWebsite().getHandle(), userid,password);
136         
137         Hashtable JavaDoc postcontent = struct;
138         String JavaDoc description = (String JavaDoc)postcontent.get("description");
139         String JavaDoc title = (String JavaDoc)postcontent.get("title");
140         if (title == null) title = "";
141         
142         Date JavaDoc dateCreated = (Date JavaDoc)postcontent.get("dateCreated");
143         if (dateCreated == null) dateCreated = (Date JavaDoc)postcontent.get("pubDate");
144         
145         String JavaDoc cat = null;
146         if ( postcontent.get("categories") != null ) {
147             Vector JavaDoc cats = (Vector JavaDoc)postcontent.get("categories");
148             cat = (String JavaDoc)cats.elementAt(0);
149         }
150         mLogger.debug(" Title: " + title);
151         mLogger.debug(" Category: " + cat);
152         
153         try {
154             
155             Timestamp JavaDoc current =
156                     new Timestamp JavaDoc(System.currentTimeMillis());
157             
158             if ( !title.equals("") ) entry.setTitle(title);
159             entry.setText(description);
160             entry.setUpdateTime(current);
161             if (Boolean.valueOf(publish).booleanValue()) {
162                 entry.setStatus(WeblogEntryData.PUBLISHED);
163             } else {
164                 entry.setStatus(WeblogEntryData.DRAFT);
165             }
166             if (dateCreated != null) {
167                 entry.setPubTime(new Timestamp JavaDoc(dateCreated.getTime()));
168             }
169             
170             if ( cat != null ) {
171                 // Use first category specified by request
172
WeblogCategoryData cd =
173                         weblogMgr.getWeblogCategoryByPath(entry.getWebsite(), cat);
174                 entry.setCategory(cd);
175             }
176             
177             // save the entry
178
weblogMgr.saveWeblogEntry(entry);
179             roller.flush();
180             
181             // notify cache
182
flushPageCache(entry.getWebsite());
183             
184             // TODO: Roller timestamps need better than 1 second accuracy
185
// Until then, we can't allow more than one post per second
186
Thread.sleep(1000);
187             
188             return true;
189         } catch (Exception JavaDoc e) {
190             String JavaDoc msg = "ERROR in MetaWeblogAPIHandler.editPost";
191             mLogger.error(msg,e);
192             throw new XmlRpcException(UNKNOWN_EXCEPTION, msg);
193         }
194     }
195     
196     
197     /**
198      * Makes a new post to a designated blog. Optionally, will publish the blog after making the post
199      *
200      * @param blogid Unique identifier of the blog the post will be added to
201      * @param userid Login for a MetaWeblog user who has permission to post to the blog
202      * @param password Password for said username
203      * @param struct Contents of the post
204      * @param publish If true, the blog will be published immediately after the post is made
205      * @throws org.apache.xmlrpc.XmlRpcException
206      * @return
207      */

208     public String JavaDoc newPost(String JavaDoc blogid, String JavaDoc userid, String JavaDoc password,
209             Hashtable JavaDoc struct, int publish) throws Exception JavaDoc {
210         
211         return newPost(blogid, userid, password, struct, publish > 0);
212     }
213     
214     
215     public String JavaDoc newPost(String JavaDoc blogid, String JavaDoc userid, String JavaDoc password,
216             Hashtable JavaDoc struct, boolean publish) throws Exception JavaDoc {
217         
218         mLogger.debug("newPost() Called ===========[ SUPPORTED ]=====");
219         mLogger.debug(" BlogId: " + blogid);
220         mLogger.debug(" UserId: " + userid);
221         mLogger.debug(" Publish: " + publish);
222         
223         WebsiteData website = validate(blogid, userid, password);
224         
225         Hashtable JavaDoc postcontent = struct;
226         String JavaDoc description = (String JavaDoc)postcontent.get("description");
227         String JavaDoc title = (String JavaDoc)postcontent.get("title");
228         if (StringUtils.isEmpty(title) && StringUtils.isEmpty(description)) {
229             throw new XmlRpcException(
230                     BLOGGERAPI_INCOMPLETE_POST, "Must specify title or description");
231         }
232         if (StringUtils.isEmpty(title)) {
233             title = Utilities.truncateNicely(description, 15, 15, "...");
234         }
235         
236         Date JavaDoc dateCreated = (Date JavaDoc)postcontent.get("dateCreated");
237         if (dateCreated == null) dateCreated = (Date JavaDoc)postcontent.get("pubDate");
238         if (dateCreated == null) dateCreated = new Date JavaDoc();
239         mLogger.debug(" Title: " + title);
240         
241         try {
242             Roller roller = RollerFactory.getRoller();
243             WeblogManager weblogMgr = roller.getWeblogManager();
244             UserData user = roller.getUserManager().getUserByUserName(userid);
245             Timestamp JavaDoc current =
246                     new Timestamp JavaDoc(System.currentTimeMillis());
247             
248             WeblogEntryData entry = new WeblogEntryData();
249             entry.setTitle(title);
250             entry.setText(description);
251             entry.setPubTime(new Timestamp JavaDoc(dateCreated.getTime()));
252             entry.setUpdateTime(current);
253             entry.setWebsite(website);
254             entry.setCreator(user);
255             if (Boolean.valueOf(publish).booleanValue()) {
256                 entry.setStatus(WeblogEntryData.PUBLISHED);
257             } else {
258                 entry.setStatus(WeblogEntryData.DRAFT);
259             }
260             
261             // MetaWeblog supports multiple cats, Roller supports one/entry
262
// so here we take accept the first category that exists
263
WeblogCategoryData rollerCat = null;
264             if ( postcontent.get("categories") != null ) {
265                 Vector JavaDoc cats = (Vector JavaDoc)postcontent.get("categories");
266                 if (cats != null && cats.size() > 0) {
267                     for (int i=0; i<cats.size(); i++) {
268                         String JavaDoc cat = (String JavaDoc)cats.get(i);
269                         rollerCat = weblogMgr.getWeblogCategoryByPath(website, cat);
270                         if (rollerCat != null) {
271                             entry.setCategory(rollerCat);
272                             break;
273                         }
274                     }
275                 }
276             }
277             if (rollerCat == null) {
278                 // or we fall back to the default Blogger API category
279
entry.setCategory(website.getBloggerCategory());
280             }
281             
282             // save the entry
283
weblogMgr.saveWeblogEntry(entry);
284             roller.flush();
285             
286             // notify cache
287
flushPageCache(entry.getWebsite());
288             
289             // TODO: Roller timestamps need better than 1 second accuracy
290
// Until then, we can't allow more than one post per second
291
Thread.sleep(1000);
292             
293             return entry.getId();
294         } catch (Exception JavaDoc e) {
295             String JavaDoc msg = "ERROR in MetaWeblogAPIHandler.newPost";
296             mLogger.error(msg,e);
297             throw new XmlRpcException(UNKNOWN_EXCEPTION, msg);
298         }
299     }
300     
301     
302     /**
303      *
304      * @param postid
305      * @param userid
306      * @param password
307      * @return
308      * @throws Exception
309      */

310     public Object JavaDoc getPost(String JavaDoc postid, String JavaDoc userid, String JavaDoc password)
311     throws Exception JavaDoc {
312         
313         mLogger.debug("getPost() Called =========[ SUPPORTED ]=====");
314         mLogger.debug(" PostId: " + postid);
315         mLogger.debug(" UserId: " + userid);
316         
317         Roller roller = RollerFactory.getRoller();
318         WeblogManager weblogMgr = roller.getWeblogManager();
319         WeblogEntryData entry = weblogMgr.getWeblogEntry(postid);
320         
321         validate(entry.getWebsite().getHandle(), userid,password);
322         
323         try {
324             return createPostStruct(entry, userid);
325         } catch (Exception JavaDoc e) {
326             String JavaDoc msg = "ERROR in MetaWeblogAPIHandler.getPost";
327             mLogger.error(msg,e);
328             throw new XmlRpcException(UNKNOWN_EXCEPTION, msg);
329         }
330     }
331     
332     
333     /**
334      * Allows user to post a binary object, a file, to Roller. If the file is
335      * allowed by the RollerConfig file-upload settings, then the file will be
336      * placed in the user's upload diretory.
337      */

338     public Object JavaDoc newMediaObject(String JavaDoc blogid, String JavaDoc userid, String JavaDoc password,
339             Hashtable JavaDoc struct) throws Exception JavaDoc {
340         
341         mLogger.debug("newMediaObject() Called =[ SUPPORTED ]=====");
342         mLogger.debug(" BlogId: " + blogid);
343         mLogger.debug(" UserId: " + userid);
344         mLogger.debug(" Password: *********");
345         
346         WebsiteData website = validate(blogid, userid, password);
347         try {
348             String JavaDoc name = (String JavaDoc) struct.get("name");
349             name = name.replaceAll("/","_");
350             String JavaDoc type = (String JavaDoc) struct.get("type");
351             mLogger.debug("newMediaObject name: " + name);
352             mLogger.debug("newMediaObject type: " + type);
353             
354             byte[] bits = (byte[]) struct.get("bits");
355             
356             Roller roller = RollerFactory.getRoller();
357             FileManager fmgr = roller.getFileManager();
358             RollerMessages msgs = new RollerMessages();
359             
360             // If save is allowed by Roller system-wide policies
361
if (fmgr.canSave(website.getHandle(), name, type, bits.length, msgs)) {
362                 // Then save the file
363
fmgr.saveFile(website.getHandle(), name, type, bits.length, new ByteArrayInputStream JavaDoc(bits));
364                 
365                 // TODO: build URL to uploaded file should be done in FileManager
366
String JavaDoc uploadPath = RollerFactory.getRoller().getFileManager().getUploadUrl();
367                 uploadPath += "/" + website.getHandle() + "/" + name;
368                 String JavaDoc fileLink = URLUtilities.getWeblogResourceURL(website, name, true);
369                 
370                 Hashtable JavaDoc returnStruct = new Hashtable JavaDoc(1);
371                 returnStruct.put("url", fileLink);
372                 return returnStruct;
373             }
374             throw new XmlRpcException(UPLOAD_DENIED_EXCEPTION,
375                     "File upload denied because:" + msgs.toString());
376         } catch (RollerException e) {
377             String JavaDoc msg = "ERROR in MetaWeblogAPIHandler.newMediaObject";
378             mLogger.error(msg,e);
379             throw new XmlRpcException(UNKNOWN_EXCEPTION, msg);
380         }
381     }
382     
383     
384     /**
385      * Get a list of recent posts for a category
386      *
387      * @param blogid Unique identifier of the blog the post will be added to
388      * @param userid Login for a Blogger user who has permission to post to the blog
389      * @param password Password for said username
390      * @param numposts Number of Posts to Retrieve
391      * @throws XmlRpcException
392      * @return
393      */

394     public Object JavaDoc getRecentPosts(String JavaDoc blogid, String JavaDoc userid, String JavaDoc password,
395             int numposts) throws Exception JavaDoc {
396         
397         mLogger.debug("getRecentPosts() Called ===========[ SUPPORTED ]=====");
398         mLogger.debug(" BlogId: " + blogid);
399         mLogger.debug(" UserId: " + userid);
400         mLogger.debug(" Number: " + numposts);
401         
402         WebsiteData website = validate(blogid, userid,password);
403         
404         try {
405             Vector JavaDoc results = new Vector JavaDoc();
406             
407             Roller roller = RollerFactory.getRoller();
408             WeblogManager weblogMgr = roller.getWeblogManager();
409             if (website != null) {
410                 List JavaDoc entries = weblogMgr.getWeblogEntries(
411                         website, // website
412
null,
413                         null, // startDate
414
null, // endDate
415
null, // catName
416
null, // status
417
"updateTime", // sortby
418
null, 0, numposts);
419                 
420                 Iterator JavaDoc iter = entries.iterator();
421                 while (iter.hasNext()) {
422                     WeblogEntryData entry = (WeblogEntryData)iter.next();
423                     results.addElement(createPostStruct(entry, userid));
424                 }
425             }
426             return results;
427             
428         } catch (Exception JavaDoc e) {
429             String JavaDoc msg = "ERROR in MetaWeblogAPIHandler.getRecentPosts";
430             mLogger.error(msg,e);
431             throw new XmlRpcException(UNKNOWN_EXCEPTION, msg);
432         }
433     }
434     
435     
436     private Hashtable JavaDoc createPostStruct(WeblogEntryData entry, String JavaDoc userid) {
437         
438         String JavaDoc permalink =
439                 RollerRuntimeConfig.getAbsoluteContextURL() + entry.getPermaLink();
440         
441         Hashtable JavaDoc struct = new Hashtable JavaDoc();
442         struct.put("title", entry.getTitle());
443         if (entry.getLink() != null) {
444             struct.put("link", Utilities.escapeHTML(entry.getLink()));
445         }
446         struct.put("description", entry.getText());
447         if (entry.getPubTime() != null) {
448             struct.put("pubDate", entry.getPubTime());
449             struct.put("dateCreated", entry.getPubTime());
450         }
451         struct.put("guid", Utilities.escapeHTML(permalink));
452         struct.put("permaLink", Utilities.escapeHTML(permalink));
453         struct.put("postid", entry.getId());
454         struct.put("userid", userid);
455         
456         Vector JavaDoc catArray = new Vector JavaDoc();
457         catArray.addElement(entry.getCategory().getPath());
458         struct.put("categories", catArray);
459         
460         return struct;
461     }
462     
463     
464     private Hashtable JavaDoc createCategoryStruct(WeblogCategoryData category, String JavaDoc userid) {
465         
466         String JavaDoc contextUrl = RollerRuntimeConfig.getAbsoluteContextURL();
467         
468         Hashtable JavaDoc struct = new Hashtable JavaDoc();
469         struct.put("description", category.getPath());
470         
471         String JavaDoc catUrl = contextUrl+"/page/"+userid+"?catname="+category.getPath();
472         catUrl = StringUtils.replace(catUrl," ","%20");
473         struct.put("htmlUrl", catUrl);
474         
475         String JavaDoc rssUrl = contextUrl+"/rss/"+userid+"?catname="+category.getPath();
476         rssUrl = StringUtils.replace(catUrl," ","%20");
477         struct.put("rssUrl",rssUrl);
478         
479         return struct;
480     }
481     
482 }
483
Popular Tags