mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Jean-Noel Rouvignac
17.57.2014 0f1c0c1956329c081d047b3bd9a560a4c1680cd7
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at legal-notices/CDDLv1_0.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Portions Copyright 2013-2014 ForgeRock AS
 */
package org.opends.server.tools.upgrade;
 
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
 
import javax.security.auth.callback.TextOutputCallback;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.ldap.Filter;
import org.opends.server.tools.RebuildIndex;
import org.opends.server.util.BuildVersion;
import org.opends.server.util.ChangeOperationType;
 
import com.forgerock.opendj.cli.ClientException;
import com.forgerock.opendj.cli.ReturnCode;
 
import static javax.security.auth.callback.ConfirmationCallback.*;
 
import static org.opends.messages.ToolMessages.*;
import static org.opends.server.tools.upgrade.FileManager.*;
import static org.opends.server.tools.upgrade.Installation.*;
import static org.opends.server.tools.upgrade.UpgradeUtils.*;
 
/**
 * Factory methods for create new upgrade tasks.
 */
public final class UpgradeTasks
{
  /** Logger for the upgrade. */
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
  /** An errors counter in case of ignore errors mode. */
  static int countErrors;
 
  /** Contains all the indexes to rebuild. */
  static Set<String> indexesToRebuild = new HashSet<String>();
 
  /** A flag to avoid rebuild single indexes if 'rebuild all' is selected. */
  static boolean isRebuildAllIndexesIsPresent;
 
  /** A flag for marking 'rebuild all' task accepted by user. */
  static boolean isRebuildAllIndexesTaskAccepted;
 
  /**
   * Returns a new upgrade task which adds a config entry to the underlying
   * config file.
   *
   * @param summary
   *          The summary of this upgrade task.
   * @param ldif
   *          The LDIF record which will be applied to matching entries.
   * @return A new upgrade task which applies an LDIF record to all
   *         configuration entries matching the provided filter.
   */
  public static UpgradeTask addConfigEntry(final LocalizableMessage summary,
      final String... ldif)
  {
    return addConfigEntry0(summary, summary, false, ldif);
  }
 
  /**
   * Returns a new upgrade task which applies an LDIF record to all
   * configuration entries matching the provided filter.
   *
   * @param summary
   *          The summary of this upgrade task.
   * @param description
   *          The detailed description of this upgrade task.
   * @param ldif
   *          The LDIF record which will be applied to matching entries.
   * @return A new upgrade task which applies an LDIF record to all
   *         configuration entries matching the provided filter.
   */
  public static UpgradeTask addConfigEntryOptional(final LocalizableMessage summary,
      final LocalizableMessage description, final String... ldif)
  {
    return addConfigEntry0(summary, description, true, ldif);
  }
 
  /**
   * This task copies the file placed in parameter within the config / schema
   * folder. If the file already exists, it's overwritten.
   *
   * @param fileName
   *          The name of the file which need to be copied.
   * @return A task which copy the the file placed in parameter within the
   *         config / schema folder. If the file already exists, it's
   *         overwritten.
   */
  public static UpgradeTask copySchemaFile(final String fileName)
  {
    return new AbstractUpgradeTask()
    {
      @Override
      public void perform(final UpgradeContext context) throws ClientException
      {
        final LocalizableMessage msg = INFO_UPGRADE_TASK_REPLACE_SCHEMA_FILE.get(fileName);
        logger.debug(msg);
 
        final ProgressNotificationCallback pnc =
            new ProgressNotificationCallback(0, msg, 0);
 
        final File schemaFileTemplate =
            new File(templateConfigSchemaDirectory, fileName);
 
        try
        {
          context.notifyProgress(pnc.setProgress(20));
          if (!schemaFileTemplate.exists() || schemaFileTemplate.length() == 0)
          {
            throw new IOException(ERR_UPGRADE_CORRUPTED_TEMPLATE
                .get(schemaFileTemplate.getPath()).toString());
          }
          copy(schemaFileTemplate, configSchemaDirectory, true);
          context.notifyProgress(pnc.setProgress(100));
        }
        catch (final IOException e)
        {
          manageTaskException(context, ERR_UPGRADE_COPYSCHEMA_FAILS.get(
              schemaFileTemplate.getName(), e.getMessage()), pnc);
        }
      }
    };
  }
 
  /**
   * This task copies the file placed in parameter within the config folder. If
   * the file already exists, it's overwritten.
   *
   * @param fileName
   *          The name of the file which need to be copied.
   * @return A task which copy the the file placed in parameter within the
   *         config folder. If the file already exists, it's overwritten.
   */
  public static UpgradeTask addConfigFile(final String fileName)
  {
    return new AbstractUpgradeTask()
    {
      @Override
      public void perform(final UpgradeContext context) throws ClientException
      {
        final LocalizableMessage msg = INFO_UPGRADE_TASK_ADD_CONFIG_FILE.get(fileName);
        logger.debug(msg);
 
        final ProgressNotificationCallback pnc =
            new ProgressNotificationCallback(0, msg, 0);
 
        final File configFile = new File(templateConfigDirectory, fileName);
 
        try
        {
          context.notifyProgress(pnc.setProgress(20));
 
          copy(configFile, configDirectory, true);
          context.notifyProgress(pnc.setProgress(100));
        }
        catch (final IOException e)
        {
          manageTaskException(context, ERR_UPGRADE_ADD_CONFIG_FILE_FAILS.get(
              configFile.getName(), e.getMessage()), pnc);
        }
      }
    };
  }
 
  /**
   * Returns a new upgrade task which deletes a config entry from the underlying
   * config file.
   *
   * @param summary
   *          The summary of this upgrade task.
   * @param dnInLDIF
   *          The dn to delete in the form of LDIF.
   * @return A new upgrade task which applies an LDIF record to all
   *         configuration entries matching the provided filter.
   */
  public static UpgradeTask deleteConfigEntry(final LocalizableMessage summary,
      final String dnInLDIF)
  {
    return new AbstractUpgradeTask()
    {
      @Override
      public void perform(final UpgradeContext context) throws ClientException
      {
        perform0(summary, null, ChangeOperationType.DELETE, context, dnInLDIF);
      }
    };
  }
 
  /**
   * Returns a new upgrade task which applies an LDIF record to all
   * configuration entries matching the provided filter.
   *
   * @param summary
   *          The summary of this upgrade task.
   * @param filter
   *          The LDAP filter which configuration entries must match.
   * @param ldif
   *          The LDIF record which will be applied to matching entries.
   * @return A new upgrade task which applies an LDIF record to all
   *         configuration entries matching the provided filter.
   */
  public static UpgradeTask modifyConfigEntry(final LocalizableMessage summary,
      final String filter, final String... ldif)
  {
    return modifyConfigEntry(summary, summary, false, filter, ldif);
  }
 
  /**
   * Returns a new upgrade task which applies an LDIF record to all
   * configuration entries matching the provided filter.
   *
   * @param summary
   *          The summary of this upgrade task.
   * @param description
   *          The detailed description of this upgrade task.
   * @param filter
   *          The LDAP filter which configuration entries must match.
   * @param ldif
   *          The LDIF record which will be applied to matching entries.
   * @return A new upgrade task which applies an LDIF record to all
   *         configuration entries matching the provided filter.
   */
  public static UpgradeTask modifyConfigEntryOptional(final LocalizableMessage summary,
      final LocalizableMessage description, final String filter, final String... ldif)
  {
    return modifyConfigEntry(summary, description, true, filter, ldif);
  }
 
  /**
   * This task adds a new attribute type (must exists in the original file) to
   * the specified file placed in parameter. The destination must be a file
   * contained in the config/schema folder. E.g : This example adds a new
   * attribute type named 'etag' in the 00.core.ldif. The 'etag' attribute
   * already exists in the 00-core.ldif template schema file.
   *
   * <pre>
   * register(&quot;2.5.0.7192&quot;,
   *   newAttributeTypes(LocalizableMessage.raw(&quot;New attribute etag&quot;),
   *   false, &quot;00-core.ldif&quot;,
   *   &quot;1.3.6.1.4.1.36733.2.1.1.59&quot;));
   * </pre>
   *
   * @param summary
   *          The summary of the task.
   * @param fileName
   *          The file where to add the new attribute types. This file must be
   *          contained in the configuration/schema folder.
   * @param attributeOids
   *          The OIDs of the new attributes to add to.
   * @return An upgrade task which adds new attribute types, defined previously
   *         in the configuration template files, reads the definition
   *         and adds it onto the specified file in parameter.
   */
  public static UpgradeTask newAttributeTypes(final LocalizableMessage summary,
      final String fileName, final String... attributeOids)
  {
    return new AbstractUpgradeTask()
    {
      @Override
      public void perform(final UpgradeContext context) throws ClientException
      {
        logger.debug(summary);
 
        final ProgressNotificationCallback pnc =
            new ProgressNotificationCallback(0, summary, 20);
        context.notifyProgress(pnc);
 
        final File schemaFileTemplate =
            new File(templateConfigSchemaDirectory, fileName);
 
        final File pathDestination = new File(configSchemaDirectory, fileName);
        try
        {
          final int changeCount =
              updateSchemaFile(schemaFileTemplate, pathDestination,
                  attributeOids, null);
 
          displayChangeCount(pathDestination.getPath(), changeCount);
 
          context.notifyProgress(pnc.setProgress(100));
        }
        catch (final IOException e)
        {
          manageTaskException(context, ERR_UPGRADE_ADDATTRIBUTE_FAILS.get(
              schemaFileTemplate.getName(), e.getMessage()), pnc);
        }
        catch (final IllegalStateException e)
        {
          manageTaskException(context, ERR_UPGRADE_ADDATTRIBUTE_FAILS.get(
              schemaFileTemplate.getName(), e.getMessage()), pnc);
        }
      }
    };
  }
 
  /**
   * This task adds a new object class (must exists in the original file) to the
   * specified file placed in parameter. The destination must be a file
   * contained in the config/schema folder.
   *
   * @param summary
   *          The summary of the task.
   * @param fileName
   *          The file where to add the new object classes. This file must be
   *          contained in the configuration/schema folder.
   * @param objectClassesOids
   *          The OIDs of the new object classes to add to.
   * @return An upgrade task which adds new object classes, defined previously
   *         in the configuration template files,
   *         reads the definition and adds it onto the specified file in
   *         parameter.
   */
  public static UpgradeTask newObjectClasses(final LocalizableMessage summary,
      final String fileName, final String... objectClassesOids)
  {
    return new AbstractUpgradeTask()
    {
      @Override
      public void perform(final UpgradeContext context) throws ClientException
      {
        logger.debug(summary);
 
        final ProgressNotificationCallback pnc =
            new ProgressNotificationCallback(0, summary, 20);
        context.notifyProgress(pnc);
 
        final File schemaFileTemplate =
            new File(templateConfigSchemaDirectory, fileName);
 
        final File pathDestination = new File(configSchemaDirectory, fileName);
 
        context.notifyProgress(pnc.setProgress(20));
 
        try
        {
          final int changeCount =
              updateSchemaFile(schemaFileTemplate, pathDestination,
                  null, objectClassesOids);
 
          displayChangeCount(pathDestination.getPath(), changeCount);
 
          context.notifyProgress(pnc.setProgress(100));
        }
        catch (final IOException e)
        {
          manageTaskException(context, ERR_UPGRADE_ADDOBJECTCLASS_FAILS.get(
              schemaFileTemplate.getName(), e.getMessage()), pnc);
        }
        catch (final IllegalStateException e)
        {
          manageTaskException(context, ERR_UPGRADE_ADDATTRIBUTE_FAILS.get(
              schemaFileTemplate.getName(), e.getMessage()), pnc);
        }
      }
    };
  }
 
  /**
   * Creates a group of tasks which will only be invoked if the current version
   * is more recent than the provided version. This may be useful in cases where
   * a regression was introduced in version X and resolved in a later version Y.
   * In this case, the provided upgrade tasks will only be invoked if the
   * current version is between X (inclusive) and Y (exclusive).
   *
   * @param versionString
   *          The lower bound version. The upgrade tasks will not be applied if
   *          the current version is older than this version.
   * @param tasks
   *          The group of tasks to invoke if the current version is equal to or
   *          more recent than {@code versionString}.
   * @return An upgrade task which will only be invoked if the current version
   *         is more recent than the provided version.
   */
  public static UpgradeTask regressionInVersion(final String versionString,
      final UpgradeTask... tasks)
  {
    final BuildVersion version = BuildVersion.valueOf(versionString);
    return new AbstractUpgradeTask()
    {
 
      @Override
      public void verify(UpgradeContext context) throws ClientException
      {
        if (currentVersionEqualToOrMoreRecentThan(context, version))
        {
          for (UpgradeTask task : tasks)
          {
            task.verify(context);
          }
        }
      }
 
      @Override
      public void interact(UpgradeContext context) throws ClientException
      {
        if (currentVersionEqualToOrMoreRecentThan(context, version))
        {
          for (UpgradeTask task : tasks)
          {
            task.interact(context);
          }
        }
      }
 
      @Override
      public void perform(UpgradeContext context) throws ClientException
      {
        if (currentVersionEqualToOrMoreRecentThan(context, version))
        {
          for (UpgradeTask task : tasks)
          {
            task.perform(context);
          }
        }
      }
 
      @Override
      public void postUpgrade(UpgradeContext context) throws ClientException
      {
        if (currentVersionEqualToOrMoreRecentThan(context, version))
        {
          boolean isOk = true;
          for (final UpgradeTask task : tasks)
          {
            if (isOk)
            {
              try
              {
                task.postUpgrade(context);
              }
              catch (ClientException e)
              {
                logger.error(LocalizableMessage.raw(e.getMessage()));
                isOk = false;
              }
            }
            else
            {
              task.postponePostUpgrade(context);
            }
          }
        }
      }
 
 
      private boolean currentVersionEqualToOrMoreRecentThan(
          UpgradeContext context, final BuildVersion version)
      {
        return context.getFromVersion().compareTo(version) >= 0;
      }
    };
  }
 
  /**
   * Creates a rebuild all indexes task.
   *
   * @param summary
   *          The summary of this upgrade task.
   * @return An Upgrade task which rebuild all the indexes.
   */
  public static UpgradeTask rebuildAllIndexes(final LocalizableMessage summary)
  {
    return new AbstractUpgradeTask()
    {
      private boolean isATaskToPerform = false;
 
      @Override
      public void interact(UpgradeContext context) throws ClientException
      {
        Upgrade.setHasPostUpgradeTask(true);
        // Requires answer from the user.
        isATaskToPerform = context.confirmYN(summary, NO) == YES;
        isRebuildAllIndexesIsPresent = true;
        isRebuildAllIndexesTaskAccepted = isATaskToPerform;
      }
 
      @Override
      public void postUpgrade(final UpgradeContext context) throws ClientException
      {
        if (!isATaskToPerform)
        {
          postponePostUpgrade(context);
        }
      }
 
      @Override
      public void postponePostUpgrade(UpgradeContext context) throws ClientException
      {
        context.notify(INFO_UPGRADE_ALL_REBUILD_INDEX_DECLINED.get(), TextOutputCallback.WARNING);
      }
    };
  }
 
 
 
  /**
   * Creates a rebuild index task for a given single index. As this task is
   * possibly lengthy, it's considered as a post upgrade task. This task is not
   * mandatory; e.g not require user interaction, but could be required to get a
   * fully functional server. <br />
   * The post upgrade task just register the task. The rebuild indexes tasks are
   * completed at the end of the upgrade process.
   *
   * @param summary
   *          A message describing why the index needs to be rebuilt and asking
   *          them whether or not they wish to perform this task after the
   *          upgrade.
   * @param index
   *          The index to rebuild.
   * @return The rebuild index task.
   */
  public static UpgradeTask rebuildSingleIndex(final LocalizableMessage summary,
      final String index)
  {
    return new AbstractUpgradeTask()
    {
      private boolean isATaskToPerform = false;
 
      @Override
      public void interact(UpgradeContext context) throws ClientException
      {
        Upgrade.setHasPostUpgradeTask(true);
        // Requires answer from the user.
        isATaskToPerform = context.confirmYN(summary, NO) == YES;
      }
 
      @Override
      public void postUpgrade(final UpgradeContext context) throws ClientException
      {
        if (isATaskToPerform)
        {
          indexesToRebuild.add(index);
        }
        else
        {
          postponePostUpgrade(context);
        }
      }
 
      @Override
      public void postponePostUpgrade(UpgradeContext context) throws ClientException
      {
        if (!isRebuildAllIndexesIsPresent)
        {
          context.notify(INFO_UPGRADE_REBUILD_INDEX_DECLINED.get(index), TextOutputCallback.WARNING);
        }
      }
    };
  }
 
  /**
   * This task is processed at the end of the upgrade, rebuilding indexes. If a
   * rebuild all indexes has been registered before, it takes the flag
   * relatively to single rebuild index.
   *
   * @return The post upgrade rebuild indexes task.
   */
  public static UpgradeTask postUpgradeRebuildIndexes()
  {
    return new AbstractUpgradeTask()
    {
      @Override
      public void postUpgrade(final UpgradeContext context) throws ClientException
      {
        LocalizableMessage message = null;
        final List<String> args = new LinkedList<String>();
 
        if (isRebuildAllIndexesIsPresent && isRebuildAllIndexesTaskAccepted)
        {
          args.add("--rebuildAll");
          message = INFO_UPGRADE_REBUILD_ALL.get();
        }
        else if (!indexesToRebuild.isEmpty()
            && !isRebuildAllIndexesTaskAccepted)
        {
          message = INFO_UPGRADE_REBUILD_INDEX_STARTS.get(indexesToRebuild);
 
          // Adding all requested indexes.
          for (final String indexToRebuild : indexesToRebuild)
          {
            args.add("-i");
            args.add(indexToRebuild);
          }
        }
        else
        {
          return;
        }
        // Startup message.
        ProgressNotificationCallback pnc =
            new ProgressNotificationCallback(0, message, 25);
        logger.debug(message);
        context.notifyProgress(pnc);
 
        // Sets the arguments like the rebuild index command line.
        args.addAll(Arrays.asList(
            "-f",
            new File(configDirectory, CURRENT_CONFIG_FILE_NAME).getAbsolutePath()));
 
        /*
         * Index(es) could be contained in several backends or none, If none,
         * the post upgrade tasks succeed and a message is printed in the
         * upgrade log file.
         */
        final List<String> backends = UpgradeUtils.getLocalBackendsFromConfig();
        if (!backends.isEmpty())
        {
          for (final String be : backends)
          {
            args.add("-b");
            args.add(be);
          }
 
          // Displays info about command line args for log only.
          logger.debug(INFO_UPGRADE_REBUILD_INDEX_ARGUMENTS, args);
 
          /*
           * The rebuild-index process just display a status ok / fails. The
           * logger stream contains all the log linked to this process. The
           * complete process is not displayed in the upgrade console.
           */
          final String[] commandLineArgs = args.toArray(new String[args.size()]);
          final int result = new RebuildIndex().rebuildIndexesWithinMultipleBackends(
              true, UpgradeLog.getPrintStream(), commandLineArgs);
 
          if (result == 0)
          {
            logger.debug(INFO_UPGRADE_REBUILD_INDEX_ENDS);
            context.notifyProgress(pnc.setProgress(100));
          }
          else
          {
            final LocalizableMessage msg = ERR_UPGRADE_PERFORMING_POST_TASKS_FAIL.get();
            context.notifyProgress(pnc.setProgress(-100));
            throw new ClientException(ReturnCode.ERROR_UNEXPECTED, msg);
          }
        }
        else
        {
          logger.debug(INFO_UPGRADE_REBUILD_INDEX_NO_BACKEND_FOUND);
          logger.debug(INFO_UPGRADE_REBUILD_INDEX_DECLINED, indexesToRebuild);
          context.notifyProgress(pnc.setProgress(100));
        }
      }
    };
  }
 
  /**
   * Creates a file object representing config/upgrade/schema.ldif.current which
   * the server creates the first time it starts if there are schema
   * customizations.
   *
   * @return An upgrade task which upgrade the config/upgrade folder, creating a
   *         new schema.ldif.rev which is needed after schema customization for
   *         starting correctly the server.
   */
  public static UpgradeTask updateConfigUpgradeFolder()
  {
    return new AbstractUpgradeTask()
    {
      @Override
      public void perform(final UpgradeContext context) throws ClientException
      {
        final LocalizableMessage msg = INFO_UPGRADE_TASK_REFRESH_UPGRADE_DIRECTORY.get();
        logger.debug(msg);
 
        final ProgressNotificationCallback pnc = new ProgressNotificationCallback(0, msg, 20);
        context.notifyProgress(pnc);
 
        try
        {
          String toRevision = String.valueOf(context.getToVersion().getRevisionNumber());
          updateConfigUpgradeSchemaFile(configSchemaDirectory, toRevision);
 
          context.notifyProgress(pnc.setProgress(100));
        }
        catch (final Exception ex)
        {
          manageTaskException(context, ERR_UPGRADE_CONFIG_ERROR_UPGRADE_FOLDER.get(ex.getMessage()), pnc);
        }
      }
    };
  }
 
  /**
   * Renames the SNMP security config file if it exists. Since 2.5.0.7466 this
   * file has been renamed.
   *
   * @param summary
   *          The summary of this upgrade task.
   * @return An upgrade task which renames the old SNMP security config file if
   *         it exists.
   */
  public static UpgradeTask renameSnmpSecurityConfig(final LocalizableMessage summary)
  {
    return new AbstractUpgradeTask()
    {
      @Override
      public void perform(final UpgradeContext context) throws ClientException
      {
        /*
         * Snmp config file contains old name in old version(like 2.4.5), in
         * order to make sure the process will still work after upgrade, we need
         * to rename it - only if it exists.
         */
        final File snmpDir = UpgradeUtils.configSnmpSecurityDirectory;
        if (snmpDir.exists())
        {
          ProgressNotificationCallback pnc =
              new ProgressNotificationCallback(0, summary, 0);
          try
          {
            final File oldSnmpConfig = new File(snmpDir, "opends-snmp.security");
            if (oldSnmpConfig.exists())
            {
              context.notifyProgress(pnc.setProgress(20));
              logger.debug(summary);
 
              final File snmpConfig = new File(snmpDir, "opendj-snmp.security");
              FileManager.rename(oldSnmpConfig, snmpConfig);
 
              context.notifyProgress(pnc.setProgress(100));
            }
          }
          catch (final Exception ex)
          {
            LocalizableMessage msg = ERR_UPGRADE_RENAME_SNMP_SECURITY_CONFIG_FILE.get(ex.getMessage());
            manageTaskException(context, msg, pnc);
          }
        }
      }
    };
  }
 
  private static UpgradeTask addConfigEntry0(final LocalizableMessage summary,
      final LocalizableMessage description, final boolean needsUserConfirmation,
      final String... ldif)
  {
    return new AbstractUpgradeTask()
    {
      private boolean userConfirmation = true;
 
      @Override
      public void interact(final UpgradeContext context) throws ClientException
      {
        if (needsUserConfirmation)
        {
          // Process needs to have user's response to perform the current modification.
          LocalizableMessage msg = INFO_UPGRADE_TASK_NEEDS_USER_CONFIRM.get(description);
          if (context.confirmYN(msg, YES) == NO)
          {
            // The user refuses to perform this task.
            userConfirmation = false;
          }
        }
      }
 
      @Override
      public void perform(final UpgradeContext context) throws ClientException
      {
        if (userConfirmation)
        {
          perform0(summary, null, ChangeOperationType.ADD, context, ldif);
        }
      }
    };
  }
 
  private static void displayChangeCount(final String fileName,
      final int changeCount)
  {
    if (changeCount != 0)
    {
      logger.debug(INFO_UPGRADE_CHANGE_DONE_IN_SPECIFIC_FILE, fileName, changeCount);
    }
    else
    {
      logger.debug(INFO_UPGRADE_NO_CHANGE_DONE_IN_SPECIFIC_FILE, fileName);
    }
  }
 
  private static void displayTaskLogInformation(final String summary,
      final String filter, final String... ldif)
  {
    logger.debug(LocalizableMessage.raw(summary));
    if (filter != null)
    {
      logger.debug(LocalizableMessage.raw(filter));
    }
    if (ldif != null)
    {
      logger.debug(LocalizableMessage.raw(Arrays.toString(ldif)));
    }
  }
 
  private static void manageTaskException(final UpgradeContext context,
      final LocalizableMessage message, final ProgressNotificationCallback pnc)
      throws ClientException
  {
    countErrors++;
    context.notifyProgress(pnc.setProgress(-100));
    logger.error(message);
    if (!context.isIgnoreErrorsMode())
    {
      throw new ClientException(ReturnCode.ERROR_UNEXPECTED, message);
    }
  }
 
  private static UpgradeTask modifyConfigEntry(final LocalizableMessage summary,
      final LocalizableMessage description, final boolean needsUserConfirmation,
      final String filter, final String... ldif)
  {
    return new AbstractUpgradeTask()
    {
      private boolean userConfirmation = true;
 
      @Override
      public void interact(final UpgradeContext context) throws ClientException
      {
        if (needsUserConfirmation)
        {
          // Process needs to have user's response to perform the current modification
          LocalizableMessage msg = INFO_UPGRADE_TASK_NEEDS_USER_CONFIRM.get(description);
          if (context.confirmYN(msg, YES) == NO)
          {
            // The user refuses to perform this task.
            userConfirmation = false;
          }
        }
      }
 
      @Override
      public void perform(final UpgradeContext context) throws ClientException
      {
        if (userConfirmation)
        {
          perform0(summary, filter, ChangeOperationType.MODIFY, context, ldif);
        }
      }
 
    };
  }
 
  private static void perform0(final LocalizableMessage summary, final String filter,
      final ChangeOperationType changeOperationType,
      final UpgradeContext context, final String... ldif)
      throws ClientException
  {
    displayTaskLogInformation(summary.toString(), filter, ldif);
 
    final ProgressNotificationCallback pnc =
        new ProgressNotificationCallback(0, summary, 20);
 
    context.notifyProgress(pnc);
 
    try
    {
      final File configFile =
          new File(configDirectory, Installation.CURRENT_CONFIG_FILE_NAME);
 
      final Filter filterVal = filter != null ? Filter.valueOf(filter) : null;
      final int changeCount = updateConfigFile(
          configFile.getPath(), filterVal, changeOperationType, ldif);
 
      displayChangeCount(configFile.getPath(), changeCount);
 
      context.notifyProgress(pnc.setProgress(100));
    }
    catch (final Exception e)
    {
      manageTaskException(context, LocalizableMessage.raw(e.getMessage()), pnc);
    }
  }
 
  /** Prevent instantiation. */
  private UpgradeTasks()
  {
    // Do nothing.
  }
}