001 /*
002 * Copyright 2008-2016 UnboundID Corp.
003 * All Rights Reserved.
004 */
005 /*
006 * Copyright (C) 2008-2016 UnboundID Corp.
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 */
021 package com.unboundid.ldap.sdk.examples;
022
023
024
025 import java.io.IOException;
026 import java.io.OutputStream;
027 import java.io.Serializable;
028 import java.util.LinkedHashMap;
029 import java.util.List;
030
031 import com.unboundid.ldap.sdk.Control;
032 import com.unboundid.ldap.sdk.LDAPConnection;
033 import com.unboundid.ldap.sdk.LDAPException;
034 import com.unboundid.ldap.sdk.ResultCode;
035 import com.unboundid.ldap.sdk.Version;
036 import com.unboundid.ldif.LDIFChangeRecord;
037 import com.unboundid.ldif.LDIFException;
038 import com.unboundid.ldif.LDIFReader;
039 import com.unboundid.util.LDAPCommandLineTool;
040 import com.unboundid.util.ThreadSafety;
041 import com.unboundid.util.ThreadSafetyLevel;
042 import com.unboundid.util.args.ArgumentException;
043 import com.unboundid.util.args.ArgumentParser;
044 import com.unboundid.util.args.BooleanArgument;
045 import com.unboundid.util.args.ControlArgument;
046 import com.unboundid.util.args.FileArgument;
047
048
049
050 /**
051 * This class provides a simple tool that can be used to perform add, delete,
052 * modify, and modify DN operations against an LDAP directory server. The
053 * changes to apply can be read either from standard input or from an LDIF file.
054 * <BR><BR>
055 * Some of the APIs demonstrated by this example include:
056 * <UL>
057 * <LI>Argument Parsing (from the {@code com.unboundid.util.args}
058 * package)</LI>
059 * <LI>LDAP Command-Line Tool (from the {@code com.unboundid.util}
060 * package)</LI>
061 * <LI>LDIF Processing (from the {@code com.unboundid.ldif} package)</LI>
062 * </UL>
063 * <BR><BR>
064 * The behavior of this utility is controlled by command line arguments.
065 * Supported arguments include those allowed by the {@link LDAPCommandLineTool}
066 * class, as well as the following additional arguments:
067 * <UL>
068 * <LI>"-f {path}" or "--ldifFile {path}" -- specifies the path to the LDIF
069 * file containing the changes to apply. If this is not provided, then
070 * changes will be read from standard input.</LI>
071 * <LI>"-a" or "--defaultAdd" -- indicates that any LDIF records encountered
072 * that do not include a changetype should be treated as add change
073 * records. If this is not provided, then such records will be
074 * rejected.</LI>
075 * <LI>"-c" or "--continueOnError" -- indicates that processing should
076 * continue if an error occurs while processing an earlier change. If
077 * this is not provided, then the command will exit on the first error
078 * that occurs.</LI>
079 * <LI>"--bindControl {control}" -- specifies a control that should be
080 * included in the bind request sent by this tool before performing any
081 * update operations.</LI>
082 * </UL>
083 */
084 @ThreadSafety(level=ThreadSafetyLevel.NOT_THREADSAFE)
085 public final class LDAPModify
086 extends LDAPCommandLineTool
087 implements Serializable
088 {
089 /**
090 * The serial version UID for this serializable class.
091 */
092 private static final long serialVersionUID = -2602159836108416722L;
093
094
095
096 // Indicates whether processing should continue even if an error has occurred.
097 private BooleanArgument continueOnError;
098
099 // Indicates whether LDIF records without a changetype should be considered
100 // add records.
101 private BooleanArgument defaultAdd;
102
103 // The argument used to specify any bind controls that should be used.
104 private ControlArgument bindControls;
105
106 // The LDIF file to be processed.
107 private FileArgument ldifFile;
108
109
110
111 /**
112 * Parse the provided command line arguments and make the appropriate set of
113 * changes.
114 *
115 * @param args The command line arguments provided to this program.
116 */
117 public static void main(final String[] args)
118 {
119 final ResultCode resultCode = main(args, System.out, System.err);
120 if (resultCode != ResultCode.SUCCESS)
121 {
122 System.exit(resultCode.intValue());
123 }
124 }
125
126
127
128 /**
129 * Parse the provided command line arguments and make the appropriate set of
130 * changes.
131 *
132 * @param args The command line arguments provided to this program.
133 * @param outStream The output stream to which standard out should be
134 * written. It may be {@code null} if output should be
135 * suppressed.
136 * @param errStream The output stream to which standard error should be
137 * written. It may be {@code null} if error messages
138 * should be suppressed.
139 *
140 * @return A result code indicating whether the processing was successful.
141 */
142 public static ResultCode main(final String[] args,
143 final OutputStream outStream,
144 final OutputStream errStream)
145 {
146 final LDAPModify ldapModify = new LDAPModify(outStream, errStream);
147 return ldapModify.runTool(args);
148 }
149
150
151
152 /**
153 * Creates a new instance of this tool.
154 *
155 * @param outStream The output stream to which standard out should be
156 * written. It may be {@code null} if output should be
157 * suppressed.
158 * @param errStream The output stream to which standard error should be
159 * written. It may be {@code null} if error messages
160 * should be suppressed.
161 */
162 public LDAPModify(final OutputStream outStream, final OutputStream errStream)
163 {
164 super(outStream, errStream);
165 }
166
167
168
169 /**
170 * Retrieves the name for this tool.
171 *
172 * @return The name for this tool.
173 */
174 @Override()
175 public String getToolName()
176 {
177 return "ldapmodify";
178 }
179
180
181
182 /**
183 * Retrieves the description for this tool.
184 *
185 * @return The description for this tool.
186 */
187 @Override()
188 public String getToolDescription()
189 {
190 return "Perform add, delete, modify, and modify " +
191 "DN operations in an LDAP directory server.";
192 }
193
194
195
196 /**
197 * Retrieves the version string for this tool.
198 *
199 * @return The version string for this tool.
200 */
201 @Override()
202 public String getToolVersion()
203 {
204 return Version.NUMERIC_VERSION_STRING;
205 }
206
207
208
209 /**
210 * Indicates whether this tool should provide support for an interactive mode,
211 * in which the tool offers a mode in which the arguments can be provided in
212 * a text-driven menu rather than requiring them to be given on the command
213 * line. If interactive mode is supported, it may be invoked using the
214 * "--interactive" argument. Alternately, if interactive mode is supported
215 * and {@link #defaultsToInteractiveMode()} returns {@code true}, then
216 * interactive mode may be invoked by simply launching the tool without any
217 * arguments.
218 *
219 * @return {@code true} if this tool supports interactive mode, or
220 * {@code false} if not.
221 */
222 @Override()
223 public boolean supportsInteractiveMode()
224 {
225 return true;
226 }
227
228
229
230 /**
231 * Indicates whether this tool defaults to launching in interactive mode if
232 * the tool is invoked without any command-line arguments. This will only be
233 * used if {@link #supportsInteractiveMode()} returns {@code true}.
234 *
235 * @return {@code true} if this tool defaults to using interactive mode if
236 * launched without any command-line arguments, or {@code false} if
237 * not.
238 */
239 @Override()
240 public boolean defaultsToInteractiveMode()
241 {
242 return true;
243 }
244
245
246
247 /**
248 * Indicates whether this tool supports the use of a properties file for
249 * specifying default values for arguments that aren't specified on the
250 * command line.
251 *
252 * @return {@code true} if this tool supports the use of a properties file
253 * for specifying default values for arguments that aren't specified
254 * on the command line, or {@code false} if not.
255 */
256 @Override()
257 public boolean supportsPropertiesFile()
258 {
259 return true;
260 }
261
262
263
264 /**
265 * Indicates whether the LDAP-specific arguments should include alternate
266 * versions of all long identifiers that consist of multiple words so that
267 * they are available in both camelCase and dash-separated versions.
268 *
269 * @return {@code true} if this tool should provide multiple versions of
270 * long identifiers for LDAP-specific arguments, or {@code false} if
271 * not.
272 */
273 @Override()
274 protected boolean includeAlternateLongIdentifiers()
275 {
276 return true;
277 }
278
279
280
281 /**
282 * Adds the arguments used by this program that aren't already provided by the
283 * generic {@code LDAPCommandLineTool} framework.
284 *
285 * @param parser The argument parser to which the arguments should be added.
286 *
287 * @throws ArgumentException If a problem occurs while adding the arguments.
288 */
289 @Override()
290 public void addNonLDAPArguments(final ArgumentParser parser)
291 throws ArgumentException
292 {
293 String description = "Treat LDIF records that do not contain a " +
294 "changetype as add records.";
295 defaultAdd = new BooleanArgument('a', "defaultAdd", description);
296 defaultAdd.addLongIdentifier("default-add");
297 parser.addArgument(defaultAdd);
298
299
300 description = "Attempt to continue processing additional changes if " +
301 "an error occurs.";
302 continueOnError = new BooleanArgument('c', "continueOnError",
303 description);
304 continueOnError.addLongIdentifier("continue-on-error");
305 parser.addArgument(continueOnError);
306
307
308 description = "The path to the LDIF file containing the changes. If " +
309 "this is not provided, then the changes will be read from " +
310 "standard input.";
311 ldifFile = new FileArgument('f', "ldifFile", false, 1, "{path}",
312 description, true, false, true, false);
313 ldifFile.addLongIdentifier("ldif-file");
314 parser.addArgument(ldifFile);
315
316
317 description = "Information about a control to include in the bind request.";
318 bindControls = new ControlArgument(null, "bindControl", false, 0, null,
319 description);
320 bindControls.addLongIdentifier("bind-control");
321 parser.addArgument(bindControls);
322 }
323
324
325
326 /**
327 * {@inheritDoc}
328 */
329 @Override()
330 protected List<Control> getBindControls()
331 {
332 return bindControls.getValues();
333 }
334
335
336
337 /**
338 * Performs the actual processing for this tool. In this case, it gets a
339 * connection to the directory server and uses it to perform the requested
340 * operations.
341 *
342 * @return The result code for the processing that was performed.
343 */
344 @Override()
345 public ResultCode doToolProcessing()
346 {
347 // Set up the LDIF reader that will be used to read the changes to apply.
348 final LDIFReader ldifReader;
349 try
350 {
351 if (ldifFile.isPresent())
352 {
353 // An LDIF file was specified on the command line, so we will use it.
354 ldifReader = new LDIFReader(ldifFile.getValue());
355 }
356 else
357 {
358 // No LDIF file was specified, so we will read from standard input.
359 ldifReader = new LDIFReader(System.in);
360 }
361 }
362 catch (IOException ioe)
363 {
364 err("I/O error creating the LDIF reader: ", ioe.getMessage());
365 return ResultCode.LOCAL_ERROR;
366 }
367
368
369 // Get the connection to the directory server.
370 final LDAPConnection connection;
371 try
372 {
373 connection = getConnection();
374 out("Connected to ", connection.getConnectedAddress(), ':',
375 connection.getConnectedPort());
376 }
377 catch (LDAPException le)
378 {
379 err("Error connecting to the directory server: ", le.getMessage());
380 return le.getResultCode();
381 }
382
383
384 // Attempt to process and apply the changes to the server.
385 ResultCode resultCode = ResultCode.SUCCESS;
386 while (true)
387 {
388 // Read the next change to process.
389 final LDIFChangeRecord changeRecord;
390 try
391 {
392 changeRecord = ldifReader.readChangeRecord(defaultAdd.isPresent());
393 }
394 catch (LDIFException le)
395 {
396 err("Malformed change record: ", le.getMessage());
397 if (! le.mayContinueReading())
398 {
399 err("Unable to continue processing the LDIF content.");
400 resultCode = ResultCode.DECODING_ERROR;
401 break;
402 }
403 else if (! continueOnError.isPresent())
404 {
405 resultCode = ResultCode.DECODING_ERROR;
406 break;
407 }
408 else
409 {
410 // We can try to keep processing, so do so.
411 continue;
412 }
413 }
414 catch (IOException ioe)
415 {
416 err("I/O error encountered while reading a change record: ",
417 ioe.getMessage());
418 resultCode = ResultCode.LOCAL_ERROR;
419 break;
420 }
421
422
423 // If the change record was null, then it means there are no more changes
424 // to be processed.
425 if (changeRecord == null)
426 {
427 break;
428 }
429
430
431 // Apply the target change to the server.
432 try
433 {
434 out("Processing ", changeRecord.getChangeType().toString(),
435 " operation for ", changeRecord.getDN());
436 changeRecord.processChange(connection);
437 out("Success");
438 out();
439 }
440 catch (LDAPException le)
441 {
442 err("Error: ", le.getMessage());
443 err("Result Code: ", le.getResultCode().intValue(), " (",
444 le.getResultCode().getName(), ')');
445 if (le.getMatchedDN() != null)
446 {
447 err("Matched DN: ", le.getMatchedDN());
448 }
449
450 if (le.getReferralURLs() != null)
451 {
452 for (final String url : le.getReferralURLs())
453 {
454 err("Referral URL: ", url);
455 }
456 }
457
458 err();
459 if (! continueOnError.isPresent())
460 {
461 resultCode = le.getResultCode();
462 break;
463 }
464 }
465 }
466
467
468 // Close the connection to the directory server and exit.
469 connection.close();
470 out("Disconnected from the server");
471 return resultCode;
472 }
473
474
475
476 /**
477 * {@inheritDoc}
478 */
479 @Override()
480 public LinkedHashMap<String[],String> getExampleUsages()
481 {
482 final LinkedHashMap<String[],String> examples =
483 new LinkedHashMap<String[],String>();
484
485 String[] args =
486 {
487 "--hostname", "server.example.com",
488 "--port", "389",
489 "--bindDN", "uid=admin,dc=example,dc=com",
490 "--bindPassword", "password",
491 "--ldifFile", "changes.ldif"
492 };
493 String description =
494 "Attempt to apply the add, delete, modify, and/or modify DN " +
495 "operations contained in the 'changes.ldif' file against the " +
496 "specified directory server.";
497 examples.put(args, description);
498
499 args = new String[]
500 {
501 "--hostname", "server.example.com",
502 "--port", "389",
503 "--bindDN", "uid=admin,dc=example,dc=com",
504 "--bindPassword", "password",
505 "--continueOnError",
506 "--defaultAdd"
507 };
508 description =
509 "Establish a connection to the specified directory server and then " +
510 "wait for information about the add, delete, modify, and/or modify " +
511 "DN operations to perform to be provided via standard input. If " +
512 "any invalid operations are requested, then the tool will display " +
513 "an error message but will continue running. Any LDIF record " +
514 "provided which does not include a 'changeType' line will be " +
515 "treated as an add request.";
516 examples.put(args, description);
517
518 return examples;
519 }
520 }