001/* 002 * Copyright 2008-2018 Ping Identity Corporation 003 * All Rights Reserved. 004 */ 005/* 006 * Copyright (C) 2008-2018 Ping Identity Corporation 007 * 008 * This program is free software; you can redistribute it and/or modify 009 * it under the terms of the GNU General Public License (GPLv2 only) 010 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only) 011 * as published by the Free Software Foundation. 012 * 013 * This program is distributed in the hope that it will be useful, 014 * but WITHOUT ANY WARRANTY; without even the implied warranty of 015 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 016 * GNU General Public License for more details. 017 * 018 * You should have received a copy of the GNU General Public License 019 * along with this program; if not, see <http://www.gnu.org/licenses>. 020 */ 021package com.unboundid.ldap.sdk.examples; 022 023 024 025import java.io.File; 026import java.io.FileInputStream; 027import java.io.InputStream; 028import java.io.IOException; 029import java.io.OutputStream; 030import java.util.ArrayList; 031import java.util.Iterator; 032import java.util.TreeMap; 033import java.util.LinkedHashMap; 034import java.util.List; 035import java.util.concurrent.atomic.AtomicLong; 036import java.util.zip.GZIPInputStream; 037 038import com.unboundid.ldap.sdk.Entry; 039import com.unboundid.ldap.sdk.LDAPConnection; 040import com.unboundid.ldap.sdk.LDAPException; 041import com.unboundid.ldap.sdk.ResultCode; 042import com.unboundid.ldap.sdk.Version; 043import com.unboundid.ldap.sdk.schema.Schema; 044import com.unboundid.ldap.sdk.schema.EntryValidator; 045import com.unboundid.ldap.sdk.unboundidds.tools.ToolUtils; 046import com.unboundid.ldif.DuplicateValueBehavior; 047import com.unboundid.ldif.LDIFException; 048import com.unboundid.ldif.LDIFReader; 049import com.unboundid.ldif.LDIFReaderEntryTranslator; 050import com.unboundid.ldif.LDIFWriter; 051import com.unboundid.util.Debug; 052import com.unboundid.util.LDAPCommandLineTool; 053import com.unboundid.util.ThreadSafety; 054import com.unboundid.util.ThreadSafetyLevel; 055import com.unboundid.util.args.ArgumentException; 056import com.unboundid.util.args.ArgumentParser; 057import com.unboundid.util.args.BooleanArgument; 058import com.unboundid.util.args.FileArgument; 059import com.unboundid.util.args.IntegerArgument; 060import com.unboundid.util.args.StringArgument; 061 062import static com.unboundid.util.StaticUtils.*; 063 064 065 066/** 067 * This class provides a simple tool that can be used to validate that the 068 * contents of an LDIF file are valid. This includes ensuring that the contents 069 * can be parsed as valid LDIF, and it can also ensure that the LDIF content 070 * conforms to the server schema. It will obtain the schema by connecting to 071 * the server and retrieving the default schema (i.e., the schema which governs 072 * the root DSE). By default, a thorough set of validation will be performed, 073 * but it is possible to disable certain types of validation. 074 * <BR><BR> 075 * Some of the APIs demonstrated by this example include: 076 * <UL> 077 * <LI>Argument Parsing (from the {@code com.unboundid.util.args} 078 * package)</LI> 079 * <LI>LDAP Command-Line Tool (from the {@code com.unboundid.util} 080 * package)</LI> 081 * <LI>LDIF Processing (from the {@code com.unboundid.ldif} package)</LI> 082 * <LI>Schema Parsing (from the {@code com.unboundid.ldap.sdk.schema} 083 * package)</LI> 084 * </UL> 085 * <BR><BR> 086 * Supported arguments include those allowed by the {@link LDAPCommandLineTool} 087 * class (to obtain the information to use to connect to the server to read the 088 * schema), as well as the following additional arguments: 089 * <UL> 090 * <LI>"--schemaDirectory {path}" -- specifies the path to a directory 091 * containing files with schema definitions. If this argument is 092 * provided, then no attempt will be made to communicate with a directory 093 * server.</LI> 094 * <LI>"-f {path}" or "--ldifFile {path}" -- specifies the path to the LDIF 095 * file to be validated.</LI> 096 * <LI>"-c" or "--isCompressed" -- indicates that the LDIF file is 097 * compressed.</LI> 098 * <LI>"-R {path}" or "--rejectFile {path}" -- specifies the path to the file 099 * to be written with information about all entries that failed 100 * validation.</LI> 101 * <LI>"-t {num}" or "--numThreads {num}" -- specifies the number of 102 * concurrent threads to use when processing the LDIF. If this is not 103 * provided, then a default of one thread will be used.</LI> 104 * <LI>"--ignoreUndefinedObjectClasses" -- indicates that the validation 105 * process should ignore validation failures due to entries that contain 106 * object classes not defined in the server schema.</LI> 107 * <LI>"--ignoreUndefinedAttributes" -- indicates that the validation process 108 * should ignore validation failures due to entries that contain 109 * attributes not defined in the server schema.</LI> 110 * <LI>"--ignoreMalformedDNs" -- indicates that the validation process should 111 * ignore validation failures due to entries with malformed DNs.</LI> 112 * <LI>"--ignoreMissingRDNValues" -- indicates that the validation process 113 * should ignore validation failures due to entries that contain an RDN 114 * attribute value that is not present in the set of entry 115 * attributes.</LI> 116 * <LI>"--ignoreStructuralObjectClasses" -- indicates that the validation 117 * process should ignore validation failures due to entries that either do 118 * not have a structural object class or that have multiple structural 119 * object classes.</LI> 120 * <LI>"--ignoreProhibitedObjectClasses" -- indicates that the validation 121 * process should ignore validation failures due to entries containing 122 * auxiliary classes that are not allowed by a DIT content rule, or 123 * abstract classes that are not subclassed by an auxiliary or structural 124 * class contained in the entry.</LI> 125 * <LI>"--ignoreProhibitedAttributes" -- indicates that the validation process 126 * should ignore validation failures due to entries including attributes 127 * that are not allowed or are explicitly prohibited by a DIT content 128 * rule.</LI> 129 * <LI>"--ignoreMissingAttributes" -- indicates that the validation process 130 * should ignore validation failures due to entries missing required 131 * attributes.</LI> 132 * <LI>"--ignoreSingleValuedAttributes" -- indicates that the validation 133 * process should ignore validation failures due to single-valued 134 * attributes containing multiple values.</LI> 135 * <LI>"--ignoreAttributeSyntax" -- indicates that the validation process 136 * should ignore validation failures due to attribute values which violate 137 * the associated attribute syntax.</LI> 138 * <LI>"--ignoreSyntaxViolationsForAttribute" -- indicates that the validation 139 * process should ignore validation failures due to attribute values which 140 * violate the associated attribute syntax, but only for the specified 141 * attribute types.</LI> 142 * <LI>"--ignoreNameForms" -- indicates that the validation process should 143 * ignore validation failures due to name form violations (in which the 144 * entry's RDN does not comply with the associated name form).</LI> 145 * </UL> 146 */ 147@ThreadSafety(level=ThreadSafetyLevel.NOT_THREADSAFE) 148public final class ValidateLDIF 149 extends LDAPCommandLineTool 150 implements LDIFReaderEntryTranslator 151{ 152 /** 153 * The end-of-line character for this platform. 154 */ 155 private static final String EOL = System.getProperty("line.separator", "\n"); 156 157 158 159 // The arguments used by this program. 160 private BooleanArgument ignoreDuplicateValues; 161 private BooleanArgument ignoreUndefinedObjectClasses; 162 private BooleanArgument ignoreUndefinedAttributes; 163 private BooleanArgument ignoreMalformedDNs; 164 private BooleanArgument ignoreMissingRDNValues; 165 private BooleanArgument ignoreMissingSuperiorObjectClasses; 166 private BooleanArgument ignoreStructuralObjectClasses; 167 private BooleanArgument ignoreProhibitedObjectClasses; 168 private BooleanArgument ignoreProhibitedAttributes; 169 private BooleanArgument ignoreMissingAttributes; 170 private BooleanArgument ignoreSingleValuedAttributes; 171 private BooleanArgument ignoreAttributeSyntax; 172 private BooleanArgument ignoreNameForms; 173 private BooleanArgument isCompressed; 174 private FileArgument schemaDirectory; 175 private FileArgument ldifFile; 176 private FileArgument rejectFile; 177 private FileArgument encryptionPassphraseFile; 178 private IntegerArgument numThreads; 179 private StringArgument ignoreSyntaxViolationsForAttribute; 180 181 // The counter used to keep track of the number of entries processed. 182 private final AtomicLong entriesProcessed = new AtomicLong(0L); 183 184 // The counter used to keep track of the number of entries that could not be 185 // parsed as valid entries. 186 private final AtomicLong malformedEntries = new AtomicLong(0L); 187 188 // The entry validator that will be used to validate the entries. 189 private EntryValidator entryValidator; 190 191 // The LDIF writer that will be used to write rejected entries. 192 private LDIFWriter rejectWriter; 193 194 195 196 /** 197 * Parse the provided command line arguments and make the appropriate set of 198 * changes. 199 * 200 * @param args The command line arguments provided to this program. 201 */ 202 public static void main(final String[] args) 203 { 204 final ResultCode resultCode = main(args, System.out, System.err); 205 if (resultCode != ResultCode.SUCCESS) 206 { 207 System.exit(resultCode.intValue()); 208 } 209 } 210 211 212 213 /** 214 * Parse the provided command line arguments and make the appropriate set of 215 * changes. 216 * 217 * @param args The command line arguments provided to this program. 218 * @param outStream The output stream to which standard out should be 219 * written. It may be {@code null} if output should be 220 * suppressed. 221 * @param errStream The output stream to which standard error should be 222 * written. It may be {@code null} if error messages 223 * should be suppressed. 224 * 225 * @return A result code indicating whether the processing was successful. 226 */ 227 public static ResultCode main(final String[] args, 228 final OutputStream outStream, 229 final OutputStream errStream) 230 { 231 final ValidateLDIF validateLDIF = new ValidateLDIF(outStream, errStream); 232 return validateLDIF.runTool(args); 233 } 234 235 236 237 /** 238 * Creates a new instance of this tool. 239 * 240 * @param outStream The output stream to which standard out should be 241 * written. It may be {@code null} if output should be 242 * suppressed. 243 * @param errStream The output stream to which standard error should be 244 * written. It may be {@code null} if error messages 245 * should be suppressed. 246 */ 247 public ValidateLDIF(final OutputStream outStream, 248 final OutputStream errStream) 249 { 250 super(outStream, errStream); 251 } 252 253 254 255 /** 256 * Retrieves the name for this tool. 257 * 258 * @return The name for this tool. 259 */ 260 @Override() 261 public String getToolName() 262 { 263 return "validate-ldif"; 264 } 265 266 267 268 /** 269 * Retrieves the description for this tool. 270 * 271 * @return The description for this tool. 272 */ 273 @Override() 274 public String getToolDescription() 275 { 276 return "Validate the contents of an LDIF file " + 277 "against the server schema."; 278 } 279 280 281 282 /** 283 * Retrieves the version string for this tool. 284 * 285 * @return The version string for this tool. 286 */ 287 @Override() 288 public String getToolVersion() 289 { 290 return Version.NUMERIC_VERSION_STRING; 291 } 292 293 294 295 /** 296 * Indicates whether this tool should provide support for an interactive mode, 297 * in which the tool offers a mode in which the arguments can be provided in 298 * a text-driven menu rather than requiring them to be given on the command 299 * line. If interactive mode is supported, it may be invoked using the 300 * "--interactive" argument. Alternately, if interactive mode is supported 301 * and {@link #defaultsToInteractiveMode()} returns {@code true}, then 302 * interactive mode may be invoked by simply launching the tool without any 303 * arguments. 304 * 305 * @return {@code true} if this tool supports interactive mode, or 306 * {@code false} if not. 307 */ 308 @Override() 309 public boolean supportsInteractiveMode() 310 { 311 return true; 312 } 313 314 315 316 /** 317 * Indicates whether this tool defaults to launching in interactive mode if 318 * the tool is invoked without any command-line arguments. This will only be 319 * used if {@link #supportsInteractiveMode()} returns {@code true}. 320 * 321 * @return {@code true} if this tool defaults to using interactive mode if 322 * launched without any command-line arguments, or {@code false} if 323 * not. 324 */ 325 @Override() 326 public boolean defaultsToInteractiveMode() 327 { 328 return true; 329 } 330 331 332 333 /** 334 * Indicates whether this tool should provide arguments for redirecting output 335 * to a file. If this method returns {@code true}, then the tool will offer 336 * an "--outputFile" argument that will specify the path to a file to which 337 * all standard output and standard error content will be written, and it will 338 * also offer a "--teeToStandardOut" argument that can only be used if the 339 * "--outputFile" argument is present and will cause all output to be written 340 * to both the specified output file and to standard output. 341 * 342 * @return {@code true} if this tool should provide arguments for redirecting 343 * output to a file, or {@code false} if not. 344 */ 345 @Override() 346 protected boolean supportsOutputFile() 347 { 348 return true; 349 } 350 351 352 353 /** 354 * Indicates whether this tool should default to interactively prompting for 355 * the bind password if a password is required but no argument was provided 356 * to indicate how to get the password. 357 * 358 * @return {@code true} if this tool should default to interactively 359 * prompting for the bind password, or {@code false} if not. 360 */ 361 @Override() 362 protected boolean defaultToPromptForBindPassword() 363 { 364 return true; 365 } 366 367 368 369 /** 370 * Indicates whether this tool supports the use of a properties file for 371 * specifying default values for arguments that aren't specified on the 372 * command line. 373 * 374 * @return {@code true} if this tool supports the use of a properties file 375 * for specifying default values for arguments that aren't specified 376 * on the command line, or {@code false} if not. 377 */ 378 @Override() 379 public boolean supportsPropertiesFile() 380 { 381 return true; 382 } 383 384 385 386 /** 387 * Indicates whether the LDAP-specific arguments should include alternate 388 * versions of all long identifiers that consist of multiple words so that 389 * they are available in both camelCase and dash-separated versions. 390 * 391 * @return {@code true} if this tool should provide multiple versions of 392 * long identifiers for LDAP-specific arguments, or {@code false} if 393 * not. 394 */ 395 @Override() 396 protected boolean includeAlternateLongIdentifiers() 397 { 398 return true; 399 } 400 401 402 403 /** 404 * Adds the arguments used by this program that aren't already provided by the 405 * generic {@code LDAPCommandLineTool} framework. 406 * 407 * @param parser The argument parser to which the arguments should be added. 408 * 409 * @throws ArgumentException If a problem occurs while adding the arguments. 410 */ 411 @Override() 412 public void addNonLDAPArguments(final ArgumentParser parser) 413 throws ArgumentException 414 { 415 String description = "The path to the LDIF file to process. The tool " + 416 "will automatically attempt to detect whether the file is " + 417 "encrypted or compressed."; 418 ldifFile = new FileArgument('f', "ldifFile", true, 1, "{path}", description, 419 true, true, true, false); 420 ldifFile.addLongIdentifier("ldif-file", true); 421 parser.addArgument(ldifFile); 422 423 424 // Add an argument that makes it possible to read a compressed LDIF file. 425 // Note that this argument is no longer needed for dealing with compressed 426 // files, since the tool will automatically detect whether a file is 427 // compressed. However, the argument is still provided for the purpose of 428 // backward compatibility. 429 description = "Indicates that the specified LDIF file is compressed " + 430 "using gzip compression."; 431 isCompressed = new BooleanArgument('c', "isCompressed", description); 432 isCompressed.addLongIdentifier("is-compressed", true); 433 isCompressed.setHidden(true); 434 parser.addArgument(isCompressed); 435 436 437 // Add an argument that indicates that the tool should read the encryption 438 // passphrase from a file. 439 description = "Indicates that the specified LDIF file is encrypted and " + 440 "that the encryption passphrase is contained in the specified " + 441 "file. If the LDIF data is encrypted and this argument is not " + 442 "provided, then the tool will interactively prompt for the " + 443 "encryption passphrase."; 444 encryptionPassphraseFile = new FileArgument(null, 445 "encryptionPassphraseFile", false, 1, null, description, true, true, 446 true, false); 447 encryptionPassphraseFile.addLongIdentifier("encryption-passphrase-file", 448 true); 449 encryptionPassphraseFile.addLongIdentifier("encryptionPasswordFile", true); 450 encryptionPassphraseFile.addLongIdentifier("encryption-password-file", 451 true); 452 parser.addArgument(encryptionPassphraseFile); 453 454 455 description = "The path to the file to which rejected entries should be " + 456 "written."; 457 rejectFile = new FileArgument('R', "rejectFile", false, 1, "{path}", 458 description, false, true, true, false); 459 rejectFile.addLongIdentifier("reject-file", true); 460 parser.addArgument(rejectFile); 461 462 description = "The path to a directory containing one or more LDIF files " + 463 "with the schema information to use. If this is provided, " + 464 "then no LDAP communication will be performed."; 465 schemaDirectory = new FileArgument(null, "schemaDirectory", false, 1, 466 "{path}", description, true, true, false, true); 467 schemaDirectory.addLongIdentifier("schema-directory", true); 468 parser.addArgument(schemaDirectory); 469 470 description = "The number of threads to use when processing the LDIF file."; 471 numThreads = new IntegerArgument('t', "numThreads", true, 1, "{num}", 472 description, 1, Integer.MAX_VALUE, 1); 473 numThreads.addLongIdentifier("num-threads", true); 474 parser.addArgument(numThreads); 475 476 description = "Ignore validation failures due to entries containing " + 477 "duplicate values for the same attribute."; 478 ignoreDuplicateValues = 479 new BooleanArgument(null, "ignoreDuplicateValues", description); 480 ignoreDuplicateValues.setArgumentGroupName( 481 "Validation Strictness Arguments"); 482 ignoreDuplicateValues.addLongIdentifier("ignore-duplicate-values", true); 483 parser.addArgument(ignoreDuplicateValues); 484 485 description = "Ignore validation failures due to object classes not " + 486 "defined in the schema."; 487 ignoreUndefinedObjectClasses = 488 new BooleanArgument(null, "ignoreUndefinedObjectClasses", description); 489 ignoreUndefinedObjectClasses.setArgumentGroupName( 490 "Validation Strictness Arguments"); 491 ignoreUndefinedObjectClasses.addLongIdentifier( 492 "ignore-undefined-object-classes", true); 493 parser.addArgument(ignoreUndefinedObjectClasses); 494 495 description = "Ignore validation failures due to attributes not defined " + 496 "in the schema."; 497 ignoreUndefinedAttributes = 498 new BooleanArgument(null, "ignoreUndefinedAttributes", description); 499 ignoreUndefinedAttributes.setArgumentGroupName( 500 "Validation Strictness Arguments"); 501 ignoreUndefinedAttributes.addLongIdentifier("ignore-undefined-attributes", 502 true); 503 parser.addArgument(ignoreUndefinedAttributes); 504 505 description = "Ignore validation failures due to entries with malformed " + 506 "DNs."; 507 ignoreMalformedDNs = 508 new BooleanArgument(null, "ignoreMalformedDNs", description); 509 ignoreMalformedDNs.setArgumentGroupName("Validation Strictness Arguments"); 510 ignoreMalformedDNs.addLongIdentifier("ignore-malformed-dns", true); 511 parser.addArgument(ignoreMalformedDNs); 512 513 description = "Ignore validation failures due to entries with RDN " + 514 "attribute values that are missing from the set of entry " + 515 "attributes."; 516 ignoreMissingRDNValues = 517 new BooleanArgument(null, "ignoreMissingRDNValues", description); 518 ignoreMissingRDNValues.setArgumentGroupName( 519 "Validation Strictness Arguments"); 520 ignoreMissingRDNValues.addLongIdentifier("ignore-missing-rdn-values", true); 521 parser.addArgument(ignoreMissingRDNValues); 522 523 description = "Ignore validation failures due to entries without exactly " + 524 "structural object class."; 525 ignoreStructuralObjectClasses = 526 new BooleanArgument(null, "ignoreStructuralObjectClasses", 527 description); 528 ignoreStructuralObjectClasses.setArgumentGroupName( 529 "Validation Strictness Arguments"); 530 ignoreStructuralObjectClasses.addLongIdentifier( 531 "ignore-structural-object-classes", true); 532 parser.addArgument(ignoreStructuralObjectClasses); 533 534 description = "Ignore validation failures due to entries with object " + 535 "classes that are not allowed."; 536 ignoreProhibitedObjectClasses = 537 new BooleanArgument(null, "ignoreProhibitedObjectClasses", 538 description); 539 ignoreProhibitedObjectClasses.setArgumentGroupName( 540 "Validation Strictness Arguments"); 541 ignoreProhibitedObjectClasses.addLongIdentifier( 542 "ignore-prohibited-object-classes", true); 543 parser.addArgument(ignoreProhibitedObjectClasses); 544 545 description = "Ignore validation failures due to entries that are " + 546 "one or more superior object classes."; 547 ignoreMissingSuperiorObjectClasses = 548 new BooleanArgument(null, "ignoreMissingSuperiorObjectClasses", 549 description); 550 ignoreMissingSuperiorObjectClasses.setArgumentGroupName( 551 "Validation Strictness Arguments"); 552 ignoreMissingSuperiorObjectClasses.addLongIdentifier( 553 "ignore-missing-superior-object-classes", true); 554 parser.addArgument(ignoreMissingSuperiorObjectClasses); 555 556 description = "Ignore validation failures due to entries with attributes " + 557 "that are not allowed."; 558 ignoreProhibitedAttributes = 559 new BooleanArgument(null, "ignoreProhibitedAttributes", description); 560 ignoreProhibitedAttributes.setArgumentGroupName( 561 "Validation Strictness Arguments"); 562 ignoreProhibitedAttributes.addLongIdentifier( 563 "ignore-prohibited-attributes", true); 564 parser.addArgument(ignoreProhibitedAttributes); 565 566 description = "Ignore validation failures due to entries missing " + 567 "required attributes."; 568 ignoreMissingAttributes = 569 new BooleanArgument(null, "ignoreMissingAttributes", description); 570 ignoreMissingAttributes.setArgumentGroupName( 571 "Validation Strictness Arguments"); 572 ignoreMissingAttributes.addLongIdentifier("ignore-missing-attributes", 573 true); 574 parser.addArgument(ignoreMissingAttributes); 575 576 description = "Ignore validation failures due to entries with multiple " + 577 "values for single-valued attributes."; 578 ignoreSingleValuedAttributes = 579 new BooleanArgument(null, "ignoreSingleValuedAttributes", description); 580 ignoreSingleValuedAttributes.setArgumentGroupName( 581 "Validation Strictness Arguments"); 582 ignoreSingleValuedAttributes.addLongIdentifier( 583 "ignore-single-valued-attributes", true); 584 parser.addArgument(ignoreSingleValuedAttributes); 585 586 description = "Ignore validation failures due to entries with attribute " + 587 "values that violate their associated syntax. If this is " + 588 "provided, then no attribute syntax violations will be " + 589 "flagged. If this is not provided, then all attribute " + 590 "syntax violations will be flagged except for violations " + 591 "in those attributes excluded by the " + 592 "--ignoreSyntaxViolationsForAttribute argument."; 593 ignoreAttributeSyntax = 594 new BooleanArgument(null, "ignoreAttributeSyntax", description); 595 ignoreAttributeSyntax.setArgumentGroupName( 596 "Validation Strictness Arguments"); 597 ignoreAttributeSyntax.addLongIdentifier("ignore-attribute-syntax", true); 598 parser.addArgument(ignoreAttributeSyntax); 599 600 description = "The name or OID of an attribute for which to ignore " + 601 "validation failures due to violations of the associated " + 602 "attribute syntax. This argument can only be used if the " + 603 "--ignoreAttributeSyntax argument is not provided."; 604 ignoreSyntaxViolationsForAttribute = new StringArgument(null, 605 "ignoreSyntaxViolationsForAttribute", false, 0, "{attr}", description); 606 ignoreSyntaxViolationsForAttribute.setArgumentGroupName( 607 "Validation Strictness Arguments"); 608 ignoreSyntaxViolationsForAttribute.addLongIdentifier( 609 "ignore-syntax-violations-for-attribute", true); 610 parser.addArgument(ignoreSyntaxViolationsForAttribute); 611 612 description = "Ignore validation failures due to entries with RDNs " + 613 "that violate the associated name form definition."; 614 ignoreNameForms = new BooleanArgument(null, "ignoreNameForms", description); 615 ignoreNameForms.setArgumentGroupName("Validation Strictness Arguments"); 616 ignoreNameForms.addLongIdentifier("ignore-name-forms", true); 617 parser.addArgument(ignoreNameForms); 618 619 620 // The ignoreAttributeSyntax and ignoreAttributeSyntaxForAttribute arguments 621 // cannot be used together. 622 parser.addExclusiveArgumentSet(ignoreAttributeSyntax, 623 ignoreSyntaxViolationsForAttribute); 624 } 625 626 627 628 /** 629 * Performs the actual processing for this tool. In this case, it gets a 630 * connection to the directory server and uses it to retrieve the server 631 * schema. It then reads the LDIF file and validates each entry accordingly. 632 * 633 * @return The result code for the processing that was performed. 634 */ 635 @Override() 636 public ResultCode doToolProcessing() 637 { 638 // Get the connection to the directory server and use it to read the schema. 639 final Schema schema; 640 if (schemaDirectory.isPresent()) 641 { 642 final File schemaDir = schemaDirectory.getValue(); 643 644 try 645 { 646 final TreeMap<String,File> fileMap = new TreeMap<String,File>(); 647 for (final File f : schemaDir.listFiles()) 648 { 649 final String name = f.getName(); 650 if (f.isFile() && name.endsWith(".ldif")) 651 { 652 fileMap.put(name, f); 653 } 654 } 655 656 if (fileMap.isEmpty()) 657 { 658 err("No LDIF files found in directory " + 659 schemaDir.getAbsolutePath()); 660 return ResultCode.PARAM_ERROR; 661 } 662 663 final ArrayList<File> fileList = new ArrayList<File>(fileMap.values()); 664 schema = Schema.getSchema(fileList); 665 } 666 catch (final Exception e) 667 { 668 Debug.debugException(e); 669 err("Unable to read schema from files in directory " + 670 schemaDir.getAbsolutePath() + ": " + getExceptionMessage(e)); 671 return ResultCode.LOCAL_ERROR; 672 } 673 } 674 else 675 { 676 try 677 { 678 final LDAPConnection connection = getConnection(); 679 schema = connection.getSchema(); 680 connection.close(); 681 } 682 catch (final LDAPException le) 683 { 684 Debug.debugException(le); 685 err("Unable to connect to the directory server and read the schema: ", 686 le.getMessage()); 687 return le.getResultCode(); 688 } 689 } 690 691 692 // Get the encryption passphrase, if it was provided. 693 String encryptionPassphrase = null; 694 if (encryptionPassphraseFile.isPresent()) 695 { 696 try 697 { 698 encryptionPassphrase = ToolUtils.readEncryptionPassphraseFromFile( 699 encryptionPassphraseFile.getValue()); 700 } 701 catch (final LDAPException e) 702 { 703 Debug.debugException(e); 704 err(e.getMessage()); 705 return e.getResultCode(); 706 } 707 } 708 709 710 // Create the entry validator and initialize its configuration. 711 entryValidator = new EntryValidator(schema); 712 entryValidator.setCheckAttributeSyntax(!ignoreAttributeSyntax.isPresent()); 713 entryValidator.setCheckMalformedDNs(!ignoreMalformedDNs.isPresent()); 714 entryValidator.setCheckEntryMissingRDNValues( 715 !ignoreMissingRDNValues.isPresent()); 716 entryValidator.setCheckMissingAttributes( 717 !ignoreMissingAttributes.isPresent()); 718 entryValidator.setCheckNameForms(!ignoreNameForms.isPresent()); 719 entryValidator.setCheckProhibitedAttributes( 720 !ignoreProhibitedAttributes.isPresent()); 721 entryValidator.setCheckProhibitedObjectClasses( 722 !ignoreProhibitedObjectClasses.isPresent()); 723 entryValidator.setCheckMissingSuperiorObjectClasses( 724 !ignoreMissingSuperiorObjectClasses.isPresent()); 725 entryValidator.setCheckSingleValuedAttributes( 726 !ignoreSingleValuedAttributes.isPresent()); 727 entryValidator.setCheckStructuralObjectClasses( 728 !ignoreStructuralObjectClasses.isPresent()); 729 entryValidator.setCheckUndefinedAttributes( 730 !ignoreUndefinedAttributes.isPresent()); 731 entryValidator.setCheckUndefinedObjectClasses( 732 !ignoreUndefinedObjectClasses.isPresent()); 733 734 if (ignoreSyntaxViolationsForAttribute.isPresent()) 735 { 736 entryValidator.setIgnoreSyntaxViolationAttributeTypes( 737 ignoreSyntaxViolationsForAttribute.getValues()); 738 } 739 740 741 // Create an LDIF reader that can be used to read through the LDIF file. 742 final LDIFReader ldifReader; 743 rejectWriter = null; 744 try 745 { 746 InputStream inputStream = new FileInputStream(ldifFile.getValue()); 747 748 inputStream = ToolUtils.getPossiblyPassphraseEncryptedInputStream( 749 inputStream, encryptionPassphrase, false, 750 "LDIF file '" + ldifFile.getValue().getPath() + 751 "' is encrypted. Please enter the encryption passphrase:", 752 "ERROR: The provided passphrase was incorrect.", 753 getOut(), getErr()).getFirst(); 754 755 if (isCompressed.isPresent()) 756 { 757 inputStream = new GZIPInputStream(inputStream); 758 } 759 else 760 { 761 inputStream = 762 ToolUtils.getPossiblyGZIPCompressedInputStream(inputStream); 763 } 764 765 ldifReader = new LDIFReader(inputStream, numThreads.getValue(), this); 766 } 767 catch (final Exception e) 768 { 769 Debug.debugException(e); 770 err("Unable to open the LDIF reader: ", getExceptionMessage(e)); 771 return ResultCode.LOCAL_ERROR; 772 } 773 774 ldifReader.setSchema(schema); 775 if (ignoreDuplicateValues.isPresent()) 776 { 777 ldifReader.setDuplicateValueBehavior(DuplicateValueBehavior.STRIP); 778 } 779 else 780 { 781 ldifReader.setDuplicateValueBehavior(DuplicateValueBehavior.REJECT); 782 } 783 784 try 785 { 786 // Create an LDIF writer that can be used to write information about 787 // rejected entries. 788 try 789 { 790 if (rejectFile.isPresent()) 791 { 792 rejectWriter = new LDIFWriter(rejectFile.getValue()); 793 } 794 } 795 catch (final Exception e) 796 { 797 Debug.debugException(e); 798 err("Unable to create the reject writer: ", getExceptionMessage(e)); 799 return ResultCode.LOCAL_ERROR; 800 } 801 802 ResultCode resultCode = ResultCode.SUCCESS; 803 while (true) 804 { 805 try 806 { 807 final Entry e = ldifReader.readEntry(); 808 if (e == null) 809 { 810 // Because we're performing parallel processing and returning null 811 // from the translate method, LDIFReader.readEntry() should never 812 // return a non-null value. However, it can throw an LDIFException 813 // if it encounters an invalid entry, or an IOException if there's 814 // a problem reading from the file, so we should still iterate 815 // through all of the entries to catch and report on those problems. 816 break; 817 } 818 } 819 catch (final LDIFException le) 820 { 821 Debug.debugException(le); 822 malformedEntries.incrementAndGet(); 823 824 if (resultCode == ResultCode.SUCCESS) 825 { 826 resultCode = ResultCode.DECODING_ERROR; 827 } 828 829 if (rejectWriter != null) 830 { 831 try 832 { 833 rejectWriter.writeComment( 834 "Unable to parse an entry read from LDIF:", false, false); 835 if (le.mayContinueReading()) 836 { 837 rejectWriter.writeComment(getExceptionMessage(le), false, true); 838 } 839 else 840 { 841 rejectWriter.writeComment(getExceptionMessage(le), false, 842 false); 843 rejectWriter.writeComment("Unable to continue LDIF processing.", 844 false, true); 845 err("Aborting LDIF processing: ", getExceptionMessage(le)); 846 return ResultCode.LOCAL_ERROR; 847 } 848 } 849 catch (final IOException ioe) 850 { 851 Debug.debugException(ioe); 852 err("Unable to write to the reject file:", 853 getExceptionMessage(ioe)); 854 err("LDIF parse failure that triggered the rejection: ", 855 getExceptionMessage(le)); 856 return ResultCode.LOCAL_ERROR; 857 } 858 } 859 } 860 catch (final IOException ioe) 861 { 862 Debug.debugException(ioe); 863 864 if (rejectWriter != null) 865 { 866 try 867 { 868 rejectWriter.writeComment("I/O error reading from LDIF:", false, 869 false); 870 rejectWriter.writeComment(getExceptionMessage(ioe), false, 871 true); 872 return ResultCode.LOCAL_ERROR; 873 } 874 catch (final Exception ex) 875 { 876 Debug.debugException(ex); 877 err("I/O error reading from LDIF:", getExceptionMessage(ioe)); 878 return ResultCode.LOCAL_ERROR; 879 } 880 } 881 } 882 } 883 884 if (malformedEntries.get() > 0) 885 { 886 out(malformedEntries.get() + " entries were malformed and could not " + 887 "be read from the LDIF file."); 888 } 889 890 if (entryValidator.getInvalidEntries() > 0) 891 { 892 if (resultCode == ResultCode.SUCCESS) 893 { 894 resultCode = ResultCode.OBJECT_CLASS_VIOLATION; 895 } 896 897 for (final String s : entryValidator.getInvalidEntrySummary(true)) 898 { 899 out(s); 900 } 901 } 902 else 903 { 904 if (malformedEntries.get() == 0) 905 { 906 out("No errors were encountered."); 907 } 908 } 909 910 return resultCode; 911 } 912 finally 913 { 914 try 915 { 916 ldifReader.close(); 917 } 918 catch (final Exception e) 919 { 920 Debug.debugException(e); 921 } 922 923 try 924 { 925 if (rejectWriter != null) 926 { 927 rejectWriter.close(); 928 } 929 } 930 catch (final Exception e) 931 { 932 Debug.debugException(e); 933 } 934 } 935 } 936 937 938 939 /** 940 * Examines the provided entry to determine whether it conforms to the 941 * server schema. 942 * 943 * @param entry The entry to be examined. 944 * @param firstLineNumber The line number of the LDIF source on which the 945 * provided entry begins. 946 * 947 * @return The updated entry. This method will always return {@code null} 948 * because all of the real processing needed for the entry is 949 * performed in this method and the entry isn't needed any more 950 * after this method is done. 951 */ 952 public Entry translate(final Entry entry, final long firstLineNumber) 953 { 954 final ArrayList<String> invalidReasons = new ArrayList<String>(5); 955 if (! entryValidator.entryIsValid(entry, invalidReasons)) 956 { 957 if (rejectWriter != null) 958 { 959 synchronized (this) 960 { 961 try 962 { 963 rejectWriter.writeEntry(entry, listToString(invalidReasons)); 964 } 965 catch (final IOException ioe) 966 { 967 Debug.debugException(ioe); 968 } 969 } 970 } 971 } 972 973 final long numEntries = entriesProcessed.incrementAndGet(); 974 if ((numEntries % 1000L) == 0L) 975 { 976 out("Processed ", numEntries, " entries."); 977 } 978 979 return null; 980 } 981 982 983 984 /** 985 * Converts the provided list of strings into a single string. It will 986 * contain line breaks after all but the last element. 987 * 988 * @param l The list of strings to convert to a single string. 989 * 990 * @return The string from the provided list, or {@code null} if the provided 991 * list is empty or {@code null}. 992 */ 993 private static String listToString(final List<String> l) 994 { 995 if ((l == null) || (l.isEmpty())) 996 { 997 return null; 998 } 999 1000 final StringBuilder buffer = new StringBuilder(); 1001 final Iterator<String> iterator = l.iterator(); 1002 while (iterator.hasNext()) 1003 { 1004 buffer.append(iterator.next()); 1005 if (iterator.hasNext()) 1006 { 1007 buffer.append(EOL); 1008 } 1009 } 1010 1011 return buffer.toString(); 1012 } 1013 1014 1015 1016 /** 1017 * {@inheritDoc} 1018 */ 1019 @Override() 1020 public LinkedHashMap<String[],String> getExampleUsages() 1021 { 1022 final LinkedHashMap<String[],String> examples = 1023 new LinkedHashMap<String[],String>(2); 1024 1025 String[] args = 1026 { 1027 "--hostname", "server.example.com", 1028 "--port", "389", 1029 "--ldifFile", "data.ldif", 1030 "--rejectFile", "rejects.ldif", 1031 "--numThreads", "4" 1032 }; 1033 String description = 1034 "Validate the contents of the 'data.ldif' file using the schema " + 1035 "defined in the specified directory server using four concurrent " + 1036 "threads. All types of validation will be performed, and " + 1037 "information about any errors will be written to the 'rejects.ldif' " + 1038 "file."; 1039 examples.put(args, description); 1040 1041 1042 args = new String[] 1043 { 1044 "--schemaDirectory", "/ds/config/schema", 1045 "--ldifFile", "data.ldif", 1046 "--rejectFile", "rejects.ldif", 1047 "--ignoreStructuralObjectClasses", 1048 "--ignoreAttributeSyntax" 1049 }; 1050 description = 1051 "Validate the contents of the 'data.ldif' file using the schema " + 1052 "defined in LDIF files contained in the /ds/config/schema directory " + 1053 "using a single thread. Any errors resulting from entries that do " + 1054 "not have exactly one structural object class or from values which " + 1055 "violate the syntax for their associated attribute types will be " + 1056 "ignored. Information about any other failures will be written to " + 1057 "the 'rejects.ldif' file."; 1058 examples.put(args, description); 1059 1060 return examples; 1061 } 1062 1063 1064 1065 /** 1066 * @return EntryValidator 1067 * 1068 * Returns the EntryValidator 1069 */ 1070 public EntryValidator getEntryValidator() 1071 { 1072 return entryValidator; 1073 } 1074}