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

Nicolas Capponi
26.08.2015 8b3cd28204e15e0a98ce038b355f100cd7c44e3c
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
/*
 * 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
 *
 *
 *      Copyright 2006-2010 Sun Microsystems, Inc.
 *      Portions Copyright 2013-2016 ForgeRock AS.
 */
package org.opends.server.tools.makeldif;
 
import static com.forgerock.opendj.cli.ArgumentConstants.*;
import static com.forgerock.opendj.cli.Utils.*;
 
import static org.opends.messages.ToolMessages.*;
import static org.opends.server.util.StaticUtils.*;
 
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.LinkedList;
import java.util.Random;
 
import org.forgerock.i18n.LocalizableMessage;
import org.opends.server.core.DirectoryServer;
import org.opends.server.core.DirectoryServer.DirectoryServerVersionHandler;
import org.opends.server.loggers.JDKLogging;
import org.forgerock.opendj.ldap.schema.AttributeType;
import org.opends.server.types.ExistingFileBehavior;
import org.opends.server.types.InitializationException;
import org.opends.server.types.LDIFExportConfig;
import org.opends.server.types.NullOutputStream;
import org.opends.server.util.BuildVersion;
import org.opends.server.util.LDIFWriter;
 
import com.forgerock.opendj.cli.ArgumentException;
import com.forgerock.opendj.cli.ArgumentParser;
import com.forgerock.opendj.cli.BooleanArgument;
import com.forgerock.opendj.cli.CommonArguments;
import com.forgerock.opendj.cli.IntegerArgument;
import com.forgerock.opendj.cli.StringArgument;
 
/**
 * This class defines a program that can be used to generate LDIF content based
 * on a template.
 */
public class MakeLDIF
       implements EntryWriter
{
  /**
   * The fully-qualified name of this class.
   */
  private static final String CLASS_NAME =
       "org.opends.server.tools.makeldif.MakeLDIF";
 
  /** The LDIF writer that will be used to write the entries. */
  private LDIFWriter ldifWriter;
 
  /** The total number of entries that have been written. */
  private long entriesWritten;
 
  private PrintStream out = System.out;
  private PrintStream err = System.err;
 
  /**
   * Invokes the <CODE>makeLDIFMain</CODE> method with the provided set of
   * arguments.
   *
   * @param  args  The command-line arguments provided for this program.
   */
  public static void main(String[] args)
  {
    MakeLDIF makeLDIF = new MakeLDIF();
    int returnCode = makeLDIF.makeLDIFMain(args);
    if (returnCode != 0)
    {
      System.exit(filterExitCode(returnCode));
    }
  }
 
  /**
   * Provides the command-line arguments to the main application for
   * processing and returns the exit code as an integer.
   *
   * @param args
   *          The set of command-line arguments provided to this
   *          program.
   * @param outStream
   *          The output stream for standard output.
   * @param errStream
   *          The output stream for standard error.
   * @return Zero to indicate that the program completed successfully,
   *         or non-zero to indicate that an error occurred.
   */
  public static int main(final String[] args, final OutputStream outStream, final OutputStream errStream)
  {
    return new MakeLDIF().makeLDIFMain(args, false, false, outStream, errStream);
  }
 
  /**
   * Creates a new instance of this utility.  It should just be used for
   * invoking the <CODE>makeLDIFMain</CODE> method.
   */
  public MakeLDIF()
  {
    ldifWriter     = null;
    entriesWritten = 0L;
  }
 
  /**
   * Processes the provided set of command-line arguments and begins generating
   * the LDIF content.
   *
   * @param  args  The command-line arguments provided for this program.
   * @param  initializeServer  Indicates whether to initialize the server.
   * @param  initializeSchema  Indicates whether to initialize the schema.
   * @param  outStream         The output stream to use for standard output, or
   *                           {@code null} if standard output is not needed.
   * @param  errStream         The output stream to use for standard error, or
   *                           {@code null} if standard error is not needed.
   * @return  A result code of zero if all processing completed properly, or
   *          a nonzero result if a problem occurred.
   *
   */
  public int makeLDIFMain(String[] args, boolean initializeServer,
      boolean initializeSchema,
      OutputStream outStream,
      OutputStream errStream)
  {
    out = NullOutputStream.wrapOrNullStream(outStream);
    err = NullOutputStream.wrapOrNullStream(errStream);
    JDKLogging.disableLogging();
 
 
//  Create and initialize the argument parser for this program.
    LocalizableMessage toolDescription = INFO_MAKELDIF_TOOL_DESCRIPTION.get();
    ArgumentParser  argParser = new ArgumentParser(CLASS_NAME, toolDescription,
                                                   false);
    argParser.setShortToolDescription(REF_SHORT_DESC_MAKELDIF.get());
    argParser.setVersionHandler(new DirectoryServerVersionHandler());
 
    BooleanArgument showUsage;
    IntegerArgument randomSeed;
    StringArgument  configClass;
    StringArgument  configFile;
    StringArgument  templatePath;
    StringArgument  ldifFile;
    StringArgument  resourcePath;
 
    try
    {
      configFile = new StringArgument("configfile", 'c', "configFile", true,
                                      false, true,
                                      INFO_CONFIGFILE_PLACEHOLDER.get(), null,
                                      null,
                                      INFO_DESCRIPTION_CONFIG_FILE.get());
      configFile.setHidden(true);
      argParser.addArgument(configFile);
 
 
      configClass = new StringArgument("configclass", OPTION_SHORT_CONFIG_CLASS,
                                       OPTION_LONG_CONFIG_CLASS, false,
                                       false, true,
                                       INFO_CONFIGCLASS_PLACEHOLDER.get(), null,
                                       null,
                                       INFO_DESCRIPTION_CONFIG_CLASS.get());
      configClass.setHidden(true);
      argParser.addArgument(configClass);
 
 
      resourcePath =
           new StringArgument("resourcepath", 'r', "resourcePath", true, false,
                              true, INFO_PATH_PLACEHOLDER.get(), null, null,
                              INFO_MAKELDIF_DESCRIPTION_RESOURCE_PATH.get());
      resourcePath.setHidden(true);
      argParser.addArgument(resourcePath);
 
 
      templatePath =
              new StringArgument("templatefile", 't', "templateFile",
                                 true, false, true, INFO_FILE_PLACEHOLDER.get(),
                                 null, null,
                                 INFO_MAKELDIF_DESCRIPTION_TEMPLATE.get());
      argParser.addArgument(templatePath);
 
 
      ldifFile = new StringArgument("ldiffile", 'o', "ldifFile", true, false,
                                    true, INFO_FILE_PLACEHOLDER.get(), null,
                                    null, INFO_MAKELDIF_DESCRIPTION_LDIF.get());
      argParser.addArgument(ldifFile);
 
 
      randomSeed = new IntegerArgument("randomseed", OPTION_SHORT_RANDOM_SEED,
                                       OPTION_LONG_RANDOM_SEED, false,
                                       false, true, INFO_SEED_PLACEHOLDER.get(),
                                       0, null,
                                       INFO_MAKELDIF_DESCRIPTION_SEED.get());
      argParser.addArgument(randomSeed);
 
 
      showUsage = CommonArguments.getShowUsage();
      argParser.addArgument(showUsage);
      argParser.setUsageArgument(showUsage);
    }
    catch (ArgumentException ae)
    {
      printWrappedText(err, ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage()));
      return 1;
    }
 
 
    // Parse the command-line arguments provided to the program.
    try
    {
      argParser.parseArguments(args);
    }
    catch (ArgumentException ae)
    {
      argParser.displayMessageAndUsageReference(err, ERR_ERROR_PARSING_ARGS.get(ae.getMessage()));
      return 1;
    }
 
 
    // If we should just display usage or version information,
    // then print it and exit.
    if (argParser.usageOrVersionDisplayed())
    {
      return 0;
    }
 
    // Checks the version - if upgrade required, the tool is unusable
    try
    {
      BuildVersion.checkVersionMismatch();
    }
    catch (InitializationException e)
    {
      printWrappedText(err, e.getMessage());
      return 1;
    }
 
    if (initializeServer)
    {
      // Initialize the Directory Server configuration handler using the
      // information that was provided.
      DirectoryServer directoryServer = DirectoryServer.getInstance();
      DirectoryServer.bootstrapClient();
 
      try
      {
        DirectoryServer.initializeJMX();
      }
      catch (Exception e)
      {
        printWrappedText(err, ERR_MAKELDIF_CANNOT_INITIALIZE_JMX.get(configFile.getValue(), e.getMessage()));
        return 1;
      }
 
      try
      {
        directoryServer.initializeConfiguration(configClass.getValue(),
            configFile.getValue());
      }
      catch (Exception e)
      {
        printWrappedText(err, ERR_MAKELDIF_CANNOT_INITIALIZE_CONFIG.get(configFile.getValue(), e.getMessage()));
        return 1;
      }
    }
 
    if (initializeSchema)
    {
      try
      {
        DirectoryServer.getInstance().initializeSchema();
      }
      catch (Exception e)
      {
        printWrappedText(err, ERR_MAKELDIF_CANNOT_INITIALIZE_SCHEMA.get(configFile.getValue(), e.getMessage()));
        return 1;
      }
    }
 
 
    // Create the random number generator that will be used for the generation
    // process.
    Random random;
    if (randomSeed.isPresent())
    {
      try
      {
        random = new Random(randomSeed.getIntValue());
      }
      catch (Exception e)
      {
        random = new Random();
      }
    }
    else
    {
      random = new Random();
    }
 
 
    // If a resource path was provided, then make sure it's acceptable.
    File resourceDir = new File(resourcePath.getValue());
    if (! resourceDir.exists())
    {
      printWrappedText(err, ERR_MAKELDIF_NO_SUCH_RESOURCE_DIRECTORY.get(resourcePath.getValue()));
      return 1;
    }
 
 
    // Load and parse the template file.
    LinkedList<LocalizableMessage> warnings = new LinkedList<>();
    TemplateFile templateFile = new TemplateFile(resourcePath.getValue(), random);
    try
    {
      templateFile.parse(templatePath.getValue(), warnings);
    }
    catch (IOException ioe)
    {
      printWrappedText(err, ERR_MAKELDIF_IOEXCEPTION_DURING_PARSE.get(ioe.getMessage()));
      return 1;
    }
    catch (Exception e)
    {
      printWrappedText(err, ERR_MAKELDIF_EXCEPTION_DURING_PARSE.get(e.getMessage()));
      return 1;
    }
 
 
    // If there were any warnings, then print them.
    if (! warnings.isEmpty())
    {
      for (LocalizableMessage s : warnings)
      {
        printWrappedText(err, s);
      }
    }
 
 
    // Create the LDIF writer that will be used to actually write the LDIF.
    LDIFExportConfig exportConfig =
         new LDIFExportConfig(ldifFile.getValue(),
                              ExistingFileBehavior.OVERWRITE);
    try
    {
      ldifWriter = new LDIFWriter(exportConfig);
    }
    catch (IOException ioe)
    {
      printWrappedText(err, ERR_MAKELDIF_UNABLE_TO_CREATE_LDIF.get(ldifFile.getValue(), ioe));
      return 1;
    }
 
 
    // Generate the LDIF content.
    try
    {
      templateFile.generateLDIF(this);
    }
    catch (Exception e)
    {
      printWrappedText(err, ERR_MAKELDIF_ERROR_WRITING_LDIF.get(ldifFile.getValue(), stackTraceToSingleLineString(e)));
      return 1;
    }
    finally
    {
      close(ldifWriter);
    }
 
 
    // If we've gotten here, then everything was successful.
    return 0;
  }
 
 
  /**
   * Processes the provided set of command-line arguments and begins generating
   * the LDIF content.
   *
   * @param  args  The command-line arguments provided for this program.
   *
   * @return  A result code of zero if all processing completed properly, or
   *          a nonzero result if a problem occurred.
   */
  public int makeLDIFMain(String[] args)
  {
     return makeLDIFMain(args, true, true, System.out, System.err);
  }
 
 
 
  /**
   * Writes the provided entry to the appropriate target.
   *
   * @param  entry  The entry to be written.
   *
   * @return  <CODE>true</CODE> if the entry writer will accept more entries, or
   *          <CODE>false</CODE> if not.
   *
   * @throws  IOException  If a problem occurs while writing the entry to its
   *                       intended destination.
   *
   * @throws  MakeLDIFException  If some other problem occurs.
   */
  @Override
  public boolean writeEntry(TemplateEntry entry)
         throws IOException, MakeLDIFException
  {
    try
    {
      if (entry.getDN() != null)
      {
        ldifWriter.writeTemplateEntry(entry);
 
        if ((++entriesWritten % 1000) == 0)
        {
          printWrappedText(out, INFO_MAKELDIF_PROCESSED_N_ENTRIES.get(entriesWritten));
        }
      }
      else
      {
        AttributeType[] rdnAttrs = entry.getTemplate().getRDNAttributes();
        String nullRdn = "";
        for (AttributeType att : rdnAttrs)
        {
          if (entry.getValue(att) == null)
          {
            nullRdn = att.getNameOrOID();
            break ;
          }
        }
        printWrappedText(err, ERR_MAKELDIF_CANNOT_WRITE_ENTRY_WITHOUT_DN.get(nullRdn));
        return true;
      }
 
      return true;
    }
    catch (IOException ioe)
    {
      throw ioe;
    }
    catch (Exception e)
    {
      LocalizableMessage message = ERR_MAKELDIF_CANNOT_WRITE_ENTRY.get(
          entry.getDN(), stackTraceToSingleLineString(e));
      throw new MakeLDIFException(message, e);
    }
  }
 
 
 
  /**
   * Notifies the entry writer that no more entries will be provided and that
   * any associated cleanup may be performed.
   */
  @Override
  public void closeEntryWriter()
  {
    printWrappedText(out, INFO_MAKELDIF_PROCESSING_COMPLETE.get(entriesWritten));
  }
}