-
Notifications
You must be signed in to change notification settings - Fork 460
/
UpdateAgent.java
823 lines (688 loc) · 34.1 KB
/
UpdateAgent.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
package com.dotcms.autoupdater;
import org.apache.commons.cli.*;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.*;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class UpdateAgent {
public static String MANIFEST_PROPERTY_AGENT_VERSION = "Agent-Version";
//private static String MANIFEST_PROPERTY_RELEASE_VERSION = "Release-Version";
public static Logger logger;
public static boolean isDebug = false;
public static String logFile;
private String url;
private String homeProjectPath;
public static String FOLDER_HOME_DOTSERVER = "dotserver";
public static String FOLDER_HOME_UPDATER = "autoupdater";
public static String FOLDER_HOME_BACK_UP = "backup";
//private String backupFile;
private String proxy;
private String proxyUser;
private String proxyPass;
private boolean allowTestingBuilds;
private String newMinor;
private String newVersion;
private String MESSAGES_CONFIRM_TEXT = Messages.getString( "UpdateAgent.text.confirm" );
private String MESSAGES_HELP_TEXT = Messages.getString( "UpdateAgent.text.help" );
public static void main ( String[] args ) {
new UpdateAgent().run( args );
}
public void run ( String[] args ) {
UpdateOptions updateOptions = new UpdateOptions();
Options options = updateOptions.getOptions();
// create the parser
CommandLineParser parser = new GnuParser();
CommandLine line;
try {
// parse the command line arguments
line = parser.parse( options, args );
} catch ( MissingOptionException e ) {
System.err.println( Messages.getString( "UpdateAgent.error.command.missing.options" ) );
List<String> list = e.getMissingOptions();
for ( String item : list ) {
System.err.println( item );
}
return;
} catch ( ParseException e ) {
System.err.println( Messages.getString( "UpdateAgent.error.command.parsing" ) + e.getMessage() );
return;
}
try {
//Initializing properties
configureLogger( line );
//Command line parameters
allowTestingBuilds = Boolean.parseBoolean( line.getOptionValue( UpdateOptions.ALLOW_TESTING_BUILDS ) );
proxy = line.getOptionValue( UpdateOptions.PROXY );
proxyUser = line.getOptionValue( UpdateOptions.PROXY_USER );
proxyPass = line.getOptionValue( UpdateOptions.PROXY_PASS );
url = line.getOptionValue( UpdateOptions.URL, updateOptions.getDefault( "update.url", "" ) );
homeProjectPath = line.getOptionValue( UpdateOptions.HOME, System.getProperty( "user.dir" ) );
updateOptions.setHomeFolder( homeProjectPath );
updateOptions.setUpdateFilesFolder( homeProjectPath + File.separator + FOLDER_HOME_UPDATER + File.separator + "updates" );
//Verify if we need to print the help documentation
if ( line.hasOption( UpdateOptions.HELP ) || args.length == 0 ) {
UpdateUtil.printHelp( options, MESSAGES_HELP_TEXT );
return;
}
logger.info( Messages.getString( "UpdateAgent.text.dotcms.home" ) + getHomeProjectPath() );
//Some validations...
checkHome( getHomeProjectPath() + File.separator + FOLDER_HOME_DOTSERVER );
checkRequisites( getHomeProjectPath() + File.separator + FOLDER_HOME_DOTSERVER );
newMinor = "";
newVersion = "";
String version = getVersion();
String minor = UpdateUtil.getBuildVersion( getJarProps() );
/*SimpleDateFormat sdf = new SimpleDateFormat( "yyyMMdd_HHmm" );
backupFile = line.getOptionValue( UpdateOptions.BACKUP, "update_backup_b" + minor + "_" + sdf.format( new Date() ) + ".zip" );
if ( !backupFile.endsWith( ".zip" ) ) {
backupFile += ".zip";
}*/
String agentVersion = UpdateUtil.getManifestValue( MANIFEST_PROPERTY_AGENT_VERSION );
logger.debug( Messages.getString( "UpdateAgent.text.autoupdater.version" ) + agentVersion );
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++VERIFY FOR NEW VERSIONS OF THE AUTOUPDATER++++++++++++++++++++
if ( !line.hasOption( UpdateOptions.NO_UPDATE ) ) {
// Check to see if new version of the updater exists
File newAgent = downloadAgent( version );
if ( newAgent != null ) {
// Exit, We found an update for the autoupdater, the auto updater script will restart the process after the update of the autoupdater.jar
logger.info( Messages.getString( "UpdateAgent.text.new.autoupdater" ) );
System.exit( 0 );
}
}
File updateFile = null;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//Verify if the user specified a version to update to
if ( line.hasOption( UpdateOptions.SPECIFIC_VERSION ) ) {
if ( minor != null ) {
logger.info( Messages.getString( "UpdateAgent.text.your.version" ) + version + " / " + minor + " Version " + line.getOptionValue( UpdateOptions.SPECIFIC_VERSION ) );
} else {
logger.info( Messages.getString( "UpdateAgent.text.your.version" ) + version + " Version " + line.getOptionValue( UpdateOptions.SPECIFIC_VERSION ) );
}
Map<String, String> map = new HashMap<String, String>();
map.put( "version", version );
//map.put( "buildNumber", minor );
map.put( "specificVersion", line.getOptionValue( UpdateOptions.SPECIFIC_VERSION ) );
if ( allowTestingBuilds ) {
map.put( "allowTestingBuilds", "true" );
}
//Search for the update version
updateFile = searchForVersion( map );
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//Verify if the user provided an update file
else if ( line.hasOption( UpdateOptions.FILE ) ) {
if ( minor != null ) {
logger.info( Messages.getString( "UpdateAgent.text.your.version" ) + version + " / " + minor + " file " + line.getOptionValue( UpdateOptions.FILE ) );
} else {
logger.info( Messages.getString( "UpdateAgent.text.your.version" ) + version + " file " + line.getOptionValue( UpdateOptions.FILE ) );
}
// Use user provided file
updateFile = new File( getHomeProjectPath() + File.separator + FOLDER_HOME_UPDATER + File.separator + "updates" + File.separator + line.getOptionValue( UpdateOptions.FILE ) );
if ( !updateFile.exists() ) {
throw new UpdateException( Messages.getString( "UpdateAgent.error.file.not.found" ), UpdateException.ERROR );
}
// Get the version locally
String fileMajor = UpdateUtil.getFileMayorVersion( updateFile );
String fileMinor = UpdateUtil.getFileMinorVersion( updateFile );
if ( fileMinor != null ) {
logger.info( Messages.getString( "UpdateAgent.text.file.version" ) + fileMajor + " / " + fileMinor );
newMinor = fileMinor;
} else {
logger.info( Messages.getString( "UpdateAgent.text.file.version" ) + fileMajor );
}
newVersion = fileMajor;
logger.info( " " );
} else {
// Download update file
if ( minor != null ) {
logger.info( Messages.getString( "UpdateAgent.text.your.version" ) + version + " / " + minor );
} else {
logger.info( Messages.getString( "UpdateAgent.text.your.version" ) + version );
}
if ( updateFile == null ) {
Map<String, String> map = new HashMap<String, String>();
map.put( "version", version );
//map.put( "buildNumber", minor );
if ( allowTestingBuilds ) {
map.put( "allowTestingBuilds", "true" );
}
//Search for the update version
updateFile = searchForVersion( map );
}
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//Ok, now we have an update file to use...
if ( updateFile != null && updateFile.exists() ) {
FileUpdater fileUpdater = new FileUpdater( updateFile, getHomeProjectPath(), null, line.hasOption( UpdateOptions.DRY_RUN ) );
// Pre-process the update, prepare everything and make back-ups
fileUpdater.preUpdate();
// Ask for confirmation
UpdateUtil.confirm( line, MESSAGES_CONFIRM_TEXT );
// Execute the update, unziping the downloaded file on the .dotserver/ directory and applying the required changes in there
fileUpdater.doUpdate();
//Clean up...
fileUpdater.postUpdate();
if ( newMinor != null && !newMinor.equals( "" ) ) {
throw new UpdateException( Messages.getString( "UpdateAgent.text.dotcms.dotcms.updated" ) + newVersion + " / " + newMinor, UpdateException.SUCCESS );
} else {
throw new UpdateException( Messages.getString( "UpdateAgent.text.dotcms.dotcms.updated" ) + newVersion, UpdateException.SUCCESS );
}
}
} catch ( IOException e ) {
//Just in case it was left running
ActivityIndicator.endIndicator();
if ( isDebug ) {
logger.debug( "IOException: ", e );
} else {
logger.error( Messages.getString( "UpdateAgent.error.downloading" ) + e.getMessage() );
}
logger.info( " " );
} catch ( UpdateException e ) {
//Just in case it was left running
ActivityIndicator.endIndicator();
if ( !e.getType().equals( UpdateException.CANCEL ) ) {
if ( e.getType().equals( UpdateException.ERROR ) ) {
if ( isDebug ) {
logger.debug( "UpdateException: ", e );
} else {
logger.error( Messages.getString( "UpdateAgent.error.updating" ) + e.getMessage() );
}
} else {
logger.info( e.getMessage() );
}
}
logger.info( " " );
}
}
/**
* Search for an update version
*
* @param map
* @throws UpdateException
* @throws IOException
*/
private File searchForVersion ( Map<String, String> map ) throws UpdateException, IOException {
PostMethod method = doGet( url, map );
int ret = method.getStatusCode();
if ( ret == 200 ) {
// Get the version of the jar.
try {
newMinor = method.getResponseHeader( "Minor-Version" ).getValue();
if ( newMinor.trim().length() > 0 ) {
String[] minorArr = newMinor.split( "_" );
if ( minorArr.length > 1 ) {
logger.info( Messages.getString( "UpdateAgent.text.latest.version" ) + minorArr[0] + " / " + minorArr[1] );
} else {
logger.info( Messages.getString( "UpdateAgent.text.latest.version" ) + minorArr[0] );
}
newVersion = minorArr[0];
logger.info( " " );
} else {
throw new Exception();
}
} catch ( Exception e ) {
logger.debug( Messages.getString( "UpdateAgent.error.no.minor.version" ), e );
throw new UpdateException( Messages.getString( "UpdateAgent.error.no.minor.version" ), UpdateException.ERROR );
}
String fileName = "update_" + newVersion + ".zip";
File updateFile = new File( getHomeProjectPath() + File.separator + FOLDER_HOME_UPDATER + File.separator + "updates" + File.separator + fileName );
if ( updateFile.exists() ) {
//check md5 of file
String MD5 = null;
boolean hasMD5 = false;
if ( method.getResponseHeader( "Content-MD5" ) != null && !method.getResponseHeader( "Content-MD5" ).equals( "" ) && !method.getResponseHeader( "Content-MD5" ).equals( "null" ) ) {
MD5 = method.getResponseHeader( "Content-MD5" ).getValue();
if ( !MD5.equals( "" ) ) {
hasMD5 = true;
}
}
if ( hasMD5 ) {
String dlMD5 = UpdateUtil.getMD5( updateFile );
logger.debug( Messages.getString( "UpdateAgent.debug.server.md5" ) + MD5 );
logger.debug( Messages.getString( "UpdateAgent.debug.file.md5" ) + dlMD5 );
if ( MD5 == null || MD5.length() == 0 || !dlMD5.equals( MD5 ) ) {
logger.fatal( Messages.getString( "UpdateAgent.error.md5.failed" ) );
throw new UpdateException( Messages.getString( "UpdateAgent.error.file.exists" ) + fileName, UpdateException.ERROR );
}
} else {
// file verified, let's use it
logger.info( updateFile.getName() + ": " + Messages.getString( "UpdateAgent.text.md5.verified" ) );
}
} else {
//Create the updates directory
if ( !updateFile.getParentFile().exists() ) {
updateFile.getParentFile().mkdirs();
}
// Download the update content, the update servlet will provide an url for the update file
String downloadUrl = method.getResponseHeader( "Download-Link" ).getValue();
download( downloadUrl, updateFile, method );
}
return updateFile;
} else {
switch ( ret ) {
case 204:
throw new UpdateException( Messages.getString( "UpdateAgent.text.dotcms.uptodate" ), UpdateException.SUCCESS );
case 401:
throw new UpdateException( Messages.getString( "UpdateAgent.error.login.failed" ), UpdateException.ERROR );
case 403:
throw new UpdateException( Messages.getString( "UpdateAgent.error.login.failed" ), UpdateException.ERROR );
default:
throw new UpdateException( Messages.getString( "UpdateAgent.error.unexpected.http.code" ) + ret, UpdateException.ERROR );
}
}
}
/**
* Will configure the logging for this tool
*
* @param line
*/
private void configureLogger ( CommandLine line ) {
Logger logRoot = Logger.getRootLogger();
//File appender get all logs always
//Console one get all on debug
// ...gets errors on quiet
// ...on normal it gets info from UpdateAgent only.
ConsoleAppender app = new ConsoleAppender( new PatternLayout( "%m%n" ) );
FileAppender logApp;
try {
SimpleDateFormat sdf = new SimpleDateFormat( "yyyMMdd_HHmm" );
logFile = "update_" + sdf.format( new Date() ) + ".log";
if ( line.hasOption( UpdateOptions.LOG ) ) {
logFile = line.getOptionValue( UpdateOptions.LOG );
}
logApp = new FileAppender( new PatternLayout( "%d %m%n" ), logFile );
logRoot.addAppender( logApp );
logApp.setThreshold( Level.DEBUG );
} catch ( IOException e ) {
System.err.println( Messages.getString( "UpdateAgent.error.cant.create.log" ) + e.getMessage() );
e.printStackTrace();
System.err.println( Messages.getString( "UpdateAgent.error.cant.create.log.will.continue" ) );
}
Logger l = Logger.getLogger( UpdateAgent.class );
l.setLevel( Level.DEBUG );
logRoot.setLevel( Level.INFO );
if ( line.hasOption( UpdateOptions.VERBOSE ) ) {
app.setThreshold( Level.DEBUG );
logRoot.addAppender( app );
isDebug = true;
} else {
l.addAppender( app );
if ( line.hasOption( UpdateOptions.QUIET ) ) {
app.setThreshold( Level.ERROR );
} else {
app.setThreshold( Level.INFO );
}
}
logger = Logger.getLogger( UpdateAgent.class );
}
private File findJarFile () throws IOException, UpdateException {
String[] libDirs = new String[]{
File.separator + "common" + File.separator + "lib",
File.separator + "dotCMS" + File.separator + "WEB-INF" + File.separator + "lib"
};
File libDir = null;
for ( String libDirName : libDirs ) {
File f = new File( getHomeProjectPath() + File.separator + FOLDER_HOME_DOTSERVER + File.separator + libDirName );
if ( f.exists() && f.isDirectory() ) {
libDir = f;
break;
}
}
if ( libDir == null ) {
throw new UpdateException( Messages.getString( "UpdateAgent.error.jar.not.found" ), UpdateException.ERROR );
}
File[] dotCMSjars = libDir.listFiles( new FileFilter() {
public boolean accept ( File pathname ) {
String fileName = pathname.getName().toLowerCase();
if ( fileName.startsWith( "dotcms_" ) && fileName.endsWith( ".jar" ) && (!fileName.startsWith( "dotcms_ant" )) ) {
return true;
}
return false;
}
} );
if ( dotCMSjars.length > 1 ) {
String jars = "";
for ( File jar : dotCMSjars ) {
jars += " " + jar.getName();
}
throw new UpdateException( Messages.getString( "UpdateAgent.error.multiple.jars" ) + jars, UpdateException.ERROR );
}
if ( dotCMSjars.length < 1 ) {
throw new UpdateException( Messages.getString( "UpdateAgent.error.jar.not.found" ), UpdateException.ERROR );
}
return dotCMSjars[0];
}
private Properties getJarProps () throws IOException, UpdateException {
JarFile jar = new JarFile( findJarFile() );
JarEntry entry = jar.getJarEntry( "com/liferay/portal/util/build.properties" );
Properties props = new Properties();
InputStream in = jar.getInputStream( entry );
props.load( in );
return props;
}
private String getVersion () throws IOException, UpdateException {
Properties props = getJarProps();
return props.getProperty( "dotcms.release.version" );
}
/**
* Will verify for some requires files on this update, specially the ant jars require then to run our ant tasks
*
* @param home
* @return
* @throws UpdateException
*/
private boolean checkRequisites ( String home ) throws UpdateException {
PostProcess postProcess = new PostProcess();
postProcess.setHome( home );
return postProcess.checkRequisites();
}
/**
* This method will verify that we have a valid .dotserver/ structure and installation looking for a couple of files
* that if it is a valid installation should be there.
*
* @param home
* @return
* @throws UpdateException
*/
private boolean checkHome ( String home ) throws UpdateException {
String[] homeCheckElements = {"build.xml", "dotCMS/WEB-INF/web.xml"};
File homeFolder;
for ( String check : homeCheckElements ) {
homeFolder = new File( home + File.separator + check );
if ( !homeFolder.exists() ) {
throw new UpdateException( Messages.getString( "UpdateAgent.error.home.not.valid" ), UpdateException.ERROR );
}
}
return true;
}
/**
* Returns the update file for the autoupdater client
*
* @return Autoupdater client update file
*/
private File downloadAgent ( String version ) {
File updateFile = new File( getHomeProjectPath() + File.separator + FOLDER_HOME_UPDATER + File.separator + "autoUpdater.new" );
try {
updateFile.createNewFile();
Map<String, String> map = new HashMap<String, String>();
map.put( "version", version );
//map.put( "version", UpdateUtil.getManifestValue( MANIFEST_PROPERTY_RELEASE_VERSION ) );
map.put( "agent_version", UpdateUtil.getManifestValue( MANIFEST_PROPERTY_AGENT_VERSION ) );
if ( allowTestingBuilds ) {
map.put( "allowTestingBuilds", "true" );
}
//Talking with the update servlet....
PostMethod method = doGet( url, map );
//Download the update file
int ret = download( updateFile, method );
if ( ret == 200 ) {
return updateFile;
}
if ( ret == 204 ) {
logger.debug( Messages.getString( "UpdateAgent.text.autoupdater.uptodate" ) );
}
} catch ( IOException e ) {
logger.error( Messages.getString( "UpdateAgent.error.no.autoupdater.version" ) + e.getMessage() );
logger.debug( "IOException: ", e );
}
updateFile.delete();
return null;
}
/**
* Process a get method
*
* @param fileUrl
* @param pars
* @return
* @throws IOException
*/
private PostMethod doGet ( String fileUrl, Map<String, String> pars ) throws IOException {
HttpClient client = new HttpClient();
// Setup a proxy
if ( proxy != null && proxy.length() > 0 ) {
String proxyHost = proxy.substring( 0, proxy.indexOf( ":" ) );
String proxyPort = proxy.substring( proxy.indexOf( ":" ) + 1 );
client.getHostConfiguration().setProxy( proxyHost, Integer.parseInt( proxyPort ) );
if ( proxyUser != null && proxyUser.length() > 0 && proxyPass != null && proxyPass.length() > 0 ) {
// Authenticate with proxy
client.getState().setProxyCredentials( null, null, new UsernamePasswordCredentials( proxyUser, proxyPass ) );
}
}
PostMethod method = new PostMethod( fileUrl );
Object[] keys = pars.keySet().toArray();
NameValuePair[] data = new NameValuePair[keys.length];
for ( int i = 0; i < keys.length; i++ ) {
String key = (String) keys[i];
NameValuePair pair = new NameValuePair( key, pars.get( key ) );
data[i] = pair;
}
method.setRequestBody( data );
client.executeMethod( method );
return method;
}
/**
* This method will download a file using a given url, after the download, if it was successful this method
* will verify the integrity of the file using the md5 check sum.
*
* @param downloadUrl
* @param outputFile
* @param postMethod
* @return status code
*/
private int download ( String downloadUrl, File outputFile, PostMethod postMethod ) {
int statusCode = 0;
try {
//Current status of the resent communication with the update servlet
statusCode = postMethod.getStatusCode();
logger.debug( Messages.getString( "UpdateAgent.debug.return.code" ) + statusCode );
if ( statusCode == 200 ) {//If everything was ok.....
// Just in case something else fails
statusCode = -1;
//Create objects to manage this file url...
URL url = new URL( downloadUrl );
URLConnection urlConnection = url.openConnection();
//Getting remote file size
int length = urlConnection.getContentLength();
String newMinor = null;
try {
newMinor = postMethod.getResponseHeader( "Minor-Version" ).getValue();
} catch ( Exception ignored ) {
}
String downloadMessage = Messages.getString( "UpdateAgent.text.downloading" );
if ( newMinor != null ) {
downloadMessage += Messages.getString( "UpdateAgent.text.new.minor" );
String[] minorArr = newMinor.split( "_" );
if ( minorArr.length > 1 ) {
downloadMessage += minorArr[0] + " / " + minorArr[1];
} else {
downloadMessage += minorArr[0];
}
}
if ( length > 0 ) {
downloadMessage += " (" + length / 1024 + "kB)";
}
logger.info( downloadMessage );
//Configuration of the download process handler
long startTime = System.currentTimeMillis();
long refreshInterval = 500;
DownloadProgress downloadProgress = new DownloadProgress( length );
//Initializing the download.....
InputStream is = urlConnection.getInputStream();
OutputStream outStream = new FileOutputStream( outputFile );
byte[] buffer = new byte[1024];
int bytesRead, bytesWritten = 0;
while ( (bytesRead = is.read( buffer )) != -1 ) {
outStream.write( buffer, 0, bytesRead );
bytesWritten += bytesRead;
//Keep tracking of the download status
long currentTime = System.currentTimeMillis();
if ( (currentTime - startTime) > refreshInterval ) {
String message = downloadProgress.getProgressMessage( bytesWritten, startTime, currentTime );
startTime = currentTime;
System.out.print( "\r" + message );
}
}
String message = Messages.getString( "UpdateAgent.text.download.complete" );
System.out.print( "\r" + message );
System.out.println( "" );
outStream.close();
is.close();
//Now we need to verfy the integrity of this downloaded file using md5
String MD5 = null;
boolean hasMD5 = false;
if ( postMethod.getResponseHeader( "Content-MD5" ) != null && !postMethod.getResponseHeader( "Content-MD5" ).equals( "" ) ) {
MD5 = postMethod.getResponseHeader( "Content-MD5" ).getValue();
if ( !MD5.equals( "" ) ) {
hasMD5 = true;
}
}
if ( hasMD5 ) {//The servlet sent us the md5 content, so lets use...
String dlMD5 = UpdateUtil.getMD5( outputFile );
logger.debug( Messages.getString( "UpdateAgent.debug.server.md5" ) + MD5 );
logger.debug( Messages.getString( "UpdateAgent.debug.file.md5" ) + dlMD5 );
if ( MD5 == null || MD5.length() == 0 || !dlMD5.equals( MD5 ) ) {
logger.fatal( Messages.getString( "UpdateAgent.error.md5.failed" ) );
outputFile.delete();
} else {
// everything went ok, we return the right return code
statusCode = 200;
logger.info( Messages.getString( "UpdateAgent.text.md5.verified" ) );
}
} else {
statusCode = 200;
logger.info( Messages.getString( "UpdateAgent.text.md5.verified" ) );
}
}
if ( statusCode == 204 ) {
logger.debug( Messages.getString( "UpdateAgent.debug.no.content" ) );
}
} catch ( HttpException e ) {
logger.error( Messages.getString( "UpdateAgent.error.downloading.file" ) + e.getMessage() );
logger.debug( "HttpException: ", e );
} catch ( IOException e ) {
logger.error( Messages.getString( "UpdateAgent.error.downloading.file" ) + e.getMessage() );
logger.debug( "IOException: ", e );
}
if ( postMethod != null ) {
postMethod.releaseConnection();
}
return statusCode;
}
/**
* This method will download an update file for dotcms, this will be after establishing a connection with the update servlet who is the one that will provide this update file
*
* @param outputFile
* @param method
* @return
* @throws URIException
* @throws MalformedURLException
*/
private int download ( File outputFile, PostMethod method ) throws URIException, MalformedURLException {
int statusCode = 0;
try {
statusCode = method.getStatusCode();
logger.debug( Messages.getString( "UpdateAgent.debug.return.code" ) + statusCode );
if ( statusCode == 200 ) {
// Just in case something else fails
statusCode = -1;
InputStream is = method.getResponseBodyAsStream();
OutputStream out = new FileOutputStream( outputFile );
byte[] b = new byte[1024];
int len;
int count = 0;
long length = 0;
String newMinor = null;
try {
String lenghtString = method.getResponseHeader( "Content-Length" ).getValue();
length = Long.parseLong( lenghtString );
} catch ( Exception ignored ) {
}
try {
newMinor = method.getResponseHeader( "Minor-Version" ).getValue();
} catch ( Exception ignored ) {
}
String dlMessage = Messages.getString( "UpdateAgent.text.downloading" );
if ( newMinor != null ) {
dlMessage += Messages.getString( "UpdateAgent.text.new.minor" );
dlMessage += newMinor;
}
if ( length > 0 ) {
dlMessage += " (" + length / 1024 + "kB)";
}
logger.info( dlMessage );
long startTime = System.currentTimeMillis();
long refreshInterval = 500;
DownloadProgress dp = new DownloadProgress( length );
while ( (len = is.read( b )) != -1 ) {
for ( int i = 0; i < len; i++ ) {
out.write( (char) b[i] );
count++;
}
long currentTime = System.currentTimeMillis();
if ( (currentTime - startTime) > refreshInterval ) {
String message = dp.getProgressMessage( count, startTime, currentTime );
startTime = currentTime;
System.out.print( "\r" + message );
}
}
String message = dp.getProgressMessage( count, startTime, System.currentTimeMillis() );
System.out.print( "\r" + message );
System.out.println( "" );
out.close();
is.close();
// verfiy md5
String MD5 = null;
boolean hasMD5 = false;
if ( method.getResponseHeader( "Content-MD5" ) != null && !method.getResponseHeader( "Content-MD5" ).equals( "" ) ) {
MD5 = method.getResponseHeader( "Content-MD5" ).getValue();
if ( !MD5.equals( "" ) ) {
hasMD5 = true;
}
}
if ( hasMD5 ) {
String dlMD5 = UpdateUtil.getMD5( outputFile );
logger.debug( Messages.getString( "UpdateAgent.debug.server.md5" ) + MD5 );
logger.debug( Messages.getString( "UpdateAgent.debug.file.md5" ) + dlMD5 );
if ( MD5 == null || MD5.length() == 0 || !dlMD5.equals( MD5 ) ) {
logger.fatal( Messages.getString( "UpdateAgent.error.md5.failed" ) );
outputFile.delete();
} else {
// everything went ok, we return the right return code
statusCode = 200;
logger.info( Messages.getString( "UpdateAgent.text.md5.verified" ) );
}
} else {
statusCode = 200;
logger.info( Messages.getString( "UpdateAgent.text.md5.verified" ) );
}
}
if ( statusCode == 204 ) {
logger.debug( Messages.getString( "UpdateAgent.debug.no.content" ) );
}
} catch ( HttpException e ) {
logger.error( Messages.getString( "UpdateAgent.error.downloading.file" ) + e.getMessage() );
logger.debug( "HttpException: ", e );
} catch ( IOException e ) {
logger.error( Messages.getString( "UpdateAgent.error.downloading.file" ) + e.getMessage() );
logger.debug( "IOException: ", e );
}
if ( method != null ) {
method.releaseConnection();
}
return statusCode;
}
public String getHomeProjectPath () {
return homeProjectPath;
}
}