Example #1
0
  @Override
  public synchronized void openBackend() throws ConfigException, InitializationException {
    baseDNSet = new HashSet<>();
    Collections.addAll(baseDNSet, baseDNs);

    // Register base DNs.
    for (DN dn : baseDNs) {
      try {
        DirectoryServer.registerBaseDN(dn, this, false);
      } catch (Exception e) {
        logger.traceException(e);

        LocalizableMessage message =
            ERR_BACKEND_CANNOT_REGISTER_BASEDN.get(dn, getExceptionMessage(e));
        throw new InitializationException(message, e);
      }
    }

    // Initialize null entry object classes.
    objectClasses = new HashMap<>();

    String topOCName = "top";
    ObjectClass topOC = DirectoryServer.getObjectClass(topOCName);
    if (topOC == null) {
      throw new InitializationException(
          LocalizableMessage.raw(
              "Unable to locate " + topOCName + " objectclass in the current server schema"));
    }
    objectClasses.put(topOC, topOCName);

    String nulOCName = "nullbackendobject";
    ObjectClass nulOC = DirectoryServer.getDefaultObjectClass(nulOCName);
    try {
      DirectoryServer.registerObjectClass(nulOC, false);
    } catch (DirectoryException de) {
      logger.traceException(de);
      throw new InitializationException(de.getMessageObject());
    }
    objectClasses.put(nulOC, nulOCName);

    String extOCName = "extensibleobject";
    ObjectClass extOC = DirectoryServer.getObjectClass(extOCName);
    if (extOC == null) {
      throw new InitializationException(
          LocalizableMessage.raw(
              "Unable to locate " + extOCName + " objectclass in the current server schema"));
    }
    objectClasses.put(extOC, extOCName);
  }
Example #2
0
  /**
   * Add the provided record at the end of this log.
   *
   * <p>The record must have a key strictly higher than the key of the last record added. If it is
   * not the case, the record is not appended and the method returns immediately.
   *
   * <p>In order to ensure that record is written out of buffers and persisted to file system, it is
   * necessary to explicitely call the {@code syncToFileSystem()} method.
   *
   * @param record The record to add.
   * @throws ChangelogException If an error occurs while adding the record to the log.
   */
  public void append(final Record<K, V> record) throws ChangelogException {
    // If this exclusive lock happens to be a bottleneck :
    // 1. use a shared lock for appending the record first
    // 2. switch to an exclusive lock only if rotation is needed
    // See http://sources.forgerock.org/cru/CR-3548#c27521 for full detail
    exclusiveLock.lock();
    try {
      if (isClosed) {
        return;
      }
      if (recordIsBreakingKeyOrdering(record)) {
        logger.info(
            LocalizableMessage.raw(
                "Rejecting append to log '%s' for record: [%s], last key appended: [%s]",
                logPath.getPath(), record, lastAppendedKey != null ? lastAppendedKey : "null"));
        return;
      }
      LogFile<K, V> headLogFile = getHeadLogFile();
      if (mustRotate(headLogFile)) {
        logger.trace(
            INFO_CHANGELOG_LOG_FILE_ROTATION.get(logPath.getPath(), headLogFile.getSizeInBytes()));

        rotateHeadLogFile();
        headLogFile = getHeadLogFile();
      }
      headLogFile.append(record);
      lastAppendedKey = record.getKey();
    } finally {
      exclusiveLock.unlock();
    }
  }
Example #3
0
  /**
   * Creates the summary table.
   *
   * @throws IOException if there is a problem with screen I/O
   * @throws LDAPException if there is a problem getting information out to the directory
   * @throws DecodeException if there is a problem with the encoding
   */
  private void printSummaryTable() throws LDAPException, IOException, DecodeException {
    List<TaskEntry> entries = taskClient.getTaskEntries();
    if (!entries.isEmpty()) {
      TableBuilder table = new TableBuilder();
      Map<String, TaskEntry> mapIdToEntry = new TreeMap<>();
      for (TaskEntry entry : entries) {
        String taskId = entry.getId();
        if (taskId != null) {
          mapIdToEntry.put(taskId, entry);
        }
      }

      table.appendHeading(INFO_TASKINFO_FIELD_ID.get());
      table.appendHeading(INFO_TASKINFO_FIELD_TYPE.get());
      table.appendHeading(INFO_TASKINFO_FIELD_STATUS.get());
      for (String taskId : mapIdToEntry.keySet()) {
        TaskEntry entryWrapper = mapIdToEntry.get(taskId);
        table.startRow();
        table.appendCell(taskId);
        table.appendCell(entryWrapper.getType());
        table.appendCell(entryWrapper.getState());
      }
      StringWriter sw = new StringWriter();
      TextTablePrinter tablePrinter = new TextTablePrinter(sw);
      tablePrinter.setIndentWidth(INDENT);
      tablePrinter.setTotalWidth(80);
      table.print(tablePrinter);
      getOutputStream().println(LocalizableMessage.raw(sw.getBuffer()));
    } else {
      getOutputStream().println(INFO_TASKINFO_NO_TASKS.get());
      getOutputStream().println();
    }
  }
Example #4
0
    /** {@inheritDoc} */
    @Override
    protected MenuResult<TaskEntry> invoke(ManageTasks app) throws ClientException {
      TaskEntry taskEntry = null;
      try {
        taskEntry = app.getTaskClient().getTaskEntry(taskId);
        List<LocalizableMessage> logs = taskEntry.getLogMessages();
        app.getOutputStream().println();

        // Create a table for the last log entry
        TableBuilder table = new TableBuilder();
        table.appendHeading(INFO_TASKINFO_FIELD_LOG.get());
        if (logs != null && !logs.isEmpty()) {
          for (LocalizableMessage log : logs) {
            table.startRow();
            table.appendCell(log);
          }
        } else {
          table.startRow();
          table.appendCell(INFO_TASKINFO_NONE.get());
        }
        StringWriter sw = new StringWriter();
        TextTablePrinter tablePrinter = new TextTablePrinter(sw);
        tablePrinter.setTotalWidth(80);
        tablePrinter.setIndentWidth(INDENT);
        tablePrinter.setColumnWidth(0, 0);
        table.print(tablePrinter);
        app.getOutputStream().println(LocalizableMessage.raw(sw.getBuffer().toString()));
        app.getOutputStream().println();
      } catch (Exception e) {
        app.println(ERR_TASKINFO_ACCESSING_LOGS.get(taskId, e.getMessage()));
      }
      return MenuResult.success(taskEntry);
    }
Example #5
0
 private int getPort() {
   try {
     return Installation.getLocal().getCurrentConfiguration().getPort();
   } catch (IOException ioe) {
     logger.info(LocalizableMessage.raw("Failed to get port", ioe));
     return -1;
   }
 }
Example #6
0
  /**
   * Sets the root directory of this instance.
   *
   * @param instanceDirectory File of this instance
   */
  public void setInstanceDirectory(File instanceDirectory) {
    // Hold off on doing validation of rootDirectory since
    // some applications (like the Installer) create an Installation
    // before the actual bits have been laid down on the filesystem.
    this.instanceDirectory = instanceDirectory;

    // Obtaining build information is a fairly time consuming operation.
    // Try to get a head start if possible.
    if (isValid(instanceDirectory)) {
      try {
        BuildInformation bi = getBuildInformation();
        logger.info(
            LocalizableMessage.raw("build info for " + instanceDirectory.getName() + ": " + bi));
      } catch (ApplicationException e) {
        logger.info(LocalizableMessage.raw("error determining build information", e));
      }
    }
  }
 private LocalizableMessage getDisconnectMessage(Entry taskEntry) {
   AttributeType attrType =
       DirectoryServer.getAttributeTypeOrDefault(ATTR_TASK_DISCONNECT_MESSAGE);
   for (Attribute a : taskEntry.getAttribute(attrType)) {
     for (ByteString v : a) {
       return LocalizableMessage.raw(v.toString());
     }
   }
   return INFO_TASK_DISCONNECT_GENERIC_MESSAGE.get();
 }
 /**
  * Returns the message for the provided attribute.
  *
  * @param attribute the attribute.
  * @return the message for the provided attribute.
  */
 protected LocalizableMessage getMessage(T attribute) {
   LocalizableMessage m;
   if (attribute instanceof MonitoringAttributes) {
     m = ((MonitoringAttributes) attribute).getMessage();
   } else if (attribute instanceof LocalizableMessage) {
     m = (LocalizableMessage) attribute;
   } else {
     m = LocalizableMessage.raw(attribute.toString());
   }
   return m;
 }
Example #9
0
  /**
   * Creates the summary table.
   *
   * @return list of strings of IDs of all the tasks in the table in order of the indexes printed in
   *     the table
   * @throws IOException if there is a problem with screen I/O
   * @throws LDAPException if there is a problem getting information out to the directory
   * @throws DecodeException if there is a problem with the encoding
   */
  private Menu<Void> getSummaryMenu() throws LDAPException, IOException, DecodeException {
    List<String> taskIds = new ArrayList<>();
    List<Integer> cancelableIndices = new ArrayList<>();
    List<TaskEntry> entries = taskClient.getTaskEntries();
    MenuBuilder<Void> menuBuilder = new MenuBuilder<>(this);
    if (!entries.isEmpty()) {
      Map<String, TaskEntry> mapIdToEntry = new TreeMap<>();
      for (TaskEntry entry : entries) {
        String taskId = entry.getId();
        if (taskId != null) {
          mapIdToEntry.put(taskId, entry);
        }
      }

      menuBuilder.setColumnHeadings(
          INFO_TASKINFO_FIELD_ID.get(),
          INFO_TASKINFO_FIELD_TYPE.get(),
          INFO_TASKINFO_FIELD_STATUS.get());
      menuBuilder.setColumnWidths(null, null, 0);
      int index = 0;
      for (final String taskId : mapIdToEntry.keySet()) {
        taskIds.add(taskId);
        final TaskEntry taskEntry = mapIdToEntry.get(taskId);
        menuBuilder.addNumberedOption(
            LocalizableMessage.raw(taskEntry.getId()),
            new TaskDrilldownMenu(taskId),
            taskEntry.getType(),
            taskEntry.getState());
        index++;
        if (taskEntry.isCancelable()) {
          cancelableIndices.add(index);
        }
      }
    } else {
      getOutputStream().println(INFO_TASKINFO_NO_TASKS.get());
      getOutputStream().println();
    }

    menuBuilder.addCharOption(
        INFO_TASKINFO_CMD_REFRESH_CHAR.get(),
        INFO_TASKINFO_CMD_REFRESH.get(),
        new PrintSummaryTop());

    if (!cancelableIndices.isEmpty()) {
      menuBuilder.addCharOption(
          INFO_TASKINFO_CMD_CANCEL_CHAR.get(),
          INFO_TASKINFO_CMD_CANCEL.get(),
          new CancelTaskTop(taskIds, cancelableIndices));
    }
    menuBuilder.addQuitOption();

    return menuBuilder.toMenu();
  }
Example #10
0
    /** {@inheritDoc} */
    @Override
    public MenuResult<Void> invoke(ManageTasks app) throws ClientException {
      MenuResult<TaskEntry> res = new PrintTaskInfo(taskId).invoke(app);
      TaskEntry taskEntry = res.getValue();
      if (taskEntry != null) {
        while (true) {
          try {
            taskEntry = app.getTaskClient().getTaskEntry(taskId);

            // Show the menu
            MenuBuilder<TaskEntry> menuBuilder = new MenuBuilder<>(app);
            menuBuilder.addBackOption(true);
            menuBuilder.addCharOption(
                INFO_TASKINFO_CMD_REFRESH_CHAR.get(),
                INFO_TASKINFO_CMD_REFRESH.get(),
                new PrintTaskInfo(taskId));
            List<LocalizableMessage> logs = taskEntry.getLogMessages();
            if (logs != null && !logs.isEmpty()) {
              menuBuilder.addCharOption(
                  INFO_TASKINFO_CMD_VIEW_LOGS_CHAR.get(),
                  INFO_TASKINFO_CMD_VIEW_LOGS.get(),
                  new ViewTaskLogs(taskId));
            }
            if (taskEntry.isCancelable() && !taskEntry.isDone()) {
              menuBuilder.addCharOption(
                  INFO_TASKINFO_CMD_CANCEL_CHAR.get(),
                  INFO_TASKINFO_CMD_CANCEL.get(),
                  new CancelTask(taskId));
            }
            menuBuilder.addQuitOption();
            Menu<TaskEntry> menu = menuBuilder.toMenu();
            MenuResult<TaskEntry> result = menu.run();
            if (result.isCancel()) {
              break;
            } else if (result.isQuit()) {
              System.exit(0);
            }
          } catch (Exception e) {
            app.println(LocalizableMessage.raw(StaticUtils.getExceptionMessage(e)));
          }
        }
      } else {
        app.println(ERR_TASKINFO_UNKNOWN_TASK_ENTRY.get(taskId));
      }
      return MenuResult.success();
    }
Example #11
0
 /**
  * Retrieves the backends from the current configuration file. The backends must be enabled to be
  * listed. No operations should be done within a disabled backend.
  *
  * @return A backend list.
  */
 static List<String> getIndexedBackendsFromConfig() {
   final SearchRequest sr =
       Requests.newSearchRequest(
           "",
           SearchScope.WHOLE_SUBTREE,
           "(&(objectclass=ds-cfg-pluggable-backend)(ds-cfg-enabled=true))",
           "ds-cfg-base-dn");
   final List<String> listBackends = new LinkedList<>();
   try (final EntryReader entryReader = searchConfigFile(sr)) {
     while (entryReader.hasNext()) {
       final Entry entry = entryReader.readEntry();
       listBackends.addAll(entry.parseAttribute("ds-cfg-base-dn").asSetOfString());
     }
   } catch (Exception ex) {
     logger.error(LocalizableMessage.raw(ex.getMessage()));
   }
   return listBackends;
 }
Example #12
0
 /**
  * Gets information about the build that was used to produce the instance.
  *
  * @param useCachedVersion where true indicates that a potentially cached version of the build
  *     information is acceptable for use; false indicates the build information will be created
  *     from scratch which is potentially time consuming
  * @return BuildInformation object describing this instance
  */
 public BuildInformation getInstanceBuildInformation(boolean useCachedVersion) {
   if (instanceInformation == null || !useCachedVersion) {
     try {
       File bif = new File(getConfigurationDirectory(), BUILDINFO_RELATIVE_PATH);
       if (bif.exists()) {
         // Read the first line and close the file.
         try (BufferedReader reader = new BufferedReader(new FileReader(bif))) {
           String line = reader.readLine();
           instanceInformation = BuildInformation.fromBuildString(line);
         }
       } else {
         return getBuildInformation();
       }
     } catch (Exception e) {
       logger.error(
           LocalizableMessage.raw("error getting build information for current instance", e));
     }
   }
   return instanceInformation;
 }
Example #13
0
 /**
  * Gets information about the build that was used to produce the bits for this installation.
  *
  * @param useCachedVersion where true indicates that a potentially cached version of the build
  *     information is acceptable for use; false indicates the the build information will be
  *     created from scratch which is potentially time consuming
  * @return BuildInformation object describing this installation
  * @throws ApplicationException if there is a problem obtaining the build information
  */
 public BuildInformation getBuildInformation(boolean useCachedVersion)
     throws ApplicationException {
   if (buildInformation == null || !useCachedVersion) {
     FutureTask<BuildInformation> ft =
         new FutureTask<>(
             new Callable<BuildInformation>() {
               @Override
               public BuildInformation call() throws ApplicationException {
                 return BuildInformation.create(Installation.this);
               }
             });
     new Thread(ft).start();
     try {
       buildInformation = ft.get();
     } catch (InterruptedException e) {
       logger.info(LocalizableMessage.raw("interrupted trying to get build information", e));
     } catch (ExecutionException e) {
       throw (ApplicationException) e.getCause();
     }
   }
   return buildInformation;
 }
Example #14
0
  /**
   * Creates a new file in the config/upgrade folder. The new file is a concatenation of entries of
   * all files contained in the config/schema folder.
   *
   * @param folder The folder containing the schema files.
   * @param revision The revision number of the current binary version.
   * @throws Exception If we cannot read the files contained in the folder where the schema files
   *     are supposed to be, or the file has errors.
   */
  static void updateConfigUpgradeSchemaFile(final File folder, final String revision)
      throws Exception {
    // We need to upgrade the schema.ldif.<rev> file contained in the
    // config/upgrade folder otherwise, we cannot enable the backend at
    // server's start. We need to read all files contained in config/schema
    // and add all attribute/object classes in this new super entry which
    // will be read at start-up.
    Entry theNewSchemaEntry = new LinkedHashMapEntry();
    LDIFEntryReader reader = null;
    LDIFEntryWriter writer = null;
    try {
      if (folder.isDirectory()) {
        final FilenameFilter filter = new SchemaConfigManager.SchemaFileFilter();
        for (final File f : folder.listFiles(filter)) {
          logger.debug(LocalizableMessage.raw(String.format("Processing %s", f.getAbsolutePath())));
          reader = new LDIFEntryReader(new FileInputStream(f));
          try {
            while (reader.hasNext()) {
              final Entry entry = reader.readEntry();
              theNewSchemaEntry.setName(entry.getName());
              for (final Attribute at : entry.getAllAttributes()) {
                theNewSchemaEntry.addAttribute(at);
              }
            }
          } catch (Exception ex) {
            throw new Exception(
                "Error parsing existing schema file " + f.getName() + " - " + ex.getMessage(), ex);
          }
        }

        // Creates a File object representing
        // config/upgrade/schema.ldif.revision which the server creates
        // the first time it starts if there are schema customizations.
        final File destination =
            new File(
                configDirectory,
                Installation.UPGRADE_PATH + File.separator + "schema.ldif." + revision);

        // Checks if the parent exists (eg. embedded
        // server doesn't seem to provide that folder)
        File parentDirectory = destination.getParentFile();
        if (!parentDirectory.exists()) {
          logger.debug(
              LocalizableMessage.raw(
                  String.format("Parent file of %s doesn't exist", destination.getPath())));

          parentDirectory.mkdirs();

          logger.debug(
              LocalizableMessage.raw(
                  String.format("Parent directory %s created.", parentDirectory.getPath())));
        }
        if (!destination.exists()) {
          destination.createNewFile();
        }

        logger.debug(
            LocalizableMessage.raw(
                String.format("Writing entries in %s.", destination.getAbsolutePath())));

        writer = new LDIFEntryWriter(new FileOutputStream(destination));
        writer.writeEntry(theNewSchemaEntry);

        logger.debug(
            LocalizableMessage.raw(
                String.format(
                    "%s created and completed successfully.", destination.getAbsolutePath())));
      }
    } finally {
      StaticUtils.close(reader, writer);
    }
  }
Example #15
0
  /**
   * This task adds new attributes / object classes to the specified destination file. The new
   * attributes and object classes must be originally defined in the template file.
   *
   * @param templateFile The file in which the new attribute/object definition can be read.
   * @param destination The file where we want to add the new definitions.
   * @param attributes Those attributes needed to be inserted into the new destination file.
   * @param objectClasses Those object classes needed to be inserted into the new destination file.
   * @return An integer which represents each time an attribute / object class is inserted
   *     successfully to the destination file.
   * @throws IOException If an unexpected IO error occurred while reading the entry.
   * @throws IllegalStateException Failure to find an attribute in the template schema indicates
   *     either a programming error (e.g. typo in the attribute name) or template corruption.
   *     Upgrade should stop.
   */
  static int updateSchemaFile(
      final File templateFile,
      final File destination,
      final String[] attributes,
      final String[] objectClasses)
      throws IOException, IllegalStateException {
    int changeCount = 0;
    LDIFEntryReader templateReader = null;
    LDIFEntryReader destinationReader = null;
    LDIFEntryWriter destinationWriter = null;
    File copy = null;
    try {
      templateReader = new LDIFEntryReader(new FileInputStream(templateFile));
      if (!templateReader.hasNext()) {
        // Unless template are corrupted, this should not happen.
        throw new IOException(
            ERR_UPGRADE_CORRUPTED_TEMPLATE.get(templateFile.getPath()).toString());
      }
      final Entry templateSchemaEntry = templateReader.readEntry();

      destinationReader = new LDIFEntryReader(new FileInputStream(destination));
      if (!destinationReader.hasNext()) {
        // Unless template are corrupted, this should not happen.
        throw new IOException(ERR_UPGRADE_CORRUPTED_TEMPLATE.get(destination.getPath()).toString());
      }
      final Entry destinationSchemaEntry = destinationReader.readEntry();

      if (attributes != null) {
        for (final String att : attributes) {
          final ByteString attributeType =
              getSchemaElement(templateSchemaEntry, "attributeTypes", att);
          destinationSchemaEntry.getAttribute("attributeTypes").add(attributeType);
          changeCount++;
          logger.debug(LocalizableMessage.raw(String.format("Added %s", attributeType)));
        }
      }

      if (objectClasses != null) {
        for (final String oc : objectClasses) {
          final ByteString objectClass = getSchemaElement(templateSchemaEntry, "objectClasses", oc);
          destinationSchemaEntry.getAttribute("objectClasses").add(objectClass);
          changeCount++;
          logger.trace("Added %s", objectClass);
        }
      }

      // Then writes the new schema entry.
      copy = File.createTempFile("copySchema", ".tmp", destination.getParentFile());
      final FileOutputStream fos = new FileOutputStream(copy);
      destinationWriter = new LDIFEntryWriter(fos);
      destinationWriter.setWrapColumn(79);
      // Copy comments to fos (get License and first comments only).
      writeFileHeaderComments(templateFile, destinationWriter);
      // Writes the entry after.
      destinationWriter.writeEntry(destinationSchemaEntry);
    } finally {
      // Readers and writer must be close before writing files.
      // This causes exceptions under windows OS.
      StaticUtils.close(templateReader, destinationReader, destinationWriter);
    }

    // Renames the copy to make it the new schema file.
    try {
      rename(copy, destination);
    } catch (IOException e) {
      logger.error(LocalizableMessage.raw(e.getMessage()));
      deleteRecursively(copy);
      throw e;
    }

    return changeCount;
  }
Example #16
0
  /**
   * Updates the config file during the upgrade process.
   *
   * @param configPath The original path to the file.
   * @param filter The filter to select entries. Only useful for modify change type.
   * @param changeType The change type which must be applied to ldif lines.
   * @param ldifLines The change record ldif lines. For ADD change type, the first line must be the
   *     dn. For DELETE change type, the first and only line must be the dn.
   * @throws IOException If an Exception occurs during the input output methods.
   * @return The changes number that have occurred.
   */
  static int updateConfigFile(
      final String configPath,
      final Filter filter,
      final ChangeOperationType changeType,
      final String... ldifLines)
      throws IOException {
    final File original = new File(configPath);
    final File copyConfig = File.createTempFile("copyConfig", ".tmp", original.getParentFile());

    int changeCount = 0;
    LDIFEntryReader entryReader = null;
    LDIFEntryWriter writer = null;
    try {
      final Schema schema = getUpgradeSchema();
      entryReader = new LDIFEntryReader(new FileInputStream(configPath)).setSchema(schema);

      writer = new LDIFEntryWriter(new FileOutputStream(copyConfig));
      writer.setWrapColumn(80);

      // Writes the header on the new file.
      writer.writeComment(INFO_CONFIG_FILE_HEADER.get());
      writer.setWrapColumn(0);

      boolean entryAlreadyExist = false;
      DN ldifDN = null;
      if (filter == null && (changeType == ADD || changeType == DELETE)) {
        // The first line should start with dn:
        ldifDN = DN.valueOf(ldifLines[0].replaceFirst("dn: ", ""));
      }
      final Filter f = filter != null ? filter : Filter.alwaysFalse();
      final Matcher matcher = f.matcher(schema);
      while (entryReader.hasNext()) {
        Entry entry = entryReader.readEntry();
        final DN entryDN = entry.getName();
        // Searching for the related entries
        if (changeType == MODIFY && matcher.matches(entry) == ConditionResult.TRUE) {
          try {
            final ModifyRequest mr =
                Requests.newModifyRequest(readLDIFLines(entryDN, changeType, ldifLines));
            entry = Entries.modifyEntryPermissive(entry, mr.getModifications());
            changeCount++;
            logger.debug(
                LocalizableMessage.raw("The following entry has been modified : %s", entryDN));
          } catch (Exception ex) {
            logger.error(LocalizableMessage.raw(ex.getMessage()));
          }
        }

        if (entryDN.equals(ldifDN)) {
          logger.debug(LocalizableMessage.raw("Entry %s found", entryDN));
          entryAlreadyExist = true;

          if (changeType == DELETE) {
            entry = null;
            changeCount++;
            logger.debug(
                LocalizableMessage.raw("The following entry has been deleted : %s", entryDN));
          }
        }

        if (entry != null) {
          writer.writeEntry(entry);
        }
      }

      if (changeType == ADD && !entryAlreadyExist) {
        final AddRequest ar = Requests.newAddRequest(ldifLines);
        writer.writeEntry(ar);
        logger.debug(
            LocalizableMessage.raw(
                "Entry successfully added %s in %s", ldifDN, original.getAbsolutePath()));
        changeCount++;
      }
    } catch (Exception ex) {
      throw new IOException(ex.getMessage());
    } finally {
      // The reader and writer must be close before renaming files.
      // Otherwise it causes exceptions under windows OS.
      StaticUtils.close(entryReader, writer);
    }

    try {
      // Renaming the file, overwriting previous one.
      rename(copyConfig, new File(configPath));
    } catch (IOException e) {
      logger.error(LocalizableMessage.raw(e.getMessage()));
      deleteRecursively(original);
      throw e;
    }

    return changeCount;
  }
  /** {@inheritDoc} */
  @Override
  public LDIFImportResult importLDIF(
      LDIFImportConfig importConfig, RootContainer rootContainer, ServerContext serverContext)
      throws DirectoryException {
    try {
      ScheduledThreadPoolExecutor timerService = new ScheduledThreadPoolExecutor(1);
      try {
        final LDIFReader reader;
        try {
          reader = new LDIFReader(importConfig);
        } catch (Exception e) {
          LocalizableMessage m =
              ERR_LDIF_BACKEND_CANNOT_CREATE_LDIF_READER.get(stackTraceToSingleLineString(e));
          throw new DirectoryException(DirectoryServer.getServerErrorResultCode(), m, e);
        }

        long importCount = 0;
        final long startTime = System.currentTimeMillis();
        timerService.scheduleAtFixedRate(
            new ImportProgress(reader),
            IMPORT_PROGRESS_INTERVAL,
            IMPORT_PROGRESS_INTERVAL,
            TimeUnit.MILLISECONDS);
        while (true) {
          final Entry entry;
          try {
            entry = reader.readEntry();
            if (entry == null) {
              break;
            }
          } catch (LDIFException le) {
            if (!le.canContinueReading()) {
              LocalizableMessage m =
                  ERR_LDIF_BACKEND_ERROR_READING_LDIF.get(stackTraceToSingleLineString(le));
              throw new DirectoryException(DirectoryServer.getServerErrorResultCode(), m, le);
            }
            continue;
          }

          final DN dn = entry.getName();
          final EntryContainer ec = rootContainer.getEntryContainer(dn);
          if (ec == null) {
            final LocalizableMessage m = ERR_LDIF_SKIP.get(dn);
            logger.error(m);
            reader.rejectLastEntry(m);
            continue;
          }

          try {
            ec.addEntry(entry, null);
            importCount++;
          } catch (DirectoryException e) {
            switch (e.getResultCode().asEnum()) {
              case ENTRY_ALREADY_EXISTS:
                if (importConfig.replaceExistingEntries()) {
                  final Entry oldEntry = ec.getEntry(entry.getName());
                  ec.replaceEntry(oldEntry, entry, null);
                } else {
                  reader.rejectLastEntry(WARN_IMPORT_ENTRY_EXISTS.get());
                }
                break;
              case NO_SUCH_OBJECT:
                reader.rejectLastEntry(ERR_IMPORT_PARENT_NOT_FOUND.get(dn.parent()));
                break;
              default:
                // Not sure why it failed.
                reader.rejectLastEntry(e.getMessageObject());
                break;
            }
          }
        }
        final long finishTime = System.currentTimeMillis();

        waitForShutdown(timerService);

        final long importTime = finishTime - startTime;
        float rate = 0;
        if (importTime > 0) {
          rate = 1000f * reader.getEntriesRead() / importTime;
        }
        logger.info(
            NOTE_IMPORT_FINAL_STATUS,
            reader.getEntriesRead(),
            importCount,
            reader.getEntriesIgnored(),
            reader.getEntriesRejected(),
            0,
            importTime / 1000,
            rate);
        return new LDIFImportResult(
            reader.getEntriesRead(), reader.getEntriesRejected(), reader.getEntriesIgnored());
      } finally {
        rootContainer.close();

        // if not already stopped, then stop it
        waitForShutdown(timerService);
      }
    } catch (DirectoryException e) {
      logger.traceException(e);
      throw e;
    } catch (OpenDsException e) {
      logger.traceException(e);
      throw new DirectoryException(getServerErrorResultCode(), e.getMessageObject());
    } catch (Exception e) {
      logger.traceException(e);
      throw new DirectoryException(
          getServerErrorResultCode(), LocalizableMessage.raw(e.getMessage()));
    }
  }
  /**
   * Updates the contents of the panel with the provided object class.
   *
   * @param oc the object class.
   * @param schema the schema.
   */
  public void update(ObjectClass oc, Schema schema) {
    ignoreChangeEvents = true;

    objectClass = oc;
    if (oc == null || schema == null) {
      // Ignore: this is called to get an initial panel size.
      return;
    }
    String n = oc.getPrimaryName();
    if (n == null) {
      n = NOT_APPLICABLE.toString();
    }
    titlePanel.setDetails(LocalizableMessage.raw(n));
    name.setText(n);

    SortableListModel<AttributeType> modelRequired = attributes.getSelectedListModel1();
    SortableListModel<AttributeType> modelAvailable = attributes.getSelectedListModel2();
    SortableListModel<AttributeType> availableModel = attributes.getAvailableListModel();
    availableModel.addAll(modelRequired.getData());
    availableModel.addAll(modelAvailable.getData());
    modelRequired.clear();
    modelAvailable.clear();

    superiors.setSelectedSuperiors(oc.getSuperiorClasses());
    superiors.setObjectClassesToExclude(Collections.singleton(oc));
    if (oc.getSuperiorClasses().size() > 1) {
      lSuperior.setText(INFO_CTRL_PANEL_OBJECTCLASS_PARENTS_LABEL.get().toString());
    } else {
      lSuperior.setText(INFO_CTRL_PANEL_OBJECTCLASS_PARENT_LABEL.get().toString());
    }

    updateAttributesWithParent(false);

    for (AttributeType attr : oc.getRequiredAttributes()) {
      availableModel.remove(attr);
      modelRequired.add(attr);
    }
    for (AttributeType attr : oc.getOptionalAttributes()) {
      availableModel.remove(attr);
      modelAvailable.add(attr);
    }
    notifyAttributesChanged();

    oid.setText(oc.getOID());
    n = oc.getDescription();
    if (n == null) {
      n = "";
    }
    description.setText(n);

    Set<String> aliases = getAliases(oc);
    lastAliases.clear();
    lastAliases.addAll(aliases);
    this.aliases.setText(Utilities.getStringFromCollection(aliases, ", "));

    String sOrigin = Utilities.getOrigin(oc);
    if (sOrigin == null) {
      sOrigin = "";
    }
    origin.setText(sOrigin);

    String sFile = getSchemaFile(oc);
    if (sFile == null) {
      sFile = "";
    }
    file.setText(sFile);

    type.setSelectedItem(oc.getObjectClassType());

    obsolete.setSelected(oc.isObsolete());

    ocName = objectClass.getNameOrOID();
    scrollListener.updateBorder();
    for (JLabel label : labels) {
      setPrimaryValid(label);
    }
    saveChanges.setEnabled(false);
    ignoreChangeEvents = false;
  }
Example #19
0
  /**
   * Processes the command-line arguments and invokes the export process.
   *
   * @param args The command-line arguments provided to this program.
   * @param initializeServer Indicates whether to initialize the server.
   * @return The error code.
   */
  public int process(String[] args, boolean initializeServer) {
    if (initializeServer) {
      DirectoryServer.bootstrapClient();
    }
    JDKLogging.disableLogging();

    // Create the command-line argument parser for use with this program.
    LDAPConnectionArgumentParser argParser =
        new LDAPConnectionArgumentParser(
            "org.opends.server.tools.TaskInfo",
            INFO_TASKINFO_TOOL_DESCRIPTION.get(),
            false,
            null,
            alwaysSSL);
    argParser.setShortToolDescription(REF_SHORT_DESC_MANAGE_TASKS.get());

    // Initialize all the command-line argument types and register them with the
    // parser.
    try {

      StringArgument propertiesFileArgument =
          new StringArgument(
              "propertiesFilePath",
              null,
              OPTION_LONG_PROP_FILE_PATH,
              false,
              false,
              true,
              INFO_PROP_FILE_PATH_PLACEHOLDER.get(),
              null,
              null,
              INFO_DESCRIPTION_PROP_FILE_PATH.get());
      argParser.addArgument(propertiesFileArgument);
      argParser.setFilePropertiesArgument(propertiesFileArgument);

      BooleanArgument noPropertiesFileArgument =
          new BooleanArgument(
              "noPropertiesFileArgument",
              null,
              OPTION_LONG_NO_PROP_FILE,
              INFO_DESCRIPTION_NO_PROP_FILE.get());
      argParser.addArgument(noPropertiesFileArgument);
      argParser.setNoPropertiesFileArgument(noPropertiesFileArgument);

      task =
          new StringArgument(
              "info",
              'i',
              "info",
              false,
              true,
              INFO_TASK_ID_PLACEHOLDER.get(),
              INFO_TASKINFO_TASK_ARG_DESCRIPTION.get());
      argParser.addArgument(task);

      cancel =
          new StringArgument(
              "cancel",
              'c',
              "cancel",
              false,
              true,
              INFO_TASK_ID_PLACEHOLDER.get(),
              INFO_TASKINFO_TASK_ARG_CANCEL.get());
      argParser.addArgument(cancel);

      summary =
          new BooleanArgument(
              "summary", 's', "summary", INFO_TASKINFO_SUMMARY_ARG_DESCRIPTION.get());
      argParser.addArgument(summary);

      noPrompt = CommonArguments.getNoPrompt();
      argParser.addArgument(noPrompt);

      BooleanArgument displayUsage = CommonArguments.getShowUsage();
      argParser.addArgument(displayUsage);
      argParser.setUsageArgument(displayUsage);
    } catch (ArgumentException ae) {
      LocalizableMessage message = ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage());
      println(message);
      return 1;
    }

    try {
      argParser.getArguments().initArgumentsWithConfiguration();
    } catch (ConfigException ce) {
      // Ignore.
    }

    // Parse the command-line arguments provided to this program.
    try {
      argParser.parseArguments(args);
      StaticUtils.checkOnlyOneArgPresent(task, summary, cancel);
    } catch (ArgumentException ae) {
      LocalizableMessage message = ERR_ERROR_PARSING_ARGS.get(ae.getMessage());
      println(message);
      println(argParser.getUsageMessage());
      return 1;
    }

    if (!argParser.usageOrVersionDisplayed()) {
      // Checks the version - if upgrade required, the tool is unusable
      try {
        BuildVersion.checkVersionMismatch();
      } catch (InitializationException e) {
        println(e.getMessageObject());
        return 1;
      }

      try {
        LDAPConnectionConsoleInteraction ui =
            new LDAPConnectionConsoleInteraction(this, argParser.getArguments());

        taskClient = new TaskClient(argParser.connect(ui, getOutputStream(), getErrorStream()));

        if (isMenuDrivenMode()) {

          // Keep prompting the user until they specify quit of
          // there is a fatal exception
          while (true) {
            getOutputStream().println();
            Menu<Void> menu = getSummaryMenu();
            MenuResult<Void> result = menu.run();
            if (result.isQuit()) {
              return 0;
            }
          }

        } else if (task.isPresent()) {
          getOutputStream().println();
          MenuResult<TaskEntry> r = new PrintTaskInfo(task.getValue()).invoke(this);
          if (r.isAgain()) {
            return 1;
          }
        } else if (summary.isPresent()) {
          getOutputStream().println();
          printSummaryTable();
        } else if (cancel.isPresent()) {
          MenuResult<TaskEntry> r = new CancelTask(cancel.getValue()).invoke(this);
          if (r.isAgain()) {
            return 1;
          }
        } else if (!isInteractive()) {
          // no-prompt option
          getOutputStream().println();
          printSummaryTable();
          return 0;
        }

      } catch (LDAPConnectionException lce) {
        println(INFO_TASKINFO_LDAP_EXCEPTION.get(lce.getMessageObject()));
        return 1;
      } catch (Exception e) {
        println(LocalizableMessage.raw(StaticUtils.getExceptionMessage(e)));
        return 1;
      }
    }
    return 0;
  }
  /** {@inheritDoc} */
  public void beginDisplay(UserData data) {
    TreeSet<ServerDescriptor> array = orderServers(data.getRemoteWithNoReplicationPort().keySet());
    AuthenticationData authData = data.getReplicationOptions().getAuthenticationData();
    String newServerDisplay;
    if (authData != null) {
      newServerDisplay = authData.getHostName() + ":" + authData.getPort();
    } else {
      newServerDisplay = "";
    }
    if (!array.equals(orderedServers) || !newServerDisplay.equals(serverToConnectDisplay)) {
      serverToConnectDisplay = newServerDisplay;
      // Adds the required focus listeners to the fields.
      final FocusListener l =
          new FocusListener() {
            public void focusGained(FocusEvent e) {
              lastFocusComponent = e.getComponent();
            }

            public void focusLost(FocusEvent e) {}
          };
      lastFocusComponent = null;
      HashMap<String, String> hmOldValues = new HashMap<>();
      for (String id : hmFields.keySet()) {
        hmOldValues.put(id, hmFields.get(id).getText());
      }
      HashMap<String, Boolean> hmOldSecureValues = new HashMap<>();
      for (String id : hmCbs.keySet()) {
        hmOldSecureValues.put(id, hmCbs.get(id).isSelected());
      }
      orderedServers.clear();
      orderedServers.addAll(array);
      hmFields.clear();
      hmCbs.clear();
      hmLabels.clear();
      for (ServerDescriptor server : orderedServers) {
        String serverDisplay;
        if (server.getHostPort(false).equalsIgnoreCase(serverToConnectDisplay)) {
          serverDisplay = serverToConnectDisplay;
        } else {
          serverDisplay = server.getHostPort(true);
        }
        LabelFieldDescriptor desc =
            new LabelFieldDescriptor(
                LocalizableMessage.raw(serverDisplay),
                INFO_REPLICATION_PORT_TOOLTIP.get(),
                LabelFieldDescriptor.FieldType.TEXTFIELD,
                LabelFieldDescriptor.LabelType.PRIMARY,
                UIFactory.PORT_FIELD_SIZE);
        AuthenticationData auth = data.getRemoteWithNoReplicationPort().get(server);
        JTextComponent field = UIFactory.makeJTextComponent(desc, String.valueOf(auth.getPort()));
        String oldValue = hmOldValues.get(server.getId());
        if (oldValue != null) {
          field.setText(oldValue);
        }

        JLabel label = UIFactory.makeJLabel(desc);

        hmFields.put(server.getId(), field);
        label.setLabelFor(field);
        field.addFocusListener(l);
        if (lastFocusComponent == null) {
          lastFocusComponent = field;
        }

        hmLabels.put(server.getId(), label);

        JCheckBox cb =
            UIFactory.makeJCheckBox(
                INFO_SECURE_REPLICATION_LABEL.get(),
                INFO_SECURE_REPLICATION_TOOLTIP.get(),
                UIFactory.TextStyle.SECONDARY_FIELD_VALID);
        cb.setSelected(auth.useSecureConnection());
        Boolean oldSecureValue = hmOldSecureValues.get(server.getId());
        if (oldSecureValue != null) {
          cb.setSelected(oldSecureValue);
        }
        hmCbs.put(server.getId(), cb);
      }
      populateFieldsPanel();
    }
  }
Example #21
0
  /**
   * Updates the contents of the panel with the provided index.
   *
   * @param index the index descriptor to be used to update the panel.
   */
  public void update(IndexDescriptor index) {
    ignoreCheckSave = true;
    setPrimaryValid(lEntryLimit);
    setPrimaryValid(lType);
    name.setText(index.getName());
    backendName.setText(index.getBackend().getBackendID());
    titlePanel.setDetails(LocalizableMessage.raw(index.getName()));
    entryLimit.setText(String.valueOf(index.getEntryLimit()));
    approximate.setSelected(false);
    equality.setSelected(false);
    ordering.setSelected(false);
    substring.setSelected(false);
    presence.setSelected(false);
    for (IndexTypeDescriptor type : index.getTypes()) {
      switch (type) {
        case APPROXIMATE:
          approximate.setSelected(true);
          break;
        case PRESENCE:
          presence.setSelected(true);
          break;
        case EQUALITY:
          equality.setSelected(true);
          break;
        case ORDERING:
          ordering.setSelected(true);
          break;
        case SUBSTRING:
          substring.setSelected(true);
          break;
      }
    }

    JComponent[] comps = {entryLimit, lType, typesPanel, lEntryLimit};

    for (JComponent comp : comps) {
      comp.setVisible(!index.isDatabaseIndex());
    }

    AttributeType attr = index.getAttributeType();
    repopulateTypesPanel(attr);

    if (index.isDatabaseIndex()) {
      entryLimit.setText("");
    }
    saveChanges.setVisible(!index.isDatabaseIndex());
    deleteIndex.setVisible(!index.isDatabaseIndex());
    if (index.isDatabaseIndex()) {
      Utilities.setWarningLabel(warning, NON_CONFIGURABLE_INDEX);
      warning.setVisible(true);
    } else if (getInfo() != null) {
      if (getInfo().mustReindex(index)) {
        Utilities.setWarningLabel(warning, INDEX_MODIFIED);
        warning.setVisible(true);
        warning.setVerticalTextPosition(SwingConstants.TOP);
      } else {
        warning.setVisible(false);
      }
    }
    this.index = index;

    ignoreCheckSave = false;
    checkSaveButton();

    scrollListener.updateBorder();
  }
Example #22
0
 private DirectoryException unwillingToPerformOperation(String operationName) {
   String msg = "The null backend does not support " + operationName + " operation";
   return new DirectoryException(ResultCode.UNWILLING_TO_PERFORM, LocalizableMessage.raw(msg));
 }
Example #23
0
 private DirectoryException newDirectoryException(Exception e) {
   LocalizableMessage message = LocalizableMessage.raw(e.getMessage());
   return new DirectoryException(DirectoryServer.getServerErrorResultCode(), message, e);
 }
Example #24
0
    /** {@inheritDoc} */
    @Override
    public MenuResult<TaskEntry> invoke(ManageTasks app) throws ClientException {
      LocalizableMessage m;
      TaskEntry taskEntry;
      try {
        taskEntry = app.getTaskClient().getTaskEntry(taskId);

        TableBuilder table = new TableBuilder();
        table.appendHeading(INFO_TASKINFO_DETAILS.get());

        table.startRow();
        table.appendCell(INFO_TASKINFO_FIELD_ID.get());
        table.appendCell(taskEntry.getId());

        table.startRow();
        table.appendCell(INFO_TASKINFO_FIELD_TYPE.get());
        table.appendCell(taskEntry.getType());

        table.startRow();
        table.appendCell(INFO_TASKINFO_FIELD_STATUS.get());
        table.appendCell(taskEntry.getState());

        table.startRow();
        table.appendCell(INFO_TASKINFO_FIELD_SCHEDULED_START.get());

        if (TaskState.isRecurring(taskEntry.getTaskState())) {
          m = taskEntry.getScheduleTab();
          table.appendCell(m);
        } else {
          m = taskEntry.getScheduledStartTime();
          if (m == null || m.equals(LocalizableMessage.EMPTY)) {
            table.appendCell(INFO_TASKINFO_IMMEDIATE_EXECUTION.get());
          } else {
            table.appendCell(m);
          }

          table.startRow();
          table.appendCell(INFO_TASKINFO_FIELD_ACTUAL_START.get());
          table.appendCell(taskEntry.getActualStartTime());

          table.startRow();
          table.appendCell(INFO_TASKINFO_FIELD_COMPLETION_TIME.get());
          table.appendCell(taskEntry.getCompletionTime());
        }

        writeMultiValueCells(
            table, INFO_TASKINFO_FIELD_DEPENDENCY.get(), taskEntry.getDependencyIds());

        table.startRow();
        table.appendCell(INFO_TASKINFO_FIELD_FAILED_DEPENDENCY_ACTION.get());
        m = taskEntry.getFailedDependencyAction();
        table.appendCell(m != null ? m : INFO_TASKINFO_NONE.get());

        writeMultiValueCells(
            table,
            INFO_TASKINFO_FIELD_NOTIFY_ON_COMPLETION.get(),
            taskEntry.getCompletionNotificationEmailAddresses(),
            INFO_TASKINFO_NONE_SPECIFIED.get());

        writeMultiValueCells(
            table,
            INFO_TASKINFO_FIELD_NOTIFY_ON_ERROR.get(),
            taskEntry.getErrorNotificationEmailAddresses(),
            INFO_TASKINFO_NONE_SPECIFIED.get());

        StringWriter sw = new StringWriter();
        TextTablePrinter tablePrinter = new TextTablePrinter(sw);
        tablePrinter.setTotalWidth(80);
        tablePrinter.setIndentWidth(INDENT);
        tablePrinter.setColumnWidth(1, 0);
        table.print(tablePrinter);
        app.getOutputStream().println();
        app.getOutputStream().println(LocalizableMessage.raw(sw.getBuffer().toString()));

        // Create a table for the task options
        table = new TableBuilder();
        table.appendHeading(INFO_TASKINFO_OPTIONS.get(taskEntry.getType()));
        Map<LocalizableMessage, List<String>> taskSpecificAttrs =
            taskEntry.getTaskSpecificAttributeValuePairs();
        for (LocalizableMessage attrName : taskSpecificAttrs.keySet()) {
          table.startRow();
          table.appendCell(attrName);
          List<String> values = taskSpecificAttrs.get(attrName);
          if (!values.isEmpty()) {
            table.appendCell(values.get(0));
          }
          if (values.size() > 1) {
            for (int i = 1; i < values.size(); i++) {
              table.startRow();
              table.appendCell();
              table.appendCell(values.get(i));
            }
          }
        }
        sw = new StringWriter();
        tablePrinter = new TextTablePrinter(sw);
        tablePrinter.setTotalWidth(80);
        tablePrinter.setIndentWidth(INDENT);
        tablePrinter.setColumnWidth(1, 0);
        table.print(tablePrinter);
        app.getOutputStream().println(LocalizableMessage.raw(sw.getBuffer().toString()));

        // Print the last log message if any
        List<LocalizableMessage> logs = taskEntry.getLogMessages();
        if (logs != null && !logs.isEmpty()) {
          // Create a table for the last log entry
          table = new TableBuilder();
          table.appendHeading(INFO_TASKINFO_FIELD_LAST_LOG.get());
          table.startRow();
          table.appendCell(logs.get(logs.size() - 1));

          sw = new StringWriter();
          tablePrinter = new TextTablePrinter(sw);
          tablePrinter.setTotalWidth(80);
          tablePrinter.setIndentWidth(INDENT);
          tablePrinter.setColumnWidth(0, 0);
          table.print(tablePrinter);
          app.getOutputStream().println(LocalizableMessage.raw(sw.getBuffer().toString()));
        }

        app.getOutputStream().println();
      } catch (Exception e) {
        app.println(ERR_TASKINFO_RETRIEVING_TASK_ENTRY.get(taskId, e.getMessage()));
        return MenuResult.again();
      }
      return MenuResult.success(taskEntry);
    }