KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > tools > migration > JahiaTableMigrator


1 package org.jahia.tools.migration;
2
3 import org.w3c.dom.Element JavaDoc;
4 import org.w3c.dom.NodeList JavaDoc;
5 import org.w3c.dom.Document JavaDoc;
6 import javax.xml.parsers.DocumentBuilder JavaDoc;
7 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
8 import java.io.FileInputStream JavaDoc;
9 import java.util.Vector JavaDoc;
10 import java.util.Iterator JavaDoc;
11
12 import java.sql.Statement JavaDoc;
13 import java.sql.ResultSet JavaDoc;
14 import java.sql.SQLException JavaDoc;
15 import java.sql.Connection JavaDoc;
16
17 import javax.naming.NamingException JavaDoc;
18 import javax.naming.directory.SearchResult JavaDoc;
19 import javax.naming.NamingEnumeration JavaDoc;
20 import javax.naming.directory.InitialDirContext JavaDoc;
21 import javax.naming.directory.SearchControls JavaDoc;
22
23 /**
24  * This class will be able to migrate some entries into the Jahia database
25  * in order to be able to change the key used for authentication
26  *
27  * @author PELTIER Olivier
28  * @version 1.0
29  */

30 public class JahiaTableMigrator {
31
32     // Static Strings for processing
33
public static final String JavaDoc USAGE = "JahiaTableMigrator <properties_file>";
34     public static final String JavaDoc ROOT_TAG = "migrator-configuration";
35     public static final String JavaDoc TABLES_ROOT_TAG = "table";
36         
37     public static final int CONFIGURATION_ERROR = 1;
38     
39     // internal connection to the LDAP server
40
private static LDAPConnector ldapconn;
41     
42     // internal connection to the Jahia DataBase
43
private static DBConnector dbconn;
44     
45     // all tables to migrate, loaded from xml configuration file
46
private Vector JavaDoc tablesToMigrate;
47     
48     private static org.apache.log4j.Logger logger =
49             org.apache.log4j.Logger.getLogger (JahiaTableMigrator.class);
50
51     // main method, process should be run as a batch
52
public static void main(String JavaDoc[] args) {
53         JahiaTableMigrator jtm = new JahiaTableMigrator();
54         if (jtm.loadConfiguration(args[0])) {
55             // configuration loaded is ok, lets go
56
jtm.migrate();
57         }else {
58             // exits with configuration error
59
logger.info("Configuration error...");
60             System.exit(CONFIGURATION_ERROR);
61         }
62     }
63     
64     /**
65      * Default Constructor.
66      */

67     public JahiaTableMigrator() {
68     }
69     
70     private boolean loadConfiguration(String JavaDoc fileName) {
71         boolean result = false;
72         logger.info("loading configuration");
73         Document JavaDoc documentRoot = null;
74
75         try {
76             // loads and parse the xml configuration file
77
DocumentBuilderFactory JavaDoc dfactory = DocumentBuilderFactory.newInstance ();
78             DocumentBuilder JavaDoc docBuilder = dfactory.newDocumentBuilder ();
79             FileInputStream JavaDoc configStream = new FileInputStream JavaDoc (fileName);
80             documentRoot = docBuilder.parse (configStream);
81             documentRoot.normalize (); // clean up DOM tree a little
82
} catch (Throwable JavaDoc t) {
83             logger.error("loading configuration ended", t);
84             return false;
85         }
86         
87         // extract the root element
88
Element JavaDoc rootTag = documentRoot.getDocumentElement ();
89         
90         if (ROOT_TAG.equals(rootTag.getTagName())) {
91             // initializing connectors
92
ldapconn = new LDAPConnector(rootTag);
93             dbconn = new DBConnector(rootTag);
94             
95             // loading tables to migrate
96
tablesToMigrate = loadTablesDefinition(rootTag);
97             
98             // evaluating loding status
99
result = ldapconn.isInitialized() && dbconn.isInitialized() && tablesToMigrate.size() > 0;
100         }
101         
102         logger.info("loading configuration ended");
103         return result;
104     }
105     
106     private Vector JavaDoc loadTablesDefinition(Element JavaDoc element) {
107         logger.info("loading tables definitions to migrate");
108         Vector JavaDoc result = new Vector JavaDoc();
109         
110         // get the node where tables should be defined
111
NodeList JavaDoc tablesList = element.getElementsByTagName (TABLES_ROOT_TAG);
112         for (int i = 0; i < tablesList.getLength (); i++) {
113             // adding new TableToMigrate
114
result.add(new TableToMigrate((Element JavaDoc)tablesList.item(i)));
115         }
116         
117         logger.info("table definitions loaded");
118         return result;
119     }
120     
121     private void migrate() {
122         logger.info("Starting migration...");
123         try {
124             for (Iterator JavaDoc ite = tablesToMigrate.iterator(); ite.hasNext();) {
125                 // migrate each tables
126
migrateTable((TableToMigrate)ite.next());
127             }
128         } catch (SQLException JavaDoc sqle) {
129             logger.error("SQLException occured", sqle);
130         } catch (NamingException JavaDoc ne) {
131             logger.error("NamingException occured", ne);
132         }
133         logger.info("Migration ended...");
134     }
135
136     private void migrateTable(TableToMigrate ttm) throws SQLException JavaDoc, NamingException JavaDoc {
137         logger.info("Table to migrate : " + ttm.getTableName());
138         // get a connection from connector
139
Connection JavaDoc conn = dbconn.getConnection();
140         conn.setAutoCommit(false);
141         
142         // create a Statement and get data that match all defined pattern
143
Statement JavaDoc stmt = conn.createStatement();
144         ResultSet JavaDoc content = stmt.executeQuery("SELECT DISTINCT "
145                                         + ttm.getColumnName()
146                                         + " FROM "
147                                         + ttm.getTableName()
148                                         + " WHERE "
149                                         + ttm.getColumnName()
150                                         + " LIKE '"
151                                         + ttm.getDbCriteria()
152                                         + "'");
153
154         // processing all results
155
while (content.next()) {
156             // get rid off the prefix used in the DB
157
String JavaDoc value = removePrefix(ttm.getDbPrefix(), content.getString(1));
158             // get all users in the LDAP server
159
NamingEnumeration JavaDoc ldapentries = getLdapEntry(value, ttm);
160             if (!ldapentries.hasMore())
161                 // no results...
162
logger.warn("No results for this value :: " + value);
163
164             while (ldapentries.hasMore()) {
165                 SearchResult JavaDoc srlt = (SearchResult JavaDoc)ldapentries.nextElement();
166                 if (ldapentries.hasMore()) {
167                     // too much results, the system can't decide alone
168
logger.warn("duplicate ldap entry found for " + value);
169                 } else {
170                     // update the table for this user
171
String JavaDoc newvalue = (String JavaDoc)srlt.getAttributes().get(ttm.getNewAttr()).get();
172                     logger.info("ldap entry found, migrating from " + value + " to " + newvalue);
173                     updateTable(conn, ttm.getDbPrefix() + value, ttm.getDbPrefix() + newvalue, ttm);
174                 }
175             }
176         }
177         
178         // commit and close...
179
conn.commit();
180         stmt.close();
181         conn.close();
182     }
183     
184     private NamingEnumeration JavaDoc getLdapEntry(String JavaDoc value, TableToMigrate ttm) throws NamingException JavaDoc {
185         // get context from connector
186
InitialDirContext JavaDoc idc = ldapconn.getContext();
187         
188         // initializing SearchControls
189
SearchControls JavaDoc sctrls = new SearchControls JavaDoc();
190         sctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
191         sctrls.setReturningAttributes(new String JavaDoc[]{ttm.getNewAttr()});
192         
193         // creating the filter for the LDAP query
194
String JavaDoc filter = "(&" + ttm.getLdapCriteria() + "(" + ttm.getCurrentAttr() + "=" + value + "))";
195         
196         // run the query
197
return idc.search(ldapconn.getBaseDN(),
198                                 filter,
199                                 sctrls);
200     }
201     
202     private String JavaDoc removePrefix(String JavaDoc prefix, String JavaDoc value) {
203         if (value.startsWith(prefix))
204             return value.substring(prefix.length());
205         else
206             return value;
207     }
208     
209     private void updateTable(Connection JavaDoc conn, String JavaDoc oldValue, String JavaDoc newValue, TableToMigrate ttm) throws SQLException JavaDoc {
210         // get a Statement
211
Statement JavaDoc stmt = conn.createStatement();
212         
213         // execute the update
214
stmt.execute("UPDATE "
215                         + ttm.getTableName()
216                         + " SET "
217                         + ttm.getColumnName()
218                         + "='"
219                         + newValue
220                         + "' WHERE "
221                         + ttm.getColumnName()
222                         + "='"
223                         + oldValue
224                         + "'");
225                         
226         // commit and close
227
conn.commit();
228         stmt.close();
229     }
230 }
Popular Tags