KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > tools > upgrade > realm > RealmUpgrade


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 /*
25  * RealmUpgrade.java
26  *
27  * Created on September 3, 2003, 4:30 PM
28  */

29
30 package com.sun.enterprise.tools.upgrade.realm;
31
32 import com.sun.enterprise.tools.upgrade.transform.elements.*;
33 import java.io.File JavaDoc;
34 import java.io.IOException JavaDoc;
35
36 import javax.xml.parsers.DocumentBuilder JavaDoc;
37 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
38 import javax.xml.parsers.FactoryConfigurationError JavaDoc;
39 import javax.xml.parsers.ParserConfigurationException JavaDoc;
40
41 import org.xml.sax.SAXException JavaDoc;
42 import org.xml.sax.SAXParseException JavaDoc;
43
44 import java.io.File JavaDoc;
45 import java.io.FileReader JavaDoc;
46 import java.io.FileWriter JavaDoc;
47 import java.io.IOException JavaDoc;
48 import java.io.FileInputStream JavaDoc;
49 import java.io.FileOutputStream JavaDoc;
50 import java.io.BufferedReader JavaDoc;
51 import java.io.BufferedWriter JavaDoc;
52 import java.io.FileNotFoundException JavaDoc;
53 import java.nio.channels.FileChannel JavaDoc;
54 import java.nio.MappedByteBuffer JavaDoc;
55
56 import org.w3c.dom.Document JavaDoc;
57 import org.w3c.dom.DOMException JavaDoc;
58 import org.w3c.dom.Element JavaDoc;
59 import org.w3c.dom.Node JavaDoc;
60 import org.w3c.dom.NodeList JavaDoc;
61 import org.w3c.dom.NamedNodeMap JavaDoc;
62
63 import javax.xml.transform.Transformer JavaDoc;
64 import javax.xml.transform.TransformerFactory JavaDoc;
65 import javax.xml.transform.TransformerException JavaDoc;
66 import javax.xml.transform.TransformerConfigurationException JavaDoc;
67
68 import javax.xml.transform.dom.DOMSource JavaDoc;
69 import javax.xml.transform.stream.StreamResult JavaDoc;
70 import javax.xml.transform.OutputKeys JavaDoc;
71
72 import com.sun.enterprise.tools.upgrade.common.CommonInfoModel;
73 import com.sun.enterprise.tools.upgrade.common.UpgradeConstants;
74 import com.sun.enterprise.tools.upgrade.common.UpdateProgressManager;
75 import com.sun.enterprise.util.i18n.StringManager;
76 import com.sun.enterprise.util.RelativePathResolver;
77 import com.sun.enterprise.tools.upgrade.logging.*;
78 import java.util.logging.*;
79 import java.util.*;
80 import java.util.jar.*;
81 import java.util.zip.*;
82
83 /**
84  *
85  * @author Hans Hrasna
86  */

87 public class RealmUpgrade implements com.sun.enterprise.tools.upgrade.common.BaseModule {
88     
89     private String JavaDoc AS7_FILE_REALM = "com.iplanet.ias.security.auth.realm.file.FileRealm";
90     private String JavaDoc AS7_LDAP_REALM = "com.iplanet.ias.security.auth.realm.ldap.LDAPRealm";
91     private String JavaDoc AS7_CERTIFICATE_REALM = "com.iplanet.ias.security.auth.realm.certificate.CertificateRealm";
92     private String JavaDoc AS7_SOLARIS_REALM = "com.iplanet.ias.security.auth.realm.solaris.SolarisRealm";
93     private String JavaDoc AS8_FILE_REALM = "com.sun.enterprise.security.auth.realm.file.FileRealm";
94     private String JavaDoc AS8_LDAP_REALM = "com.sun.enterprise.security.auth.realm.ldap.LDAPRealm";
95     private String JavaDoc AS8_CERTIFICATE_REALM = "com.sun.enterprise.security.auth.realm.certificate.CertificateRealm";
96     private String JavaDoc AS8_SOLARIS_REALM = "com.sun.enterprise.security.auth.realm.solaris.SolarisRealm";
97     
98     private StringManager stringManager = StringManager.getManager("com.sun.enterprise.tools.upgrade.realm");
99     private Logger logger = CommonInfoModel.getDefaultLogger();
100     private CommonInfoModel commonInfo = null;
101     private Vector recoveryList = new Vector();
102     
103     /** Creates a new instance of RealmUpgrade */
104     public RealmUpgrade() {
105     }
106     
107     public boolean upgrade(CommonInfoModel commonInfoModel) {
108         logger.log(Level.INFO, stringManager.getString("upgrade.realm.startMessage"));
109         this.commonInfo = commonInfoModel;
110         DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
111         //factory.setValidating(true);
112
factory.setNamespaceAware(true);
113         if(commonInfo.getSourceDomainRootFlag()) {
114             factory.setAttribute("http://apache.org/xml/features/nonvalidating/load-external-dtd",Boolean.FALSE);
115         }
116         String JavaDoc realmname ="";
117         try {
118             DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
119             if(!commonInfo.getSourceVersion().equals(UpgradeConstants.VERSION_7X)){
120                 builder.setEntityResolver((org.xml.sax.helpers.DefaultHandler JavaDoc)Class.forName
121                         ("com.sun.enterprise.config.serverbeans.ServerValidationHandler").newInstance());
122             }
123             Document JavaDoc sourceDoc = builder.parse( new File JavaDoc(commonInfo.getSourceConfigXMLFile()));
124             // Document sourceDoc = builder.parse( new File(commonInfo.getSourceInstancePath() + File.separator + commonInfo.CONFIG + File.separator + "server.xml") );
125
NodeList JavaDoc nl = sourceDoc.getElementsByTagName("auth-realm");
126             for(int i =0; i < nl.getLength(); i++){
127                 Node JavaDoc node = nl.item(i);
128                 NamedNodeMap JavaDoc attributes = node.getAttributes();
129                 
130                 if(commonInfo.getSourceVersion().equals(UpgradeConstants.VERSION_7X)){
131                     //check for custom realm class
132
String JavaDoc classname = (attributes.getNamedItem("classname")).getNodeValue();
133                     if (!(classname.equals(AS7_FILE_REALM) || classname.equals(AS7_LDAP_REALM) ||
134                             classname.equals(AS7_CERTIFICATE_REALM) || classname.equals(AS7_SOLARIS_REALM))) {
135                         NodeList JavaDoc nlist = sourceDoc.getElementsByTagName("java-config");
136                         Node JavaDoc njava = nlist.item(0); // there is only one java-config element
137
NamedNodeMap JavaDoc java_attrs = njava.getAttributes();
138                         String JavaDoc classpath = (java_attrs.getNamedItem("server-classpath")).getNodeValue();
139                         migrateClass(classname, classpath);
140                     }
141                 } else if(commonInfo.getSourceVersion().equals(UpgradeConstants.VERSION_80) ||
142                         commonInfo.getSourceVersion().equals(UpgradeConstants.VERSION_81)){
143                     //check for custom realm class
144
String JavaDoc classname = (attributes.getNamedItem("classname")).getNodeValue();
145                     if (!(classname.equals(AS8_FILE_REALM) || classname.equals(AS8_LDAP_REALM) ||
146                             classname.equals(AS8_CERTIFICATE_REALM) || classname.equals(AS8_SOLARIS_REALM))) {
147                         NodeList JavaDoc nlist = sourceDoc.getElementsByTagName("java-config");
148                         Node JavaDoc njava = nlist.item(0); // there is only one java-config element
149
NamedNodeMap JavaDoc java_attrs = njava.getAttributes();
150                         String JavaDoc classpath = (java_attrs.getNamedItem("server-classpath")).getNodeValue();
151                         migrateClass(classname, classpath);
152                     }
153                 }
154                 //check for file realm
155
realmname = (attributes.getNamedItem("name")).getNodeValue();
156                 String JavaDoc classname = (attributes.getNamedItem("classname")).getNodeValue();
157                 if ( classname.equals(AS8_FILE_REALM) ) {
158                     NodeList JavaDoc props = node.getChildNodes();
159                     for( int j=0; j < props.getLength(); j++ ) {
160                         Node JavaDoc propnode = props.item(j);
161                         if(propnode.getNodeName().equals("property")) { //skip #text children
162
NamedNodeMap JavaDoc attrs = propnode.getAttributes();
163                             if (attrs != null && (attrs.getNamedItem("name").getNodeValue()).equals("file")) {
164                                 Node JavaDoc valueNode = attrs.getNamedItem("value");
165                                 System.setProperty("com.sun.aas.instanceRoot", commonInfo.getSourceInstancePath());
166                                 String JavaDoc rawSourceRealmPath = valueNode.getNodeValue();
167                                 String JavaDoc sourceRealmPath = RelativePathResolver.resolvePath(rawSourceRealmPath);
168                                 File JavaDoc sourceRealmFile = new File JavaDoc(sourceRealmPath);
169                                 String JavaDoc targetRealmPath = commonInfo.getDestinationDomainPath() + File.separator + commonInfo.CONFIG + File.separator + sourceRealmFile.getName();
170                                 File JavaDoc targetRealmFile = new File JavaDoc(targetRealmPath);
171                                 backup(targetRealmPath); // backup target keyfile
172
transferKeys(sourceRealmFile, targetRealmFile, builder);
173                             }
174                         }
175                     }
176                 }
177             }
178             
179         } catch (Exception JavaDoc ex){
180             logger.log(Level.SEVERE, stringManager.getString("upgrade.realm.migrationFailureMessage",ex.getMessage()),new Object JavaDoc [] {realmname,ex});
181             ex.printStackTrace();
182             UpdateProgressManager.getProgressManager().setContinueUpgrade(false);
183             return false;
184         }
185         return true;
186     }
187     
188     private void backup(String JavaDoc filePath) throws IOException JavaDoc {
189         String JavaDoc backupFilePath = filePath + ".bak";
190         copyFile(filePath, backupFilePath);
191         recoveryList.add(filePath);
192     }
193     
194     public void recovery(CommonInfoModel commonInfo) {
195         Enumeration e = recoveryList.elements();
196         while(e.hasMoreElements()){
197             String JavaDoc recoverPath = (String JavaDoc)e.nextElement();
198             String JavaDoc backupPath = recoverPath + ".bak";
199             try {
200                 copyFile(backupPath, recoverPath);
201                 new File JavaDoc(backupPath).delete();
202             } catch (IOException JavaDoc ioe) {
203                 logger.log(Level.SEVERE, stringManager.getString("upgrade.realm.recoveryFailureMessage",ioe.getMessage()),new Object JavaDoc[]{recoverPath,ioe});
204             }
205         }
206         
207     }
208     
209     
210     //find the named class file or jar that includes the named class file
211
//and copy it to the parallel corresponding AS8 directory then append the target
212
// server-classpath with the path to the copied jar or class file
213
private void migrateClass(String JavaDoc classname, String JavaDoc classpath) {
214         boolean found = false;
215         StringTokenizer st = new StringTokenizer(classpath, File.pathSeparator, false);
216         String JavaDoc [] fileList = new String JavaDoc [st.countTokens()];
217         for(int i=0;i<fileList.length;i++) {
218             fileList[i] = st.nextToken();
219         }
220         String JavaDoc targetDir = commonInfo.getDestinationDomainPath() + File.separator + "lib" + File.separator + "ext";
221         String JavaDoc file = classname;
222         for(int i =0;i<fileList.length;i++) {
223             String JavaDoc fileName = fileList[i];
224             if(fileName.endsWith(".jar")) {
225                 try {
226                     JarFile jarFile = new JarFile(fileName);
227                     Enumeration ee = jarFile.entries();
228                     while(ee.hasMoreElements()) {
229                         ZipEntry entry = (ZipEntry)ee.nextElement();
230                         String JavaDoc entryString = entry.toString();
231                         String JavaDoc className = entryString.replaceAll("/",".");
232                         if(className.equals(file)) {
233                             String JavaDoc target = targetDir + File.pathSeparatorChar + jarFile.getName();
234                             copyFile(fileName,target);
235                             updateDomainClassPath(jarFile.getName());
236                             found = true;
237                             break;
238                         }
239                     }
240                 } catch (IOException JavaDoc ioe) {
241                     (commonInfo.getDefaultLogger()).info(stringManager.getString("upgrade.realm.customRealmClassMessage")
242                     + fileName + stringManager.getString("upgrade.realm.IOExceptionMessage"));
243                 }
244             }
245             
246         }
247         if(!found) {
248             (commonInfo.getDefaultLogger()).info(stringManager.getString("upgrade.realm.customRealmClassMessage")
249             + classname + stringManager.getString("upgrade.realm.manuallyRelocatedMessage"));
250         }
251     }
252     
253     private void copyFile(String JavaDoc source, String JavaDoc target) throws IOException JavaDoc {
254         copyFile(source, target, false);
255     }
256     
257     public void copyFile(String JavaDoc source, String JavaDoc target, boolean append) throws IOException JavaDoc{
258         //copy the file
259
FileReader JavaDoc in = new FileReader JavaDoc(new File JavaDoc(source));
260         FileWriter JavaDoc out = new FileWriter JavaDoc(new File JavaDoc(target), append);
261         int c;
262         while ((c = in.read()) != -1) {
263             out.write(c);
264         }
265         in.close();
266         out.close();
267     }
268     
269     private void updateDomainClassPath(String JavaDoc fileName){
270         // The method expects the file is put under installRoot/lib/ext
271
logger.log(Level.INFO, stringManager.getString("upgrade.realm.updateDomainClassPathMessage"));
272         DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
273         //factory.setValidating(true);
274
factory.setNamespaceAware(true);
275         try {
276             DocumentBuilder JavaDoc builderDomainXml = factory.newDocumentBuilder();
277             builderDomainXml.setEntityResolver((org.xml.sax.helpers.DefaultHandler JavaDoc)Class.forName
278                     ("com.sun.enterprise.config.serverbeans.ServerValidationHandler").newInstance());
279             Document JavaDoc resultDoc = builderDomainXml.parse( new File JavaDoc(commonInfo.getTargetConfigXMLFile()) );
280             this.updateClassPathString(resultDoc,fileName);
281             
282             // write out the resultDoc to destination file.
283

284             // Use a Transformer for output
285
TransformerFactory JavaDoc tFactory = TransformerFactory.newInstance();
286             Transformer JavaDoc transformer = tFactory.newTransformer();
287             if (resultDoc.getDoctype() != null){
288                 String JavaDoc systemValue = resultDoc.getDoctype().getSystemId();
289                 transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, systemValue);
290                 String JavaDoc pubValue = resultDoc.getDoctype().getPublicId();
291                 transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pubValue);
292             }
293             DOMSource JavaDoc source = new DOMSource JavaDoc(resultDoc);
294             StreamResult JavaDoc result = new StreamResult JavaDoc(new FileOutputStream JavaDoc(commonInfo.getTargetConfigXMLFile()));
295             transformer.transform(source, result);
296         }catch (Exception JavaDoc ex){
297             logger.log(Level.SEVERE, stringManager.getString("upgrade.realm.updateDomainFailureMessage"),ex);
298         }
299     }
300     private void updateClassPathString(Document JavaDoc domainXML, String JavaDoc fileName){
301         // The method expects the file is put under installRoot/lib/ext
302
Element JavaDoc docEle = domainXML.getDocumentElement();
303         NodeList JavaDoc configList = docEle.getElementsByTagName("java-config");
304         // There should be only one java-config element.
305
Element JavaDoc javaConfElement = (Element JavaDoc)configList.item(0);
306         javaConfElement.setAttribute("server-classpath", javaConfElement.getAttribute("server-classpath")+"${path.separator}${com.sun.aas.installRoot}"+
307                 File.separator+"lib"+File.separator+"ext"+File.separator+fileName);
308     }
309     
310     public String JavaDoc getName() {
311         return stringManager.getString("upgrade.realm.moduleName");
312     }
313     
314     private void transferKeys(File JavaDoc sourceRealmFile, File JavaDoc targetRealmFile, DocumentBuilder JavaDoc builder) throws FileNotFoundException JavaDoc, IOException JavaDoc, SAXException JavaDoc {
315         Document JavaDoc sourceDoc = builder.parse( new File JavaDoc(commonInfo.getTargetConfigXMLFile()));
316         BufferedReader JavaDoc reader = new BufferedReader JavaDoc(new FileReader JavaDoc(sourceRealmFile));
317         BufferedWriter JavaDoc writer = new BufferedWriter JavaDoc(new FileWriter JavaDoc(targetRealmFile));
318         String JavaDoc entry;
319         while(reader.ready()) {
320             entry = reader.readLine();
321             if( entry.startsWith("admin") && !commonInfo.getSourceVersion().equals(UpgradeConstants.VERSION_81)) {
322                 // 8.1 holds the admin key in a seperate file for the admin-realm
323
// previous versions kept it in the default keyfile
324
//find the admin-realm file, back it up and replace with a keyfile containing the source admin key entry
325
NodeList JavaDoc nl = sourceDoc.getElementsByTagName("auth-realm");
326                 for(int i =0; i < nl.getLength(); i++){
327                     Node JavaDoc node = nl.item(i);
328                     NamedNodeMap JavaDoc attributes = node.getAttributes();
329                     String JavaDoc name = (attributes.getNamedItem("name")).getNodeValue();
330                     if (name.equals("admin-realm")) {
331                         //get the name of the keyfile for the admin-realm
332
NodeList JavaDoc props = node.getChildNodes();
333                         for( int j=0; j < props.getLength(); j++ ) {
334                             Node JavaDoc propnode = props.item(j);
335                             if(propnode.getNodeName().equals("property")) { //skip #text children
336
NamedNodeMap JavaDoc attrs = propnode.getAttributes();
337                                 if (attrs != null && (attrs.getNamedItem("name").getNodeValue()).equals("file")) {
338                                     Node JavaDoc valueNode = attrs.getNamedItem("value");
339                                     System.setProperty("com.sun.aas.instanceRoot", commonInfo.getDestinationDomainPath());
340                                     String JavaDoc rawSourceRealmPath = valueNode.getNodeValue();
341                                     String JavaDoc adminRealmPath = RelativePathResolver.resolvePath(rawSourceRealmPath);
342                                     File JavaDoc adminRealmFile = new File JavaDoc(adminRealmPath);
343                                     backup(adminRealmPath); // backup admin-realm keyfile
344
BufferedWriter JavaDoc adminRealmWriter = new BufferedWriter JavaDoc(new FileWriter JavaDoc(adminRealmFile));
345                                     adminRealmWriter.write(entry);
346                                     adminRealmWriter.newLine();
347                                     adminRealmWriter.write("# Domain User and Password - Do Not Delete Entry Above");
348                                     adminRealmWriter.close();
349                                 }
350                             }
351                         }
352                     }
353                 }
354             } else {
355                 if(!entry.startsWith("#")) { // don't transfer comments
356
writer.write(entry);
357                     writer.newLine();
358                 }
359             }
360         }
361         writer.close();
362         reader.close();
363     }
364 }
365
Popular Tags