UnboundID Server SDK

Ping Identity
UnboundID Server SDK Documentation

ExamplePostLDIFExportTaskProcessor.java

/*
 * 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
 * docs/licenses/cddl.txt
 * or http://www.opensource.org/licenses/cddl1.php.
 * 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
 * docs/licenses/cddl.txt.  If applicable,
 * add the following below this CDDL HEADER, with the fields enclosed
 * by brackets "[]" replaced with your own identifying information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 * Portions Copyright 2023-2024 Ping Identity Corporation
 */
package com.unboundid.directory.sdk.examples;



import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.unboundid.directory.sdk.common.types.LogSeverity;
import com.unboundid.directory.sdk.ds.api.PostLDIFExportTaskProcessor;
import com.unboundid.directory.sdk.ds.config.PostLDIFExportTaskProcessorConfig;
import com.unboundid.directory.sdk.ds.types.DirectoryServerContext;
import com.unboundid.directory.sdk.ds.types.LDIFExportTaskProperties;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.ResultCode;
import com.unboundid.util.Debug;
import com.unboundid.util.NotNull;
import com.unboundid.util.StaticUtils;
import com.unboundid.util.args.ArgumentParser;
import com.unboundid.util.args.ArgumentException;
import com.unboundid.util.args.FileArgument;



/**
 * This class provides an example post-LDIF-export task processor implementation
 * that may be used to copy the output file to an alternative location on the
 * filesystem.
 * <p>
 * This post-LDIF-export task processor supports the following configuration
 * properties:
 * <ul>
 *   <li>
 *     copy-to-directory -- The path to the directory to which the output file
 *     should be copied.
 *   </li>
 * </ul>
 */
public final class ExamplePostLDIFExportTaskProcessor
       extends PostLDIFExportTaskProcessor
{
  /**
   * The name of the extension argument that specifies the path to the directory
   * to which the output file should be copied.
   */
  private static final String ARG_NAME_COPY_TO_DIRECTORY = "copy-to-directory";



  // The name of the property that holds the passphrase.
  private volatile File copyToDirectory;

  // The server context for this extension.
  private volatile DirectoryServerContext serverContext;



  /**
   * Creates a new instance of this post-LDIF-export task processor.  All
   * post-LDIF-export task processor implementations must include a default
   * constructor, but any initialization should generally be done in the
   * {@code initializePassphraseProvider} method.
   */
  public ExamplePostLDIFExportTaskProcessor()
  {
    copyToDirectory = null;
    serverContext = null;
  }



  /**
   * Retrieves a human-readable name for this extension.
   *
   * @return  A human-readable name for this extension.
   */
  @NotNull()
  @Override()
  public String getExtensionName()
  {
    return "Example Post-LDIF-Export Task Processor";
  }



  /**
   * Retrieves a human-readable description for this extension.  Each element
   * of the array that is returned will be considered a separate paragraph in
   * generated documentation.
   *
   * @return  A human-readable description for this extension, or {@code null}
   *          or an empty array if no description should be available.
   */
  @NotNull()
  @Override()
  public String[] getExtensionDescription()
  {
    return new String[]
    {
      "An example post-LDIF-export task processor that can be used to copy " +
           "the output file to an alternative location on the filesystem."
    };
  }



  /**
   * Updates the provided argument parser to define any configuration arguments
   * which may be used by this extension.  The argument parser may also be
   * updated to define relationships between arguments (e.g., to specify
   * required, exclusive, or dependent argument sets).
   *
   * @param  parser  The argument parser to be updated with the configuration
   *                 arguments which may be used by this extension.
   *
   * @throws  ArgumentException  If a problem is encountered while updating the
   *                             provided argument parser.
   */
  @Override()
  public void defineConfigArguments(@NotNull final ArgumentParser parser)
       throws ArgumentException
  {
    final Character shortIdentifier = null;
    final String    longIdentifier  = ARG_NAME_COPY_TO_DIRECTORY;
    final boolean   required        = true;
    final int       maxOccurrences  = 1;
    final String    placeholder     = "{path}";
    final String    description     = "The path to the directory to which " +
         "exported LDIF files should be copied.";

    parser.addArgument(new FileArgument(shortIdentifier, longIdentifier,
         required, maxOccurrences, placeholder, description, true, true, false,
         true));
  }



  /**
   * Initializes this post-LDIF-export task processor.
   *
   * @param  serverContext  A handle to the server context for the server in
   *                        which this extension is running.
   * @param  config         The general configuration for this post-LDIF-export
   *                        task processor.
   * @param  parser         The argument parser which has been initialized from
   *                        the configuration for this post-LDIF-export task
   *                        processor.
   *
   * @throws  LDAPException  If a problem occurs while initializing this
   *                         post-LDIF-export task processor.
   */
  @Override()
  public void initializePostLDIFExportTaskProcessor(
                   @NotNull final DirectoryServerContext serverContext,
                   @NotNull final PostLDIFExportTaskProcessorConfig config,
                   @NotNull final ArgumentParser parser)
         throws LDAPException
  {
    this.serverContext = serverContext;

    copyToDirectory =
         parser.getFileArgument(ARG_NAME_COPY_TO_DIRECTORY).getValue();
  }



  /**
   * Indicates whether the configuration represented by the provided argument
   * parser is acceptable for use by this extension.  The parser will have been
   * used to parse any configuration available for this extension, and any
   * automatic validation will have been performed.  This method may be used to
   * perform any more complex validation which cannot be performed automatically
   * by the argument parser.
   *
   * @param  config               The general configuration for this extension.
   * @param  parser               The argument parser that has been used to
   *                              parse the proposed configuration for this
   *                              extension.
   * @param  unacceptableReasons  A list to which messages may be added to
   *                              provide additional information about why the
   *                              provided configuration is not acceptable.
   *
   * @return  {@code true} if the configuration in the provided argument parser
   *          appears to be acceptable, or {@code false} if not.
   */
  @Override()
  public boolean isConfigurationAcceptable(
              @NotNull final PostLDIFExportTaskProcessorConfig config,
              @NotNull final ArgumentParser parser,
              @NotNull final List<String> unacceptableReasons)
  {
    // No extended validation will be performed by default.
    return true;
  }



  /**
   * Attempts to apply the configuration from the provided argument parser to
   * this extension.
   *
   * @param  config                The general configuration for this extension.
   * @param  parser                The argument parser that has been used to
   *                               parse the new configuration for this
   *                               extension.
   * @param  adminActionsRequired  A list to which messages may be added to
   *                               provide additional information about any
   *                               additional administrative actions that may
   *                               be required to apply some of the
   *                               configuration changes.
   * @param  messages              A list to which messages may be added to
   *                               provide additional information about the
   *                               processing performed by this method.
   *
   * @return  A result code providing information about the result of applying
   *          the configuration change.  A result of {@code SUCCESS} should be
   *          used to indicate that all processing completed successfully.  Any
   *          other result will indicate that a problem occurred during
   *          processing.
   */
  @Override()
  @NotNull()
  public ResultCode applyConfiguration(
              @NotNull final PostLDIFExportTaskProcessorConfig config,
              @NotNull final ArgumentParser parser,
              @NotNull final List<String> adminActionsRequired,
              @NotNull final List<String> messages)
  {
    copyToDirectory =
         parser.getFileArgument(ARG_NAME_COPY_TO_DIRECTORY).getValue();

    return ResultCode.SUCCESS;
  }



  /**
   * Performs any cleanup which may be necessary when this post-LDIF-export task
   * processor is to be taken out of service.
   */
  @Override()
  public void finalizePostLDIFExportTaskProcessor()
  {
    // No implementation is required.
  }



  /**
   * Performs any appropriate processing for an LDIF export file that has been
   * generated by an administrative task.  Note that while this method may
   * access the resulting export file (for example, to examine its contents or
   * copy it to an alternative location), it must not delete, move, rename, or
   * otherwise alter the file in any way.
   *
   * @param  exportProperties  An object with information about the LDIF export
   *                           task that was completed.
   *
   * @throws  LDAPException  If a problem is encountered during processing.
   */
  @Override()
  public void doPostLDIFExportTaskProcessing(
              @NotNull final LDIFExportTaskProperties exportProperties)
         throws LDAPException
  {
    final File exportedFile = exportProperties.getOutputFile();
    final File copyToFile = new File(copyToDirectory, exportedFile.getName());

    try
    {
      Files.copy(exportedFile.toPath(), copyToFile.toPath(),
           StandardCopyOption.REPLACE_EXISTING,
           StandardCopyOption.COPY_ATTRIBUTES);
      serverContext.logMessage(LogSeverity.NOTICE,
           "The example post-LDIF-export task processor successfully " +
                "copied exported LDIF file '" + exportedFile.getAbsolutePath() +
                "' to directory '" + copyToDirectory + "'.");
    }
    catch (final IOException e)
    {
      Debug.debugException(e);
      throw new LDAPException(ResultCode.OTHER,
           "An error occurred while attempting to copy LDIF export file '" +
                exportedFile.getAbsolutePath() +
                "' to directory '" + copyToDirectory.getAbsolutePath() +
                "':  " + StaticUtils.getExceptionMessage(e),
           e);
    }
  }



  /**
   * Retrieves a map containing examples of configurations that may be used for
   * this extension.  The map key should be a list of sample arguments, and the
   * corresponding value should be a description of the behavior that will be
   * exhibited by the extension when used with that configuration.
   *
   * @return  A map containing examples of configurations that may be used for
   *          this extension.  It may be {@code null} or empty if there should
   *          not be any example argument sets.
   */
  @NotNull()
  @Override()
  public Map<List<String>,String> getExamplesArgumentSets()
  {
    return StaticUtils.mapOf(
         Collections.singletonList(
              "copy-to-directory=/path/to/target/directory"),
         "Indicates that LDIF export output files should be copied to the " +
              "specified directory.");
  }
}