KickJava   Java API By Example, From Geeks To Geeks.

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


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.sql.Timestamp JavaDoc;
22 import java.util.ArrayList 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.Map JavaDoc;
28 import java.util.StringTokenizer JavaDoc;
29 import java.util.Vector JavaDoc;
30
31 import javax.servlet.http.HttpServletRequest JavaDoc;
32
33 import org.apache.commons.lang.StringUtils;
34 import org.apache.commons.logging.Log;
35 import org.apache.commons.logging.LogFactory;
36 import org.apache.roller.RollerException;
37 import org.apache.roller.config.RollerRuntimeConfig;
38 import org.apache.roller.model.Roller;
39 import org.apache.roller.model.RollerFactory;
40 import org.apache.roller.model.UserManager;
41 import org.apache.roller.model.WeblogManager;
42 import org.apache.roller.pojos.UserData;
43 import org.apache.roller.pojos.WeblogEntryData;
44 import org.apache.roller.pojos.WeblogTemplate;
45 import org.apache.roller.pojos.WebsiteData;
46 import org.apache.roller.util.Utilities;
47 import org.apache.xmlrpc.XmlRpcException;
48
49 /**
50  * Roller XML-RPC Handler for the Blogger v1 API.
51  *
52  * Blogger API spec can be found at http://plant.blogger.com/api/index.html
53  * See also http://xmlrpc.free-conversant.com/docs/bloggerAPI
54  *
55  * @author David M Johnson
56  */

57 public class BloggerAPIHandler extends BaseAPIHandler {
58     
59     static final long serialVersionUID = 2398898776655115019L;
60     
61     private static Log mLogger = LogFactory.getLog(BloggerAPIHandler.class);
62     
63     public BloggerAPIHandler() {
64         super();
65     }
66     
67     
68     /**
69      * Delete a Post
70      *
71      * @param appkey Unique identifier/passcode of the application sending the post
72      * @param postid Unique identifier of the post to be changed
73      * @param userid Login for a Blogger user who has permission to post to the blog
74      * @param password Password for said username
75      * @param publish Ignored
76      * @throws XmlRpcException
77      * @return
78      */

79     public boolean deletePost(String JavaDoc appkey, String JavaDoc postid, String JavaDoc userid,
80             String JavaDoc password, boolean publish) throws Exception JavaDoc {
81         
82         mLogger.debug("deletePost() Called =====[ SUPPORTED ]=====");
83         mLogger.debug(" Appkey: " + appkey);
84         mLogger.debug(" PostId: " + postid);
85         mLogger.debug(" UserId: " + userid);
86         
87         Roller roller = RollerFactory.getRoller();
88         WeblogManager weblogMgr = roller.getWeblogManager();
89         WeblogEntryData entry = weblogMgr.getWeblogEntry(postid);
90         
91         validate(entry.getWebsite().getHandle(), userid, password);
92         
93         try {
94             // delete the entry
95
weblogMgr.removeWeblogEntry(entry);
96             roller.flush();
97             
98             // notify cache
99
flushPageCache(entry.getWebsite());
100         } catch (Exception JavaDoc e) {
101             String JavaDoc msg = "ERROR in blogger.deletePost: "+e.getClass().getName();
102             mLogger.error(msg,e);
103             throw new XmlRpcException(UNKNOWN_EXCEPTION, msg);
104         }
105         
106         return true;
107     }
108     
109     
110     /**
111      * Edits the main index template of a given blog. Roller only support
112      * updating the main template, the default template of your weblog.
113      *
114      * @param appkey Unique identifier/passcode of the application sending the post
115      * @param blogid Unique identifier of the blog the post will be added to
116      * @param userid Login for a Blogger user who has permission to post to the blog
117      * @param password Password for said username
118      * @param template The text for the new template (usually mostly HTML).
119      * @param templateType Determines which of the blog's templates is to be set.
120      * @throws XmlRpcException
121      * @return
122      */

123     public boolean setTemplate(String JavaDoc appkey, String JavaDoc blogid, String JavaDoc userid,
124             String JavaDoc password, String JavaDoc templateData,
125             String JavaDoc templateType) throws Exception JavaDoc {
126         
127         mLogger.debug("setTemplate() Called =====[ SUPPORTED ]=====");
128         mLogger.debug(" Appkey: " + appkey);
129         mLogger.debug(" BlogId: " + blogid);
130         mLogger.debug(" UserId: " + userid);
131         mLogger.debug(" Template: " + templateData);
132         mLogger.debug(" Type: " + templateType);
133         
134         validate(blogid, userid, password);
135         
136         if (! templateType.equals("main")) {
137             throw new XmlRpcException(
138                     UNKNOWN_EXCEPTION, "Roller only supports main template");
139         }
140         
141         try {
142             Roller roller = RollerFactory.getRoller();
143             UserManager userMgr = roller.getUserManager();
144             
145             WeblogTemplate page = userMgr.getPage(templateType);
146             page.setContents(templateData);
147             userMgr.savePage(page);
148             flushPageCache(page.getWebsite());
149             
150             return true;
151         } catch (RollerException e) {
152             String JavaDoc msg = "ERROR in BlooggerAPIHander.setTemplate";
153             mLogger.error(msg,e);
154             throw new XmlRpcException(UNKNOWN_EXCEPTION,msg);
155         }
156     }
157     
158     
159     /**
160      * Returns the main or archive index template of a given blog
161      *
162      * @param appkey Unique identifier/passcode of the application sending the post
163      * @param blogid Unique identifier of the blog the post will be added to
164      * @param userid Login for a Blogger user who has permission to post to the blog
165      * @param password Password for said username
166      * @param templateType Determines which of the blog's templates will be returned. Currently, either "main" or "archiveIndex"
167      * @throws XmlRpcException
168      * @return
169      */

170     public String JavaDoc getTemplate(String JavaDoc appkey, String JavaDoc blogid, String JavaDoc userid,
171             String JavaDoc password, String JavaDoc templateType)
172             throws Exception JavaDoc {
173         
174         mLogger.debug("getTemplate() Called =====[ SUPPORTED ]=====");
175         mLogger.debug(" Appkey: " + appkey);
176         mLogger.debug(" BlogId: " + blogid);
177         mLogger.debug(" UserId: " + userid);
178         mLogger.debug(" Type: " + templateType);
179         
180         validate(blogid, userid,password);
181         
182         try {
183             Roller roller = RollerFactory.getRoller();
184             UserManager userMgr = roller.getUserManager();
185             WeblogTemplate page = userMgr.getPage(templateType);
186             
187             if ( null == page ) {
188                 throw new XmlRpcException(UNKNOWN_EXCEPTION,"Template not found");
189             } else {
190                 return page.getContents();
191             }
192         } catch (Exception JavaDoc e) {
193             String JavaDoc msg = "ERROR in BlooggerAPIHander.getTemplate";
194             mLogger.error(msg,e);
195             throw new XmlRpcException(UNKNOWN_EXCEPTION,msg);
196         }
197     }
198     
199     
200     /**
201      * Authenticates a user and returns basic user info (name, email, userid, etc.)
202      *
203      * @param appkey Unique identifier/passcode of the application sending the post
204      * @param userid Login for a Blogger user who has permission to post to the blog
205      * @param password Password for said username
206      * @throws XmlRpcException
207      * @return
208      */

209     public Object JavaDoc getUserInfo(String JavaDoc appkey, String JavaDoc userid, String JavaDoc password)
210     throws Exception JavaDoc {
211         
212         mLogger.debug("getUserInfo() Called =====[ SUPPORTED ]=====");
213         mLogger.debug(" Appkey: " + appkey);
214         mLogger.debug(" UserId: " + userid);
215         
216         validateUser(userid, password);
217         
218         try {
219             Roller roller = RollerFactory.getRoller();
220             UserManager userMgr = roller.getUserManager();
221             UserData user = userMgr.getUserByUserName(userid);
222             
223             // parses full name into two strings, firstname and lastname
224
String JavaDoc firstname = "", lastname = "";
225             StringTokenizer JavaDoc toker = new StringTokenizer JavaDoc(user.getFullName());
226             
227             if (toker.hasMoreTokens()) {
228                 firstname = toker.nextToken();
229             }
230             
231             while (toker.hasMoreTokens()) {
232                 if ( !lastname.equals("") ) {
233                     lastname += " ";
234                 }
235                 lastname += toker.nextToken();
236             }
237             
238             // populates user information to return as a result
239
Hashtable JavaDoc result = new Hashtable JavaDoc();
240             result.put("nickname", user.getUserName());
241             result.put("userid", user.getUserName());
242             result.put("email", "");
243             result.put("lastname", lastname);
244             result.put("firstname", firstname);
245             
246             return result;
247         } catch (RollerException e) {
248             String JavaDoc msg = "ERROR in BlooggerAPIHander.getInfo";
249             mLogger.error(msg,e);
250             throw new XmlRpcException(UNKNOWN_EXCEPTION,msg);
251         }
252     }
253     
254     
255     /**
256      * Returns information on all the blogs a given user is a member of
257      *
258      * @param appkey Unique identifier/passcode of the application sending the post
259      * @param userid Login for a Blogger user who has permission to post to the blog
260      * @param password Password for said username
261      * @throws XmlRpcException
262      * @return
263      */

264     public Object JavaDoc getUsersBlogs(String JavaDoc appkey, String JavaDoc userid, String JavaDoc password)
265     throws Exception JavaDoc {
266         
267         mLogger.debug("getUsersBlogs() Called ===[ SUPPORTED ]=======");
268         mLogger.debug(" Appkey: " + appkey);
269         mLogger.debug(" UserId: " + userid);
270         
271         Vector JavaDoc result = new Vector JavaDoc();
272         if (validateUser(userid, password)) {
273             try {
274                 String JavaDoc contextUrl = RollerRuntimeConfig.getAbsoluteContextURL();
275                 
276                 UserManager umgr = RollerFactory.getRoller().getUserManager();
277                 UserData user = umgr.getUserByUserName(userid);
278                 // get list of user's enabled websites
279
List JavaDoc websites = umgr.getWebsites(user, Boolean.TRUE, null, null, null, 0, -1);
280                 Iterator JavaDoc iter = websites.iterator();
281                 while (iter.hasNext()) {
282                     WebsiteData website = (WebsiteData)iter.next();
283                     Hashtable JavaDoc blog = new Hashtable JavaDoc(3);
284                     blog.put("url", website.getURL());
285                     blog.put("blogid", website.getHandle());
286                     blog.put("blogName", website.getName());
287                     result.add(blog);
288                 }
289             } catch (Exception JavaDoc e) {
290                 String JavaDoc msg = "ERROR in BlooggerAPIHander.getUsersBlogs";
291                 mLogger.error(msg,e);
292                 throw new XmlRpcException(UNKNOWN_EXCEPTION, msg);
293             }
294         }
295         return result;
296     }
297     
298     
299     /**
300      * Edits a given post. Optionally, will publish the blog after making the edit
301      *
302      * @param appkey Unique identifier/passcode of the application sending the post
303      * @param postid Unique identifier of the post to be changed
304      * @param userid Login for a Blogger user who has permission to post to the blog
305      * @param password Password for said username
306      * @param content Contents of the post
307      * @param publish If true, the blog will be published immediately after the post is made
308      * @throws XmlRpcException
309      * @return
310      */

311     public boolean editPost(String JavaDoc appkey, String JavaDoc postid, String JavaDoc userid,
312             String JavaDoc password, String JavaDoc content, boolean publish)
313             throws Exception JavaDoc {
314         
315         mLogger.debug("editPost() Called ========[ SUPPORTED ]=====");
316         mLogger.debug(" Appkey: " + appkey);
317         mLogger.debug(" PostId: " + postid);
318         mLogger.debug(" UserId: " + userid);
319         mLogger.debug(" Publish: " + publish);
320         mLogger.debug(" Content:\n " + content);
321         
322         if (validateUser(userid, password)) {
323             try {
324                 Timestamp JavaDoc current = new Timestamp JavaDoc(System.currentTimeMillis());
325                 
326                 Roller roller = RollerFactory.getRoller();
327                 WeblogManager weblogMgr = roller.getWeblogManager();
328                 WeblogEntryData entry = weblogMgr.getWeblogEntry(postid);
329                 entry.setText(content);
330                 entry.setUpdateTime(current);
331                 if (Boolean.valueOf(publish).booleanValue()) {
332                     entry.setStatus(WeblogEntryData.PUBLISHED);
333                 } else {
334                     entry.setStatus(WeblogEntryData.DRAFT);
335                 }
336                 
337                 // save the entry
338
weblogMgr.saveWeblogEntry(entry);
339                 roller.flush();
340                 
341                 // notify cache
342
flushPageCache(entry.getWebsite());
343                 
344                 return true;
345             } catch (Exception JavaDoc e) {
346                 String JavaDoc msg = "ERROR in BlooggerAPIHander.editPost";
347                 mLogger.error(msg,e);
348                 throw new XmlRpcException(UNKNOWN_EXCEPTION, msg);
349             }
350         }
351         return false;
352     }
353     
354     
355     /**
356      * Makes a new post to a designated blog. Optionally, will publish the blog after making the post
357      *
358      * @param appkey Unique identifier/passcode of the application sending the post
359      * @param blogid Unique identifier of the blog the post will be added to
360      * @param userid Login for a Blogger user who has permission to post to the blog
361      * @param password Password for said username
362      * @param content Contents of the post
363      * @param publish If true, the blog will be published immediately after the post is made
364      * @throws XmlRpcException
365      * @return
366      */

367     public String JavaDoc newPost(String JavaDoc appkey, String JavaDoc blogid, String JavaDoc userid,
368             String JavaDoc password, String JavaDoc content, boolean publish)
369             throws Exception JavaDoc {
370         
371         mLogger.debug("newPost() Called ===========[ SUPPORTED ]=====");
372         mLogger.debug(" Appkey: " + appkey);
373         mLogger.debug(" BlogId: " + blogid);
374         mLogger.debug(" UserId: " + userid);
375         mLogger.debug(" Publish: " + publish);
376         mLogger.debug(" Content:\n " + content);
377         
378         WebsiteData website = validate(blogid, userid, password);
379         
380         // extract the title from the content
381
String JavaDoc title = "";
382         
383         if (content.indexOf("<title>") != -1) {
384             title =
385                     content.substring(content.indexOf("<title>") + 7,
386                     content.indexOf("</title>"));
387             content = StringUtils.replace(content, "<title>"+title+"</title>", "");
388         }
389         if (StringUtils.isEmpty(title)) {
390             title = Utilities.truncateNicely(content, 15, 15, "...");
391         }
392         
393         try {
394             Roller roller = RollerFactory.getRoller();
395             WeblogManager weblogMgr = roller.getWeblogManager();
396             
397             Timestamp JavaDoc current = new Timestamp JavaDoc(System.currentTimeMillis());
398             
399             WeblogEntryData entry = new WeblogEntryData();
400             entry.setTitle(title);
401             entry.setText(content);
402             entry.setPubTime(current);
403             entry.setUpdateTime(current);
404             UserData user = roller.getUserManager().getUserByUserName(userid);
405             entry.setCreator(user);
406             entry.setWebsite(website);
407             entry.setCategory(website.getBloggerCategory());
408             if (Boolean.valueOf(publish).booleanValue()) {
409                 entry.setStatus(WeblogEntryData.PUBLISHED);
410             } else {
411                 entry.setStatus(WeblogEntryData.DRAFT);
412             }
413             
414             // save the entry
415
weblogMgr.saveWeblogEntry(entry);
416             roller.flush();
417             
418             // notify cache
419
flushPageCache(entry.getWebsite());
420             
421             return entry.getId();
422         } catch (Exception JavaDoc e) {
423             String JavaDoc msg = "ERROR in BlooggerAPIHander.newPost";
424             mLogger.error(msg,e);
425             throw new XmlRpcException(UNKNOWN_EXCEPTION, msg);
426         }
427     }
428     
429     
430     /**
431      * This method was added to the Blogger 1.0 API via an Email from Evan
432      * Williams to the Yahoo Group bloggerDev, see the email message for details -
433      * http://groups.yahoo.com/group/bloggerDev/message/225
434      *
435      * @param appkey Unique identifier/passcode of the application sending the post
436      * @param blogid Unique identifier of the blog the post will be added to
437      * @param userid Login for a Blogger user who has permission to post to the blog
438      * @param password Password for said username
439      * @param numposts Number of Posts to Retrieve
440      * @throws XmlRpcException
441      * @return Vector of Hashtables, each containing dateCreated, userid, postid, content
442      */

443     public Object JavaDoc getRecentPosts(String JavaDoc appkey, String JavaDoc blogid, String JavaDoc userid,
444             String JavaDoc password, int numposts)
445             throws Exception JavaDoc {
446         
447         mLogger.debug("getRecentPosts() Called ===========[ SUPPORTED ]=====");
448         mLogger.debug(" Appkey: " + appkey);
449         mLogger.debug(" BlogId: " + blogid);
450         mLogger.debug(" UserId: " + userid);
451         mLogger.debug(" Number: " + numposts);
452         
453         WebsiteData website = validate(blogid, userid,password);
454         
455         try {
456             Vector JavaDoc results = new Vector JavaDoc();
457             
458             Roller roller = RollerFactory.getRoller();
459             WeblogManager weblogMgr = roller.getWeblogManager();
460             if (website != null) {
461                 Map JavaDoc entries = weblogMgr.getWeblogEntryObjectMap(
462                         website, // website
463
null, // startDate
464
new Date JavaDoc(), // endDate
465
null, // catName
466
null, null, 0, -1);
467                 
468                 Iterator JavaDoc iter = entries.values().iterator();
469                 while (iter.hasNext()) {
470                     ArrayList JavaDoc list = (ArrayList JavaDoc) iter.next();
471                     Iterator JavaDoc i = list.iterator();
472                     while (i.hasNext()) {
473                         WeblogEntryData entry = (WeblogEntryData) i.next();
474                         Hashtable JavaDoc result = new Hashtable JavaDoc();
475                         if (entry.getPubTime() != null) {
476                             result.put("dateCreated", entry.getPubTime());
477                         }
478                         result.put("userid", userid);
479                         result.put("postid", entry.getId());
480                         result.put("content", entry.getText());
481                         results.add(result);
482                     }
483                 }
484             }
485             return results;
486         } catch (Exception JavaDoc e) {
487             String JavaDoc msg = "ERROR in BlooggerAPIHander.getRecentPosts";
488             mLogger.error(msg,e);
489             throw new XmlRpcException(UNKNOWN_EXCEPTION, msg);
490         }
491     }
492     
493 }
494
Popular Tags