1 package ch.odi.justblog.api.blogger;
2
3 import java.io.IOException;
4 import java.net.URL;
5
6 import javax.security.auth.callback.Callback;
7 import javax.security.auth.callback.CallbackHandler;
8 import javax.security.auth.callback.NameCallback;
9 import javax.security.auth.callback.PasswordCallback;
10 import javax.security.auth.callback.UnsupportedCallbackException;
11
12 import ch.odi.justblog.api.ApiException;
13 import ch.odi.justblog.api.AuthenticationFailedException;
14 import ch.odi.justblog.api.Blog;
15 import ch.odi.justblog.api.Entry;
16
17 /***
18 * A Blogger Blog.
19 *
20 * @author oglueck
21 */
22 public class BloggerBlog implements Blog {
23 private URL url;
24 private String id, name;
25 private String userName;
26 private char[] password;
27 private Blogger authenticatedBlogger;
28
29 /***
30 *
31 */
32 public BloggerBlog(String id) {
33 this.id = id;
34 }
35 /***
36 * @return Returns the name.
37 */
38 public String getName() {
39 return name;
40 }
41
42 /***
43 * @param name The name to set.
44 */
45 public void setName(String name) {
46 this.name = name;
47 }
48
49 /***
50 * @return Returns the url.
51 */
52 public URL getUrl() {
53 return url;
54 }
55
56 /***
57 * @param url The url to set.
58 */
59 public void setUrl(URL url) {
60 this.url = url;
61 }
62
63 /***
64 * @return Returns the id.
65 */
66 public String getId() {
67 return id;
68 }
69
70 public void authenticate(CallbackHandler authCallback) throws AuthenticationFailedException {
71 NameCallback namecb = new NameCallback("Username");
72 PasswordCallback passcb = new PasswordCallback("Password", false);
73 Callback[] callbacks = new Callback[] {
74 namecb,
75 passcb
76 };
77 try {
78 authCallback.handle(callbacks);
79 userName = namecb.getName();
80 password = passcb.getPassword();
81 } catch (IOException e) {
82 throw new RuntimeException(e);
83 } catch (UnsupportedCallbackException e) {
84 throw new RuntimeException(e);
85 }
86 Blogger blogger = new Blogger(getUrl());
87 blogger.setCredentials(userName, password);
88 try {
89 blogger.getUserInfo();
90 } catch (ApiException e) {
91 throw new AuthenticationFailedException(e);
92 } catch (IOException e) {
93 throw new AuthenticationFailedException(e);
94 }
95 blogger.setBlog(this);
96 authenticatedBlogger = blogger;
97 }
98
99
100 public void post(Entry entry) throws ApiException {
101 try {
102 IBloggerEntryExt ext = (IBloggerEntryExt) entry.getExtension(IBloggerEntryExt.class);
103 if (ext == null) {
104 String id = authenticatedBlogger.newPost(entry.getText(), true);
105 ext = new PersistentEntryExt();
106 ext.setId(id);
107 entry.addExtension(ext);
108 } else {
109 authenticatedBlogger.editPost(ext.getId(), entry.getText(), true);
110 }
111 } catch (IOException e) {
112 throw new ApiException(e);
113 }
114 }
115
116 }