KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > upgrade > JahiaUpgrade


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12
//
13
// JahiaUpgrade
14
// AK 28.02.2001 JahiaUpgrade creation.
15
//
16

17 package upgrade;
18
19 import java.io.BufferedInputStream JavaDoc;
20 import java.io.BufferedOutputStream JavaDoc;
21 import java.io.BufferedReader JavaDoc;
22 import java.io.File JavaDoc;
23 import java.io.FileInputStream JavaDoc;
24 import java.io.FileOutputStream JavaDoc;
25 import java.io.FileReader JavaDoc;
26 import java.io.FileWriter JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.InputStream JavaDoc;
29 import java.io.OutputStream JavaDoc;
30 import java.net.MalformedURLException JavaDoc;
31 import java.net.URL JavaDoc;
32 import java.net.URLClassLoader JavaDoc;
33 import java.sql.Connection JavaDoc;
34 import java.sql.Driver JavaDoc;
35 import java.sql.SQLException JavaDoc;
36 import java.sql.Statement JavaDoc;
37 import java.util.Enumeration JavaDoc;
38 import java.util.Properties JavaDoc;
39 import java.util.Vector JavaDoc;
40 import java.util.jar.JarFile JavaDoc;
41 import java.util.zip.ZipEntry JavaDoc;
42 import java.util.zip.ZipInputStream JavaDoc;
43
44
45
46 public class JahiaUpgrade
47 {
48     private static final String JavaDoc jahiaUpgradeClassFileName = "upgrade.jar";
49     private static String JavaDoc jahiaUpgradeClassFilePath = "";
50     private static String JavaDoc launchDirectoryPath = "";
51     private static String JavaDoc jahiaFilesPath = "";
52     private static String JavaDoc jahiaPropertiesFilePath = "";
53
54     private static String JavaDoc jahiaDBScript = "";
55     private static String JavaDoc jahiaDBDriver = "";
56     private static String JavaDoc jahiaDBUrl = "";
57     private static String JavaDoc jahiaDBUsername = "";
58     private static String JavaDoc jahiaDBPassword = "";
59
60     private static final String JavaDoc SCRIPT_SEPARATOR = ":";
61     private static final String JavaDoc SCRIPT_PREFIX = "release.";
62
63     private static String JavaDoc newReleaseNumber = "";
64     private static int jahiaInstalledRelease;
65
66     private static File JavaDoc jahiaUpgradeClass;
67     private static URLClassLoader JavaDoc upgradeClassLoader;
68
69
70
71     /**
72      * Main default method.
73      *
74      * @author AK
75      * @param args Command line arguments.
76      */

77     public static void main( String JavaDoc args[] )
78     {
79         // display the Jahia startup message...
80
startupConsole();
81
82         // check the environment where the user launch this class...
83
checkLaunchDirectory();
84
85         // create an another class loader...
86
createDifferentClassLoader();
87
88         // check installed jahia release...
89
checkInstalledRelease();
90
91         // extract this jar file and overwrite files...
92
extractJarFile();
93
94         // get database script runtime...
95
executeDatabaseRuntime();
96
97         // change jahia.properties file, add values, remove values, change values...
98
changeJahiaPropertiesFile();
99
100         // save new release number into Jahia properties file...
101
writeReleaseNumber();
102
103         // remove non necessary files like JahiaUpgrade.class, scripts and the manifest...
104
removeDummiesFiles();
105
106         // say goodbye... :o)
107
shutdownConsole();
108
109     } // end main
110

111
112
113     /**
114      * Check if the user is in the good directory to launch JahiaUpgrade
115      * and if he use "jahia -jar upgrade.jar".
116      *
117      * @author AK
118      */

119     private static void checkLaunchDirectory()
120     {
121         launchDirectoryPath = System.getProperties().getProperty("user.dir");
122         jahiaFilesPath = launchDirectoryPath + File.separator + "WEB-INF" + File.separator + "jahiafiles";
123         jahiaUpgradeClassFilePath = launchDirectoryPath + File.separator + jahiaUpgradeClassFileName;
124
125         jahiaUpgradeClass = new File JavaDoc(jahiaUpgradeClassFilePath);
126         File JavaDoc jahiaFilesDirectory = new File JavaDoc(jahiaFilesPath);
127
128         // check if the jar file is in your current directory...
129
if(!jahiaUpgradeClass.exists()) {
130             toConsole(jahiaUpgradeClassFileName + " not found.");
131             toConsole("You must launch JahiaUpgrade using \"java -jar upgrade.jar\".");
132             System.exit(0);
133         }
134
135         // check if the jahia files directory exists...
136
if(!jahiaFilesDirectory.exists()) {
137             toConsole("You must be in the Jahia root to launch JahiaUpgrade.");
138             System.exit(0);
139         }
140     } // end checkLaunchDirectory
141

142
143
144     /**
145      * Create an another class loader using jar files in lib directory.
146      *
147      * @author AK
148      */

149     private static void createDifferentClassLoader()
150     {
151         String JavaDoc jahiaLibDirectoryPath = launchDirectoryPath + File.separator + "WEB-INF" + File.separator + "lib";
152
153         File JavaDoc jahiaLibDirectory = new File JavaDoc(jahiaLibDirectoryPath);
154         File JavaDoc[] filesInThisDirectory = jahiaLibDirectory.listFiles();
155
156         URL JavaDoc[] urlsFromJarFiles = new URL JavaDoc[filesInThisDirectory.length];
157
158         // list the content of this directory... filter *.jar
159
for(int i=0; i<filesInThisDirectory.length; i++) {
160             String JavaDoc fileName = filesInThisDirectory[i].getPath();
161             try {
162                 if(fileName.substring(fileName.length()-4, fileName.length()).equals(".jar")) {
163                     File JavaDoc thisJarFile = new File JavaDoc(fileName);
164                     URL JavaDoc thisJarFileURL = thisJarFile.toURL();
165                     urlsFromJarFiles[i] = thisJarFileURL;
166                 }
167             } catch (IndexOutOfBoundsException JavaDoc ioobe) {
168             } catch (MalformedURLException JavaDoc mue) {
169             }
170         }
171
172         upgradeClassLoader = new URLClassLoader JavaDoc( urlsFromJarFiles );
173     } // end setClassPath
174

175
176
177     /**
178      * Check which release of Jahia is currently installed.
179      *
180      * @author AK
181      */

182     private static void checkInstalledRelease()
183     {
184         toConsole("Checking current installed Jahia release.");
185
186         // try to load the current installed release number...
187
try
188         {
189             jahiaPropertiesFilePath = jahiaFilesPath + File.separator + "config" + File.separator + "jahia.properties";
190
191             Properties JavaDoc jahiaPropertiesObject = new Properties JavaDoc();
192             FileInputStream JavaDoc inputStream = new FileInputStream JavaDoc(jahiaPropertiesFilePath);
193
194             jahiaPropertiesObject.load(inputStream);
195             inputStream.close();
196
197             // get properties values...
198
String JavaDoc jahiaReleaseNumber = jahiaPropertiesObject.getProperty("release");
199             jahiaDBScript = jahiaPropertiesObject.getProperty("db_script");
200             jahiaDBDriver = jahiaPropertiesObject.getProperty("db_driver");
201             jahiaDBUrl = jahiaPropertiesObject.getProperty("db_url");
202             jahiaDBUsername = jahiaPropertiesObject.getProperty("db_username");
203             jahiaDBPassword = jahiaPropertiesObject.getProperty("db_password");
204
205             if((jahiaReleaseNumber == null) || (jahiaDBScript == null) || (jahiaDBDriver == null) || (jahiaDBUrl == null) || (jahiaDBUsername == null) || (jahiaDBPassword == null))
206             {
207                 //System.out.println("\n");
208
toConsole("Jahia properties file not found or corrupt.");
209                 toConsole("Have you completed the Jahia installation before?");
210                 System.exit(0);
211             }
212
213             // convert type of values...
214
jahiaInstalledRelease = Integer.parseInt(jahiaReleaseNumber);
215
216         } catch (IOException JavaDoc ioe) {
217             //System.out.println("\n");
218
toConsole("Jahia properties file not found or corrupt.");
219             toConsole("Have you completed the Jahia installation before?");
220             System.exit(0);
221         }
222
223         toConsole("Upgrading Jahia from release " + jahiaInstalledRelease + "...\n");
224     } // end checkInstalledRelease
225

226
227
228     /**
229      * Extract this jar file into the jahiafiles/upgrade directory.
230      * -> use NK's unzip() method.
231      *
232      * @author AK
233      */

234     private static void extractJarFile()
235     {
236         try {
237             toConsole("Decompressing upgrade files... please wait.");
238
239             JarFile JavaDoc jahiaUpgradeJarFile = new JarFile JavaDoc(jahiaUpgradeClass);
240             FileInputStream JavaDoc fileStream = new FileInputStream JavaDoc(jahiaUpgradeClassFilePath);
241             BufferedInputStream JavaDoc bufferedStream = new BufferedInputStream JavaDoc(fileStream);
242             ZipInputStream JavaDoc zipStream = new ZipInputStream JavaDoc(bufferedStream);
243             ZipEntry JavaDoc zipEntry;
244
245             try
246             {
247                 while((zipEntry = zipStream.getNextEntry()) != null)
248                 {
249                     File JavaDoc fileOutput = new File JavaDoc( launchDirectoryPath + File.separator + generatePathFile(zipEntry.getName()) );
250                     if(zipEntry.isDirectory()) {
251                         fileOutput.mkdirs();
252                     } else {
253                         File JavaDoc parent = new File JavaDoc(fileOutput.getParent());
254                         parent.mkdirs();
255
256                         FileOutputStream JavaDoc outputStream = new FileOutputStream JavaDoc(fileOutput);
257                         copyStream(zipStream, outputStream);
258                     }
259                     zipStream.closeEntry();
260                 }
261             } finally {
262                 fileStream.close();
263                 zipStream.close();
264                 bufferedStream.close();
265             }
266
267             toConsole("Decompression is done.\n");
268         } catch (IOException JavaDoc ioe) {
269         }
270     } // end extractJarFile
271

272
273
274     /**
275      * Remove non necessary files like JahiaUpgrade.class and the manifest.
276      * Remove only files requested between the current release and this release.
277      *
278      * @author AK
279      */

280     private static void removeDummiesFiles()
281     {
282         Enumeration JavaDoc eachLines = readLines(launchDirectoryPath + File.separator + "upgrade" + File.separator + "remove_files.upgrade");
283
284         while(eachLines.hasMoreElements()) {
285             try
286             {
287                 String JavaDoc fileName = (String JavaDoc) eachLines.nextElement();
288                 if(fileName.trim().length() > 0)
289                 {
290                     boolean doOperation = false;
291                     int separatorPosition = fileName.indexOf(SCRIPT_SEPARATOR);
292                     String JavaDoc releaseNumber = fileName.substring(SCRIPT_PREFIX.length(), separatorPosition).trim();
293     
294                     if(releaseNumber.equals("all")) {
295                         doOperation = true;
296                     } else {
297                         try {
298                             int releaseNumberInt = Integer.parseInt(releaseNumber);
299                             if(releaseNumberInt > jahiaInstalledRelease) {
300                                 doOperation = true;
301                             }
302                         } catch (NumberFormatException JavaDoc nfe) {
303                         }
304                     }
305     
306                     if(doOperation) {
307                         String JavaDoc completeFileName = launchDirectoryPath + File.separator + fileName.substring(separatorPosition+1, fileName.length()).trim();
308                         File JavaDoc theFile = new File JavaDoc( completeFileName );
309                         deleteFile( theFile );
310                     }
311                 }
312             } catch (IndexOutOfBoundsException JavaDoc ioobe) {
313             }
314         }
315     } // end removeDummiesFiles
316

317
318
319     /**
320      * Get database script runtime and execute the runtime.
321      *
322      * @author AK
323      */

324     private static void executeDatabaseRuntime()
325     {
326         Enumeration JavaDoc eachLines = readLines(launchDirectoryPath + File.separator + "upgrade" + File.separator + jahiaDBScript);
327
328         try
329         {
330             toConsole("Upgrading your database... please wait.");
331             
332             Class JavaDoc dbDriverClass = Class.forName( jahiaDBDriver, false, upgradeClassLoader );
333             Driver JavaDoc dbDriver = (Driver JavaDoc) dbDriverClass.newInstance();
334
335             Properties JavaDoc dbProperties = new Properties JavaDoc();
336             dbProperties.setProperty("user", jahiaDBUsername);
337             dbProperties.setProperty("password", jahiaDBPassword);
338
339             Connection JavaDoc dbConnection = dbDriver.connect( jahiaDBUrl, dbProperties );
340             Statement JavaDoc dbStatement = dbConnection.createStatement();
341
342             while(eachLines.hasMoreElements()) {
343                 try
344                 {
345                     String JavaDoc sqlCode = (String JavaDoc) eachLines.nextElement();
346                     if(sqlCode.trim().length() > 0)
347                     {
348                         int separatorPosition = sqlCode.indexOf(SCRIPT_SEPARATOR);
349                         String JavaDoc releaseNumber = sqlCode.substring(SCRIPT_PREFIX.length(), separatorPosition).trim();
350     
351                         try {
352                             int releaseNumberInt = Integer.parseInt(releaseNumber);
353                             if(releaseNumberInt > jahiaInstalledRelease) {
354                                 try {
355                                     String JavaDoc completeSqlCode = sqlCode.substring(separatorPosition+1, sqlCode.length()).trim();
356                                     if((completeSqlCode.substring(0,6).equals("CREATE")) || (completeSqlCode.substring(0,4).equals("DROP"))) {
357                                         dbStatement.executeQuery( completeSqlCode );
358                                     } else {
359                                         dbStatement.executeUpdate( completeSqlCode );
360                                     }
361                                 } catch (SQLException JavaDoc sqle) {
362                                 } catch (IndexOutOfBoundsException JavaDoc ioobe) {
363                                 }
364                             }
365                         } catch (NumberFormatException JavaDoc nfe) {
366                         }
367                     }
368                 } catch (IndexOutOfBoundsException JavaDoc ioobe) {
369                 }
370             }
371
372             dbStatement.close();
373             toConsole("Upgrade database is done.\n");
374
375         } catch (ClassNotFoundException JavaDoc cnfe) {
376             //System.out.println("\n");
377
toConsole(jahiaDBDriver + " driver class not found.");
378         } catch (SQLException JavaDoc sqle) {
379             //System.out.println("\n");
380
toConsole("Can't connect to database or connection refused.");
381             toConsole("Jahia must be configured if you want to make an upgrade.");
382         } catch (Throwable JavaDoc t) {
383             t.printStackTrace();
384         }
385     } // end executeDatabaseRuntime
386

387
388
389     /**
390      * Changes properties (add, modify, delete) in jahia.properties file.
391      *
392      * @author AK
393      */

394     private static void changeJahiaPropertiesFile()
395     {
396         Enumeration JavaDoc eachLines = readLines(launchDirectoryPath + File.separator + "upgrade" + File.separator + "jahia_properties.upgrade");
397
398         while(eachLines.hasMoreElements()) {
399             try
400             {
401                 String JavaDoc property = (String JavaDoc) eachLines.nextElement();
402                 if(property.trim().length() > 0)
403                 {
404                     int separatorPosition = property.indexOf(SCRIPT_SEPARATOR);
405                     String JavaDoc releaseNumber = property.substring(SCRIPT_PREFIX.length(), separatorPosition).trim();
406
407                     try {
408                         int releaseNumberInt = Integer.parseInt(releaseNumber);
409                         if(releaseNumberInt > jahiaInstalledRelease) {
410                             String JavaDoc propertyName = property.substring(separatorPosition+1, property.indexOf("=")).trim();
411                             String JavaDoc propvalue = property.substring(property.indexOf("=")+1, property.length()).trim();
412
413                             //System.out.println("propertyName = [" + propertyName + "]");
414
//System.out.println("propvalue = [" + propvalue + "]");
415
}
416                     } catch (NumberFormatException JavaDoc nfe) {
417                     }
418                 }
419             } catch (IndexOutOfBoundsException JavaDoc ioobe) {
420             }
421         }
422     } // end changeJahiaPropertiesFile
423

424
425
426     /**
427      * Get and save new release number into Jahia properties file..
428      *
429      * @author AK
430      */

431     private static void writeReleaseNumber()
432     {
433         try
434         {
435             String JavaDoc releaseNumberFilePath = launchDirectoryPath + File.separator + "upgrade" + File.separator + "release.upgrade";
436             Properties JavaDoc releaseNumberProperties = new Properties JavaDoc();
437             FileInputStream JavaDoc inputStream = new FileInputStream JavaDoc(releaseNumberFilePath);
438
439             releaseNumberProperties.load(inputStream);
440             inputStream.close();
441
442             // get release.upgrade value...
443
newReleaseNumber = releaseNumberProperties.getProperty("release");
444
445             // write new release number into jahia.properties file...
446
updatepropvalue( "release", newReleaseNumber, jahiaPropertiesFilePath );
447
448         } catch (IOException JavaDoc ioe) {
449         }
450     } // end writeReleaseNumber
451

452
453
454     /**
455      * Read a text file, line after line, and create an Enumeration.
456      *
457      * @author AK
458      * @param filePath String containing the path to the file you want read.
459      *
460      * @return Enumeration containing each separated line.
461      */

462     private static Enumeration JavaDoc readLines( String JavaDoc filePath )
463     {
464         Vector JavaDoc allLines = new Vector JavaDoc();
465
466         try
467         {
468             BufferedReader JavaDoc buffered = new BufferedReader JavaDoc( new FileReader JavaDoc(filePath) );
469             String JavaDoc buffer = "";
470     
471             while((buffer = buffered.readLine()) != null) {
472                 if(buffer.trim().length() > 0) {
473                     allLines.add(buffer);
474                 }
475             }
476             buffered.close();
477         } catch (IOException JavaDoc ioe) {
478         }
479
480         return allLines.elements();
481     } // end readLine
482

483
484
485     /**
486      * Generates a path file for a gived entry name. Parses "/" and
487      * replaces them with File.separator.
488      * -> use unknown's genPathFile() method.
489      *
490      * @author AK
491      */

492     private static String JavaDoc generatePathFile( String JavaDoc entryName )
493     {
494         StringBuffer JavaDoc thePath = new StringBuffer JavaDoc(entryName.length());
495         for(int i=0; i<entryName.length(); i++) {
496             if(entryName.charAt(i) == '/') {
497                 thePath.append(File.separator);
498             } else {
499                 thePath.append(entryName.charAt(i));
500             }
501         }
502         return(thePath.toString());
503     }
504
505
506
507     /**
508      * Copy an InputStream to an OutPutStream
509      *
510      * @author AK
511      */

512     private static void copyStream( InputStream JavaDoc inputStream,
513                                     OutputStream JavaDoc outputStream )
514     throws IOException JavaDoc
515     {
516         int bufferRead;
517         int bufferSize = 1024;
518         byte[] writeBuffer = new byte[bufferSize];
519
520         BufferedOutputStream JavaDoc bufferedStream = new BufferedOutputStream JavaDoc(outputStream, bufferSize);
521         while((bufferRead = inputStream.read(writeBuffer)) != -1)
522
523         bufferedStream.write(writeBuffer, 0, bufferRead);
524         bufferedStream.flush();
525         bufferedStream.close();
526
527         outputStream.flush();
528         outputStream.close();
529     } // end copyStream
530

531
532
533     /**
534      * Delete a file or directory (and all its content).
535      * -> use NK's deleteFile() method.
536      *
537      * @author AK
538      */

539     private static void deleteFile( File JavaDoc theFile )
540     {
541         if(theFile.isDirectory())
542         {
543             File JavaDoc[] filesInThisDirectory = theFile.listFiles();
544             for(int i=0; i<filesInThisDirectory.length; i++) {
545                 if(filesInThisDirectory[i].isFile()) {
546                     filesInThisDirectory[i].delete();
547                 } else {
548                     deleteFile(filesInThisDirectory[i]);
549                 }
550             }
551         }
552         theFile.delete();
553     } // end deleteFile
554

555
556
557     /**
558      * Update a property's value in a properties file
559      * -> use NK's updatepropvalue() method.
560      *
561      * @author AK
562      * @param propertyName Property name
563      * @param propvalue Property value
564      * @param path Full path to the properties file
565      */

566     private static void updatepropvalue( String JavaDoc propertyName,
567                                              String JavaDoc propvalue,
568                                              String JavaDoc path )
569     {
570         Vector JavaDoc bufferVector = new Vector JavaDoc();
571         String JavaDoc lineReaded = null;
572         int position = 0;
573         boolean lineFound = false;
574
575         try
576         {
577             // parse the file...
578
BufferedReader JavaDoc buffered = new BufferedReader JavaDoc( new FileReader JavaDoc(path) );
579             while((lineReaded = buffered.readLine()) != null) {
580                 if(lineReaded.indexOf(propertyName) >= 0) {
581                     position = lineReaded.lastIndexOf("=");
582                     if(position >= 0) {
583                         bufferVector.add( lineReaded.substring(0,position+1) + " " + propvalue );
584                         lineFound = true;
585                     }
586                 } else {
587                     bufferVector.add(lineReaded);
588                 }
589             }
590             buffered.close();
591
592             // add property if it don't exists before...
593
if(!lineFound)
594             {
595                 bufferVector.add( propertyName + " = " + propvalue );
596             }
597
598             // rewrite the file...
599
File JavaDoc thisFile = new File JavaDoc(path);
600             FileWriter JavaDoc fileWriter = new FileWriter JavaDoc( thisFile );
601             StringBuffer JavaDoc outputBuffer = new StringBuffer JavaDoc();
602
603             for(int i=0; i < bufferVector.size(); i++) {
604                 outputBuffer.append((String JavaDoc) bufferVector.get(i));
605             }
606
607             fileWriter.write( outputBuffer.toString() );
608             fileWriter.close();
609         } catch (java.io.IOException JavaDoc ioe) {
610         }
611     } // end updatepropvalue
612

613
614
615     /**
616      * Format the message and output in the console.
617      *
618      * @author AK
619      * @param msg Message to display in the console.
620      */

621     private static void toConsole( String JavaDoc msg )
622     {
623         //System.out.println("upgrade: " + msg);
624
} // end toConsole
625

626
627
628     /**
629      * Display a Jahia message to indicate the start of JahiaUpgrade :o)
630      *
631      * @author AK
632      */

633     private static void startupConsole()
634     {
635         StringBuffer JavaDoc msg = new StringBuffer JavaDoc("\n\n\n");
636         msg.append(" ____.\n");
637         msg.append(" __/\\ ______| |__/\\. _______\n");
638         msg.append(" __ .____| | \\ | +----+ \\\n");
639         msg.append(" _______| /--| | | - \\ _ | : - \\_________\n");
640         msg.append(" \\\\______: :---| : : | : | \\________>\n");
641         msg.append(" |__\\---\\_____________:______: :____|____:_____\\\n");
642         msg.append(" /_____|\n");
643         msg.append("\n");
644         msg.append(" . . . j a h i a u p g r a d e . . .\n");
645         msg.append("\n\n");
646         msg.append(" Copyright 2002 - Jahia Ltd http://www.jahia.org - all rights reserved\n");
647         msg.append("\n\n");
648         System.out.println(msg.toString());
649     } // end startupConsole
650

651
652
653     /**
654      * Say goodbye in the console :o)
655      *
656      * @author AK
657      */

658     private static void shutdownConsole()
659     {
660         //System.out.println("\nupgrade: Upgrade is done! You now have the release " + newReleaseNumber + ".");
661
}
662
663
664 } // end JahiaUpgrade
Popular Tags