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

lutoff
15.10.2007 184ed890c828220c114f60ee165ce2230ada3d7c
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
/*
 * 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
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE
 * or https://OpenDS.dev.java.net/OpenDS.LICENSE.
 * 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
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  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 2006-2007 Sun Microsystems, Inc.
 */
package org.opends.server.tools;
 
 
 
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
 
import org.opends.server.core.DirectoryServer;
import org.opends.server.extensions.ConfigFileHandler;
import org.opends.server.protocols.ldap.LDAPResultCode;
import org.opends.server.types.Attribute;
import org.opends.server.types.AttributeType;
import org.opends.server.types.AttributeValue;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.DN;
import org.opends.server.types.Entry;
import org.opends.server.types.ExistingFileBehavior;
import org.opends.server.types.LDAPException;
import org.opends.server.types.LDIFExportConfig;
import org.opends.server.types.LDIFImportConfig;
import org.opends.server.types.Modification;
import org.opends.server.types.ObjectClass;
import org.opends.server.types.RawModification;
import org.opends.server.util.AddChangeRecordEntry;
import org.opends.server.util.ChangeRecordEntry;
import org.opends.server.util.DeleteChangeRecordEntry;
import org.opends.server.util.LDIFException;
import org.opends.server.util.LDIFReader;
import org.opends.server.util.LDIFWriter;
import org.opends.server.util.ModifyChangeRecordEntry;
import org.opends.server.util.args.ArgumentException;
import org.opends.server.util.args.ArgumentParser;
import org.opends.server.util.args.BooleanArgument;
import org.opends.server.util.args.StringArgument;
 
import static org.opends.server.messages.MessageHandler.*;
import static org.opends.server.messages.ToolMessages.*;
import static org.opends.server.util.StaticUtils.*;
import static org.opends.server.tools.ToolConstants.*;
 
 
 
/**
 * This class provides a program that may be used to apply a set of changes (in
 * LDIF change format) to an LDIF file.  It will first read all of the changes
 * into memory, and then will iterate through an LDIF file and apply them to the
 * entries contained in it.  Note that because of the manner in which it
 * processes the changes, certain types of operations will not be allowed,
 * including:
 * <BR>
 * <UL>
 *   <LI>Modify DN operations</LI>
 *   <LI>Deleting an entry that has been added</LI>
 *   <LI>Modifying an entry that has been added</LI>
 * </UL>
 */
public class LDIFModify
{
  /**
   * The fully-qualified name of this class.
   */
  private static final String CLASS_NAME = "org.opends.server.tools.LDIFModify";
 
 
 
  /**
   * Applies the specified changes to the source LDIF, writing the modified
   * file to the specified target.  Neither the readers nor the writer will be
   * closed.
   *
   * @param  sourceReader  The LDIF reader that will be used to read the LDIF
   *                       content to be modified.
   * @param  changeReader  The LDIF reader that will be used to read the changes
   *                       to be applied.
   * @param  targetWriter  The LDIF writer that will be used to write the
   *                       modified LDIF.
   * @param  errorList     A list into which any error messages generated while
   *                       processing changes may be added.
   *
   * @return  <CODE>true</CODE> if all updates were successfully applied, or
   *          <CODE>false</CODE> if any errors were encountered.
   *
   * @throws  IOException  If a problem occurs while attempting to read the
   *                       source or changes, or write the target.
   *
   * @throws  LDIFException  If a problem occurs while attempting to decode the
   *                         source or changes, or trying to determine whether
   *                         to include the entry in the output.
   */
  public static boolean modifyLDIF(LDIFReader sourceReader,
                                   LDIFReader changeReader,
                                   LDIFWriter targetWriter,
                                   List<String> errorList)
         throws IOException, LDIFException
  {
    // Read the changes into memory.
    TreeMap<DN,AddChangeRecordEntry> adds =
          new TreeMap<DN,AddChangeRecordEntry>();
    TreeMap<DN,Entry> ldifEntries =
          new TreeMap<DN,Entry>();
    HashMap<DN,DeleteChangeRecordEntry> deletes =
         new HashMap<DN,DeleteChangeRecordEntry>();
    HashMap<DN,LinkedList<Modification>> modifications =
         new HashMap<DN,LinkedList<Modification>>();
 
    while (true)
    {
      ChangeRecordEntry changeRecord;
      try
      {
        changeRecord = changeReader.readChangeRecord(false);
      }
      catch (LDIFException le)
      {
        if (le.canContinueReading())
        {
          errorList.add(le.getMessage());
          continue;
        }
        else
        {
          throw le;
        }
      }
 
      if (changeRecord == null)
      {
        break;
      }
 
      DN changeDN = changeRecord.getDN();
      switch (changeRecord.getChangeOperationType())
      {
        case ADD:
          // The entry must not exist in the add list.
          if (adds.containsKey(changeDN))
          {
            int msgID = MSGID_LDIFMODIFY_CANNOT_ADD_ENTRY_TWICE;
            errorList.add(getMessage(msgID, String.valueOf(changeDN)));
            continue;
          }
          else
          {
            adds.put(changeDN, (AddChangeRecordEntry) changeRecord);
          }
          break;
 
        case DELETE:
          // The entry must not exist in the add list.  If it exists in the
          // modify list, then remove the changes since we won't need to apply
          // them.
          if (adds.containsKey(changeDN))
          {
            int msgID = MSGID_LDIFMODIFY_CANNOT_DELETE_AFTER_ADD;
            errorList.add(getMessage(msgID, String.valueOf(changeDN)));
            continue;
          }
          else
          {
            modifications.remove(changeDN);
            deletes.put(changeDN, (DeleteChangeRecordEntry) changeRecord);
          }
          break;
 
        case MODIFY:
          // The entry must not exist in the add or delete lists.
          if (adds.containsKey(changeDN) || deletes.containsKey(changeDN))
          {
            int msgID = MSGID_LDIFMODIFY_CANNOT_MODIFY_ADDED_OR_DELETED;
            errorList.add(getMessage(msgID, String.valueOf(changeDN)));
            continue;
          }
          else
          {
            LinkedList<Modification> mods =
                 modifications.get(changeDN);
            if (mods == null)
            {
              mods = new LinkedList<Modification>();
              modifications.put(changeDN, mods);
            }
 
            for (RawModification mod :
                 ((ModifyChangeRecordEntry) changeRecord).getModifications())
            {
              try
              {
                mods.add(mod.toModification());
              }
              catch (LDAPException le)
              {
                errorList.add(le.getMessage());
                continue;
              }
            }
          }
          break;
 
        case MODIFY_DN:
          int msgID = MSGID_LDIFMODIFY_MODDN_NOT_SUPPORTED;
          errorList.add(getMessage(msgID, String.valueOf(changeDN)));
          continue;
 
        default:
          msgID = MSGID_LDIFMODIFY_UNKNOWN_CHANGETYPE;
          errorList.add(getMessage(msgID, String.valueOf(changeDN),
               String.valueOf(changeRecord.getChangeOperationType())));
          continue;
      }
    }
 
 
    // Read the source an entry at a time and apply any appropriate changes
    // before writing to the target LDIF.
    while (true)
    {
      Entry entry;
      try
      {
        entry = sourceReader.readEntry();
      }
      catch (LDIFException le)
      {
        if (le.canContinueReading())
        {
          errorList.add(le.getMessage());
          continue;
        }
        else
        {
          throw le;
        }
      }
 
      if (entry == null)
      {
        break;
      }
 
 
      // If the entry is to be deleted, then just skip over it without writing
      // it to the output.
      DN entryDN = entry.getDN();
      if (deletes.remove(entryDN) != null)
      {
        continue;
      }
 
 
      // If the entry is to be added, then that's an error, since it already
      // exists.
      if (adds.remove(entryDN) != null)
      {
        int msgID = MSGID_LDIFMODIFY_ADD_ALREADY_EXISTS;
        errorList.add(getMessage(msgID, String.valueOf(entryDN)));
        continue;
      }
 
 
      // If the entry is to be modified, then process the changes.
      LinkedList<Modification> mods = modifications.remove(entryDN);
      if ((mods != null) && (! mods.isEmpty()))
      {
        try
        {
          entry.applyModifications(mods);
        }
        catch (DirectoryException de)
        {
          errorList.add(de.getErrorMessage());
          continue;
        }
      }
 
 
      // If we've gotten here, then the (possibly updated) entry should be
      // written to the LDIF entry Map.
      ldifEntries.put(entry.getDN(),entry);
    }
 
 
    // Perform any adds that may be necessary.
    for (AddChangeRecordEntry add : adds.values())
    {
      Map<ObjectClass,String> objectClasses =
           new LinkedHashMap<ObjectClass,String>();
      Map<AttributeType,List<Attribute>> userAttributes =
           new LinkedHashMap<AttributeType,List<Attribute>>();
      Map<AttributeType,List<Attribute>> operationalAttributes =
           new LinkedHashMap<AttributeType,List<Attribute>>();
 
      for (Attribute a : add.getAttributes())
      {
        AttributeType t = a.getAttributeType();
        if (t.isObjectClassType())
        {
          for (AttributeValue v : a.getValues())
          {
            String stringValue = v.getStringValue();
            String lowerValue  = toLowerCase(stringValue);
            ObjectClass oc = DirectoryServer.getObjectClass(lowerValue, true);
            objectClasses.put(oc, stringValue);
          }
        }
        else if (t.isOperational())
        {
          List<Attribute> attrList = operationalAttributes.get(t);
          if (attrList == null)
          {
            attrList = new LinkedList<Attribute>();
            operationalAttributes.put(t, attrList);
          }
          attrList.add(a);
        }
        else
        {
          List<Attribute> attrList = userAttributes.get(t);
          if (attrList == null)
          {
            attrList = new LinkedList<Attribute>();
            userAttributes.put(t, attrList);
          }
          attrList.add(a);
        }
      }
 
      Entry e = new Entry(add.getDN(), objectClasses, userAttributes,
                          operationalAttributes);
      //Put the entry to be added into the LDIF entry map.
      ldifEntries.put(e.getDN(),e);
    }
 
 
    // If there are any entries left in the delete or modify lists, then that's
    // a problem because they didn't exist.
    if (! deletes.isEmpty())
    {
      for (DN dn : deletes.keySet())
      {
        int msgID = MSGID_LDIFMODIFY_DELETE_NO_SUCH_ENTRY;
        errorList.add(getMessage(msgID, String.valueOf(dn)));
      }
    }
 
    if (! modifications.isEmpty())
    {
      for (DN dn : modifications.keySet())
      {
        int msgID = MSGID_LDIFMODIFY_MODIFY_NO_SUCH_ENTRY;
        errorList.add(getMessage(msgID, String.valueOf(dn)));
      }
    }
    return targetWriter.writeEntries(ldifEntries.values()) &&
            errorList.isEmpty();
  }
 
 
 
  /**
   * Invokes <CODE>ldifModifyMain</CODE> to perform the appropriate processing.
   *
   * @param  args  The command-line arguments provided to the client.
   */
  public static void main(String[] args)
  {
    int returnCode = ldifModifyMain(args, false);
    if (returnCode != 0)
    {
      System.exit(returnCode);
    }
  }
 
 
 
  /**
   * Processes the command-line arguments and makes the appropriate updates to
   * the LDIF file.
   *
   * @param  args               The command line arguments provided to this
   *                            program.
   * @param  serverInitialized  Indicates whether the Directory Server has
   *                            already been initialized (and therefore should
   *                            not be initialized a second time).
   *
   * @return  A value of zero if everything completed properly, or nonzero if
   *          any problem(s) occurred.
   */
  public static int ldifModifyMain(String[] args, boolean serverInitialized)
  {
    // Prepare the argument parser.
    BooleanArgument showUsage;
    StringArgument  changesFile;
    StringArgument  configClass;
    StringArgument  configFile;
    StringArgument  sourceFile;
    StringArgument  targetFile;
 
    String toolDescription = getMessage(MSGID_LDIFMODIFY_TOOL_DESCRIPTION);
    ArgumentParser argParser = new ArgumentParser(CLASS_NAME, toolDescription,
                                                  false);
 
    try
    {
      configFile = new StringArgument("configfile", 'c', "configFile", true,
                                      false, true, "{configFile}", null, null,
                                      MSGID_DESCRIPTION_CONFIG_FILE);
      configFile.setHidden(true);
      argParser.addArgument(configFile);
 
 
      configClass = new StringArgument("configclass", OPTION_SHORT_CONFIG_CLASS,
                             OPTION_LONG_CONFIG_CLASS, false,
                             false, true, OPTION_VALUE_CONFIG_CLASS,
                             ConfigFileHandler.class.getName(), null,
                             MSGID_DESCRIPTION_CONFIG_CLASS);
      configClass.setHidden(true);
      argParser.addArgument(configClass);
 
 
      sourceFile = new StringArgument("sourceldif", 's', "sourceLDIF", true,
                                      false, true, "{file}", null, null,
                                      MSGID_LDIFMODIFY_DESCRIPTION_SOURCE);
      argParser.addArgument(sourceFile);
 
 
      changesFile = new StringArgument("changesldif", 'm', "changesLDIF", true,
                                       false, true, "{file}", null, null,
                                       MSGID_LDIFMODIFY_DESCRIPTION_CHANGES);
      argParser.addArgument(changesFile);
 
 
      targetFile = new StringArgument("targetldif", 't', "targetLDIF", true,
                                      false, true, "{file}", null, null,
                                      MSGID_LDIFMODIFY_DESCRIPTION_TARGET);
      argParser.addArgument(targetFile);
 
 
      showUsage = new BooleanArgument("help", OPTION_SHORT_HELP,
                                      OPTION_LONG_HELP,
                                      MSGID_LDIFMODIFY_DESCRIPTION_HELP);
      argParser.addArgument(showUsage);
      argParser.setUsageArgument(showUsage);
    }
    catch (ArgumentException ae)
    {
      int    msgID   = MSGID_CANNOT_INITIALIZE_ARGS;
      String message = getMessage(msgID, ae.getMessage());
      System.err.println(message);
      return 1;
    }
 
 
    // Parse the command-line arguments provided to the program.
    try
    {
      argParser.parseArguments(args);
    }
    catch (ArgumentException ae)
    {
      int    msgID   = MSGID_ERROR_PARSING_ARGS;
      String message = getMessage(msgID, ae.getMessage());
 
      System.err.println(message);
      System.err.println(argParser.getUsage());
      return LDAPResultCode.CLIENT_SIDE_PARAM_ERROR;
    }
 
 
    // If we should just display usage or version information,
    // then print it and exit.
    if (argParser.usageOrVersionDisplayed())
    {
      return 0;
    }
 
 
    if (! serverInitialized)
    {
      // Bootstrap the Directory Server configuration for use as a client.
      DirectoryServer directoryServer = DirectoryServer.getInstance();
      directoryServer.bootstrapClient();
 
 
      // If we're to use the configuration then initialize it, along with the
      // schema.
      boolean checkSchema = configFile.isPresent();
      if (checkSchema)
      {
        try
        {
          directoryServer.initializeJMX();
        }
        catch (Exception e)
        {
          int    msgID   = MSGID_LDIFMODIFY_CANNOT_INITIALIZE_JMX;
          String message = getMessage(msgID,
                                      String.valueOf(configFile.getValue()),
                                      e.getMessage());
          System.err.println(message);
          return 1;
        }
 
        try
        {
          directoryServer.initializeConfiguration(configClass.getValue(),
                                                  configFile.getValue());
        }
        catch (Exception e)
        {
          int    msgID   = MSGID_LDIFMODIFY_CANNOT_INITIALIZE_CONFIG;
          String message = getMessage(msgID,
                                      String.valueOf(configFile.getValue()),
                                      e.getMessage());
          System.err.println(message);
          return 1;
        }
 
        try
        {
          directoryServer.initializeSchema();
        }
        catch (Exception e)
        {
          int    msgID   = MSGID_LDIFMODIFY_CANNOT_INITIALIZE_SCHEMA;
          String message = getMessage(msgID,
                                      String.valueOf(configFile.getValue()),
                                      e.getMessage());
          System.err.println(message);
          return 1;
        }
      }
    }
 
 
    // Create the LDIF readers and writer from the arguments.
    File source = new File(sourceFile.getValue());
    if (! source.exists())
    {
      int    msgID   = MSGID_LDIFMODIFY_SOURCE_DOES_NOT_EXIST;
      String message = getMessage(msgID, sourceFile.getValue());
      System.err.println(message);
      return LDAPResultCode.CLIENT_SIDE_PARAM_ERROR;
    }
 
    LDIFImportConfig importConfig = new LDIFImportConfig(sourceFile.getValue());
    LDIFReader sourceReader;
    try
    {
      sourceReader = new LDIFReader(importConfig);
    }
    catch (IOException ioe)
    {
      int    msgID   = MSGID_LDIFMODIFY_CANNOT_OPEN_SOURCE;
      String message = getMessage(msgID, sourceFile.getValue(),
                                  String.valueOf(ioe));
      System.err.println(message);
      return LDAPResultCode.CLIENT_SIDE_LOCAL_ERROR;
    }
 
 
    File changes = new File(changesFile.getValue());
    if (! changes.exists())
    {
      int    msgID   = MSGID_LDIFMODIFY_CHANGES_DOES_NOT_EXIST;
      String message = getMessage(msgID, changesFile.getValue());
      System.err.println(message);
      return LDAPResultCode.CLIENT_SIDE_PARAM_ERROR;
    }
 
    importConfig = new LDIFImportConfig(changesFile.getValue());
    LDIFReader changeReader;
    try
    {
      changeReader = new LDIFReader(importConfig);
    }
    catch (IOException ioe)
    {
      int    msgID   = MSGID_LDIFMODIFY_CANNOT_OPEN_CHANGES;
      String message = getMessage(msgID, sourceFile.getValue());
      System.err.println(message);
      return LDAPResultCode.CLIENT_SIDE_LOCAL_ERROR;
    }
 
 
    LDIFExportConfig exportConfig =
         new LDIFExportConfig(targetFile.getValue(),
                              ExistingFileBehavior.OVERWRITE);
    LDIFWriter targetWriter;
    try
    {
      targetWriter = new LDIFWriter(exportConfig);
    }
    catch (IOException ioe)
    {
      int    msgID   = MSGID_LDIFMODIFY_CANNOT_OPEN_TARGET;
      String message = getMessage(msgID, sourceFile.getValue());
      System.err.println(message);
      return LDAPResultCode.CLIENT_SIDE_LOCAL_ERROR;
    }
 
 
    // Actually invoke the LDIF procesing.
    LinkedList<String> errorList = new LinkedList<String>();
    boolean successful;
    try
    {
      successful = modifyLDIF(sourceReader, changeReader, targetWriter,
                              errorList);
    }
    catch (Exception e)
    {
      int    msgID   = MSGID_LDIFMODIFY_ERROR_PROCESSING_LDIF;
      String message = getMessage(msgID, String.valueOf(e));
      System.err.println(message);
 
      successful = false;
    }
 
    try
    {
      sourceReader.close();
    } catch (Exception e) {}
 
    try
    {
      changeReader.close();
    } catch (Exception e) {}
 
    try
    {
      targetWriter.close();
    } catch (Exception e) {}
 
    for (String s : errorList)
    {
      System.err.println(s);
    }
    return (successful ? 0 : 1);
  }
}