KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jivesoftware > messenger > plugin > ImportExportPlugin


1 package org.jivesoftware.messenger.plugin;
2
3 import java.io.File JavaDoc;
4 import java.io.FileWriter JavaDoc;
5 import java.io.IOException JavaDoc;
6 import java.io.StringWriter JavaDoc;
7 import java.net.MalformedURLException JavaDoc;
8 import java.util.ArrayList JavaDoc;
9 import java.util.Collection JavaDoc;
10 import java.util.HashMap JavaDoc;
11 import java.util.Iterator JavaDoc;
12 import java.util.List JavaDoc;
13 import java.util.Map JavaDoc;
14 import java.util.StringTokenizer JavaDoc;
15
16 import org.dom4j.Document;
17 import org.dom4j.DocumentException;
18 import org.dom4j.DocumentHelper;
19 import org.dom4j.Element;
20 import org.dom4j.io.OutputFormat;
21 import org.dom4j.io.SAXReader;
22 import org.dom4j.io.XMLWriter;
23 import org.jivesoftware.messenger.XMPPServer;
24 import org.jivesoftware.messenger.container.Plugin;
25 import org.jivesoftware.messenger.container.PluginManager;
26 import org.jivesoftware.messenger.roster.RosterItem;
27 import org.jivesoftware.messenger.roster.RosterItemProvider;
28 import org.jivesoftware.messenger.user.User;
29 import org.jivesoftware.messenger.user.UserAlreadyExistsException;
30 import org.jivesoftware.messenger.user.UserManager;
31 import org.jivesoftware.messenger.user.UserNotFoundException;
32 import org.jivesoftware.messenger.user.UserProvider;
33 import org.jivesoftware.util.JiveGlobals;
34 import org.jivesoftware.util.Log;
35 import org.xmpp.packet.JID;
36
37 /**
38  * The user import/export plugin provides a way to import and export Jive Messenger
39  * user data via the Admin Console. The user data consists of jid (aka "username"),
40  * name, email address, password and roster list (aka "buddy list"). This plugin also
41  * can aid in the migration of users from other Jabber/XMPP based systems to Jive
42  * Messenger.
43  *
44  * @author Ryan Graham
45  */

46 public class ImportExportPlugin implements Plugin {
47     private UserManager userManager;
48     private PluginManager pluginManager;
49     private UserProvider provider;
50     
51     private String JavaDoc serverName;
52     private String JavaDoc exportDirectory;
53     
54     public ImportExportPlugin() {
55         userManager = XMPPServer.getInstance().getUserManager();
56         provider = UserManager.getUserProvider();
57         
58         serverName = XMPPServer.getInstance().getServerInfo().getName();
59         
60         
61         if (exportDirectory == null) {
62             if (JiveGlobals.getHomeDirectory() != null) {
63                 File JavaDoc messengerHome = new File JavaDoc(JiveGlobals.getHomeDirectory());
64                 if (messengerHome.exists() && messengerHome.canWrite()) {
65                     exportDirectory = (new File JavaDoc(messengerHome, "export")).toString();
66                 }
67             }
68         }
69         
70         if (!exportDirectory.endsWith(File.separator)) {
71             exportDirectory = exportDirectory + File.separator;
72         }
73
74         // Make sure the export directory exists. If not, make it:
75
File JavaDoc exportDir = new File JavaDoc(exportDirectory);
76         if (!exportDir.exists()) {
77             exportDir.mkdir();
78         }
79     }
80
81     public void initializePlugin(PluginManager manager, File JavaDoc pluginDirectory) {
82         pluginManager = manager;
83     }
84
85     public void destroyPlugin() {
86         userManager = null;
87         pluginManager = null;
88         provider = null;
89         serverName = null;
90         exportDirectory = null;
91     }
92     
93     public boolean isUserProviderReadOnly() {
94         return provider.isReadOnly();
95     }
96     
97     public String JavaDoc exportDirectory() {
98         return exportDirectory;
99     }
100     
101     public boolean exportUsersToFile(String JavaDoc file) throws IOException JavaDoc {
102         if (!file.endsWith(".xml")) {
103             file += ".xml";
104         }
105         String JavaDoc exportFilePath = exportDirectory + file;
106         
107         XMLWriter writer = null;
108         try {
109             writer = new XMLWriter(new FileWriter JavaDoc(exportFilePath), OutputFormat.createPrettyPrint());
110             writer.write(exportUsers());
111         } catch (IOException JavaDoc ioe) {
112             Log.error(ioe);
113             throw ioe;
114         } finally {
115             if (writer != null) {
116                 writer.close();
117             }
118         }
119         
120         return true;
121     }
122     
123     public String JavaDoc exportUsersToString() throws IOException JavaDoc {
124         StringWriter JavaDoc stringWriter = new StringWriter JavaDoc();
125         XMLWriter writer = null;
126         try {
127             writer = new XMLWriter(stringWriter, OutputFormat.createPrettyPrint());
128             writer.write(exportUsers());
129         } catch (IOException JavaDoc ioe) {
130             Log.error(ioe);
131             throw ioe;
132         } finally {
133             if (writer != null) {
134                 writer.close();
135             }
136         }
137         
138         return stringWriter.toString();
139     }
140     
141     public boolean validateImportFile(String JavaDoc file) {
142         String JavaDoc importFilePath = exportDirectory + file;
143         
144         try {
145             return new UserSchemaValidator(importFilePath, "messenger-user-schema.xsd.xml").validate();
146         }
147         catch (Exception JavaDoc e) {
148             Log.error(e);
149             return false;
150         }
151     }
152     
153     public List JavaDoc importUserData(String JavaDoc file) throws MalformedURLException JavaDoc, DocumentException {
154         String JavaDoc importFilePath = exportDirectory + File.separator + file;
155         
156         SAXReader reader = new SAXReader();
157         Document document = reader.read(new File JavaDoc(importFilePath).toURL());
158         return importUsers(document);
159     }
160     
161     private Document exportUsers() {
162         Document document = DocumentHelper.createDocument();
163         Element root = document.addElement("JiveMessenger");
164
165         Collection JavaDoc<User> users = userManager.getUsers();
166         for (User user : users) {
167             Element userElement = root.addElement("User");
168             String JavaDoc userName = user.getUsername();
169 // if (userName != null) {
170
// try {
171
// userName = URLEncoder.encode(userName, "UTF-8");
172
// } catch (UnsupportedEncodingException e) {
173
// Log.error(e);
174
// userName = "";
175
// }
176
// } else {
177
// userName = "";
178
// }
179
userElement.addElement("Jid").addText(userName);
180             
181             try {
182                 userElement.addElement("Password").addText(provider.getPassword(user.getUsername()));
183             }
184             catch (UserNotFoundException e) {
185                 //this should never happen
186
Log.info("User not found: " + userName + ", setting password to their username");
187                 userElement.addElement("Password").addText(userName);
188             }
189             userElement.addElement("Email").addText(user.getEmail() == null ? "" : user.getEmail());
190             
191             String JavaDoc name = user.getName();
192 // if (name != null) {
193
// try {
194
// name = URLEncoder.encode(name, "UTF-8");
195
// } catch (UnsupportedEncodingException e) {
196
// Log.error(e);
197
// name = "";
198
// }
199
// } else {
200
// name = "";
201
// }
202
userElement.addElement("Name").addText(name == null ? "" : name);
203             
204             //creation and modified datte are not used as part of the import process but are exported
205
//for historical purposes, should they be formatted differently?
206
userElement.addElement("CreationDate").addText(String.valueOf(user.getCreationDate().getTime()));
207             userElement.addElement("ModifiedDate").addText(String.valueOf(user.getModificationDate().getTime()));
208             
209             Element rosterElement = userElement.addElement("Roster");
210             Collection JavaDoc<RosterItem> roster = user.getRoster().getRosterItems();
211             for (RosterItem ri : roster) {
212                 Element itemElement = rosterElement.addElement("Item");
213                 itemElement.addAttribute("jid", removeDoman(ri.getJid()));
214                 itemElement.addAttribute("askstatus", String.valueOf(ri.getAskStatus().getValue()));
215                 itemElement.addAttribute("recvstatus", String.valueOf(ri.getRecvStatus().getValue()));
216                 itemElement.addAttribute("substatus", String.valueOf(ri.getSubStatus().getValue()));
217                 itemElement.addAttribute("name", ri.getNickname());
218                 
219                 Element groupElement = itemElement.addElement("Group");
220                 List JavaDoc<String JavaDoc> groups = ri.getGroups();
221                 for (String JavaDoc group : groups) {
222                     groupElement.addText(group);
223                 }
224             }
225         }
226
227         return document;
228     }
229     
230     public List JavaDoc<String JavaDoc> importUsers(Document document) throws DocumentException {
231         List JavaDoc<String JavaDoc> duplicateUsers = new ArrayList JavaDoc<String JavaDoc>();
232         
233         UserManager userManager = UserManager.getInstance();
234         RosterItemProvider rosterItemProvider = RosterItemProvider.getInstance();
235         
236         Map JavaDoc<String JavaDoc, List JavaDoc> rosterMap = new HashMap JavaDoc<String JavaDoc, List JavaDoc>();
237         
238         Element users = document.getRootElement();
239         
240         Iterator JavaDoc usersIter = users.elementIterator("User");
241         while (usersIter.hasNext()) {
242             Element user = (Element) usersIter.next();
243             
244             String JavaDoc userName = null;
245             String JavaDoc password = null;
246             String JavaDoc email = null;
247             String JavaDoc name = null;
248             List JavaDoc<RosterItem> rosterItems = new ArrayList JavaDoc<RosterItem>();
249             
250             Iterator JavaDoc userElements = user.elementIterator();
251             while (userElements.hasNext()) {
252                 Element userElement = (Element) userElements.next();
253                 
254                 String JavaDoc nameElement = userElement.getName();
255                 
256                 if ("Jid".equals(nameElement)) {
257                     userName = userElement.getText();
258                 }
259                 else if ("Password".equals(nameElement)) {
260                     password = userElement.getText();
261                 }
262                 else if ("Name".equals(nameElement)) {
263                     name = userElement.getText();
264                 }
265                 else if ("Email".equals(nameElement)) {
266                     email = userElement.getText();
267                 }
268                 else if ("Roster".equals(nameElement)) {
269                     Iterator JavaDoc rosterIter = userElement.elementIterator("Item");
270                     
271                     while (rosterIter.hasNext()) {
272                         Element rosterElement = (Element) rosterIter.next();
273                         
274                         String JavaDoc jid = rosterElement.attributeValue("jid");
275                         String JavaDoc askstatus = rosterElement.attributeValue("askstatus");
276                         String JavaDoc recvstatus = rosterElement.attributeValue("recvstatus");
277                         String JavaDoc substatus = rosterElement.attributeValue("substatus");
278                         String JavaDoc nickname = rosterElement.attributeValue("name");
279                         
280                         List JavaDoc<String JavaDoc> groups = new ArrayList JavaDoc<String JavaDoc>();
281                         Iterator JavaDoc groupIter = rosterElement.elementIterator("Group");
282                         while (groupIter.hasNext()) {
283                             Element group = (Element) groupIter.next();
284                             groups.add(group.getText());
285                         }
286                         
287                         rosterItems.add(new RosterItem(new JID(jid + "@" + serverName),
288                                         RosterItem.SubType.getTypeFromInt(Integer.parseInt(substatus)),
289                                         RosterItem.AskType.getTypeFromInt(Integer.parseInt(askstatus)),
290                                         RosterItem.RecvType.getTypeFromInt(Integer.parseInt(recvstatus)),
291                                         nickname,
292                                         groups));
293                     }
294                 }
295             }
296             
297             if ((userName != null) && (password != null)) {
298                 try {
299                     userManager.createUser(userName, password, name, email);
300                     rosterMap.put(userName, rosterItems);
301                 }
302                 catch (UserAlreadyExistsException e) {
303                     Log.info("User already exists: " + userName);
304                     duplicateUsers.add(userName);
305                 }
306             }
307         }
308         
309         //this prevents a user from adding a non-existent user to their roster
310
Iterator JavaDoc i = rosterMap.keySet().iterator();
311         while (i.hasNext()) {
312             String JavaDoc userName = (String JavaDoc) i.next();
313             
314             Iterator JavaDoc rosterIter = rosterMap.get(userName).iterator();
315             while (rosterIter.hasNext()) {
316                 RosterItem ri = (RosterItem) rosterIter.next();
317                 
318                 try {
319                     userManager.getUser(removeDoman(ri.getJid()));
320                     rosterItemProvider.createItem(userName, ri);
321                 }
322                 catch (UserNotFoundException e) {
323                     Log.info("User '" + removeDoman(ri.getJid()) + "' not found, will not be added to '" + userName + "' roster.");
324                 }
325                 catch (UserAlreadyExistsException e) {
326                     Log.info("User '" + removeDoman(ri.getJid()) + "' already belongs to '" + userName + "' roster.");
327                 }
328             }
329         }
330         
331         return duplicateUsers;
332      }
333     
334     private static String JavaDoc removeDoman(JID jid) {
335         StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(jid.toBareJID(), "@");
336         if (tokens.hasMoreTokens()) {
337             return tokens.nextToken();
338         }
339         
340         return null;
341     }
342 }
343
344
Popular Tags