protected void validate(CPathMappingItem pathItem) throws InvalidConfigurationException {
   ValidationResponse response =
       this.validator.validateGroupsSettingPathMappingItem(null, pathItem);
   if (!response.isValid()) {
     throw new InvalidConfigurationException(response);
   }
 }
  public void updateCatalogEntry(String catalogId, String entryId, CCatalogEntry entry)
      throws InvalidConfigurationException {
    ValidationResponse vr = validator.validateCatalogEntry(entry);
    if (vr.getValidationErrors().size() > 0) {
      throw new InvalidConfigurationException(vr);
    }

    lock.lock();

    try {

      CCatalog catalog = getCatalog(catalogId);
      CCatalogEntry current = getCatalogEntry(catalogId, entryId);

      if (current != null) {
        catalog.getEntries().remove(current);
        catalog.getEntries().add(entry);

        save();
      }

    } finally {
      lock.unlock();
    }
  }
  public ValidationResponse validate(final CCapability capability, final boolean isCreateMode) {
    final ValidationResponse response = new ValidationResponse();

    if (!isCreateMode && StringUtils.isEmpty(capability.getId())) {
      final ValidationMessage msg = new ValidationMessage("id", "Capability ID cannot be empty.");

      response.addValidationError(msg);
    }
    if (StringUtils.isEmpty(capability.getName())) {
      final ValidationMessage msg =
          new ValidationMessage("name", "Capability name cannot be empty.");

      response.addValidationError(msg);
    }
    if (StringUtils.isEmpty(capability.getTypeId())) {
      final ValidationMessage msg =
          new ValidationMessage("typeId", "Capability type cannot be empty.");

      response.addValidationError(msg);
    }

    for (final CCapabilityProperty property : capability.getProperties()) {
      if (StringUtils.isEmpty(property.getKey())) {
        final ValidationMessage msg =
            new ValidationMessage("type", "Capability properties cannot cannot have an empty key.");

        response.addValidationError(msg);
        break;
      }
    }

    return response;
  }
  @Test
  public void testBad2() throws Exception {
    // get start with the default config
    this.copyDefaultConfigToPlace();
    this.copyResource("/META-INF/nexus/default-oss-nexus.xml", getNexusConfiguration());
    Configuration config = this.loadNexusConfig(new File(this.getNexusConfiguration()));

    // make it bad

    // invalid policy
    CRepository invalidPolicyRepo = config.getRepositories().get(0);
    Xpp3Dom externalConfig = (Xpp3Dom) invalidPolicyRepo.getExternalConfiguration();
    ExternalConfigUtil.setNodeValue(externalConfig, "repositoryPolicy", "badPolicy");

    // duplicate the repository id
    for (CRepository repo : config.getRepositories()) {
      if (!repo.getId().equals("central")) {
        // duplicate
        repo.setId("central");
        break;
      }
    }

    // TODO: add more errors here

    // now validate it
    ValidationResponse response = underTest.validateModel(new ValidationRequest(config));

    assertThat(response.isValid(), is(false));
    assertThat(response.isModified(), is(false));

    assertThat(response.getValidationErrors(), hasSize(greaterThan(0)));
    assertThat(response.getValidationWarnings(), hasSize(0));
  }
 public ValidationResponse validateAnonymousUsername(
     SecurityValidationContext context, String anonymousUsername) {
   // we are not currently doing anything here
   ValidationResponse validationResponse = new ValidationResponse();
   validationResponse.setContext(context);
   return validationResponse;
 }
 public void validateTime(String key, Date date) throws InvalidConfigurationException {
   if (date.before(new Date())) {
     ValidationResponse vr = new ApplicationValidationResponse();
     ValidationMessage vm = new ValidationMessage(key, "Time cannot be in the past.");
     vr.addValidationError(vm);
     throw new InvalidConfigurationException(vr);
   }
 }
  protected void validateRepository(CRepository settings, boolean create)
      throws ConfigurationException {
    ApplicationValidationContext ctx = getRepositoryValidationContext();

    if (!create && !StringUtils.isEmpty(settings.getId())) {
      // remove "itself" from the list to avoid hitting "duplicate repo" problem
      ctx.getExistingRepositoryIds().remove(settings.getId());
    }

    ValidationResponse vr = configurationValidator.validateRepository(ctx, settings);

    if (!vr.isValid()) {
      throw new InvalidConfigurationException(vr);
    }
  }
  public ValidationResponse validateModel(
      SecurityValidationContext context, ValidationRequest<SecurityConfiguration> request) {
    ValidationResponse validationResponse = new ValidationResponse();
    validationResponse.setContext(context);

    SecurityConfiguration configuration = request.getConfiguration();

    validationResponse.append(
        this.validateAnonymousUsername(context, configuration.getAnonymousUsername()));
    validationResponse.append(
        this.validateAnonymousPassword(context, configuration.getAnonymousPassword()));
    validationResponse.append(this.validateRealms(context, configuration.getRealms()));

    return validationResponse;
  }
  public ValidationResponse validateRealms(SecurityValidationContext context, List<String> realms) {
    ValidationResponse validationResponse = new ValidationResponse();
    validationResponse.setContext(context);

    if ((context.getSecurityConfiguration() != null
            && context.getSecurityConfiguration().isEnabled())
        || context.getSecurityConfiguration() == null) {
      if (realms.size() < 1) {
        validationResponse.addValidationError(
            "Security is enabled, You must have at least one realm enabled.");
      }
      // TODO: we should also try to load each one to see if it exists
    }

    return validationResponse;
  }
  public void createCatalog(CCatalog catalog) throws InvalidConfigurationException {
    lock.lock();

    try {
      ValidationResponse vr = validator.validateCatalog(catalog);
      if (vr.getValidationErrors().size() > 0) {
        throw new InvalidConfigurationException(vr);
      }

      getConfiguration().getCatalogs().add(catalog);

      save();
    } finally {
      lock.unlock();
    }
  }
  @Test
  public void testNexus1710Good() throws Exception {
    // this is after fix: groupId is appended by "-group" to resolve clash
    ValidationResponse response =
        underTest.validateModel(
            new ValidationRequest(
                getConfigurationFromStream(
                    getClass()
                        .getResourceAsStream(
                            "/org/sonatype/nexus/configuration/upgrade/nexus1710/nexus.xml.result"))));

    assertThat(response.isValid(), is(true));
    assertThat(response.isModified(), is(false));

    assertThat(response.getValidationErrors(), hasSize(0));
    assertThat(response.getValidationWarnings(), hasSize(0));
  }
  public void validateStartDate(String date) throws InvalidConfigurationException {
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date(Long.parseLong(date)));

    Calendar nowCal = Calendar.getInstance();
    nowCal.setTime(new Date());

    // This is checking just the year/month/day, time isn't of concern right now
    if (cal.before(nowCal)
        && (cal.get(Calendar.YEAR) != nowCal.get(Calendar.YEAR)
            || cal.get(Calendar.MONTH) != nowCal.get(Calendar.MONTH)
            || cal.get(Calendar.DAY_OF_YEAR) != nowCal.get(Calendar.DAY_OF_YEAR))) {
      ValidationResponse vr = new ApplicationValidationResponse();
      ValidationMessage vm = new ValidationMessage("startDate", "Date cannot be in the past.");
      vr.addValidationError(vm);
      throw new InvalidConfigurationException(vr);
    }
  }
  @SuppressWarnings("unchecked")
  public ValidationResponse validateModel(final ValidationRequest request) {
    final ValidationResponse response = new ValidationResponse();

    final Configuration configuration = (Configuration) request.getConfiguration();

    if (configuration == null) {
      final ValidationMessage msg =
          new ValidationMessage("*", "No configuration available to validate");

      response.addValidationError(msg);
    } else {
      for (final CCapability capability : configuration.getCapabilities()) {
        response.append(validate(capability, false));
      }
    }

    return response;
  }
  public synchronized void saveConfiguration() throws IOException {
    if (applyConfiguration()) {
      // TODO: when NEXUS-2215 is fixed, this should be remove/moved/cleaned
      // START <<<
      // validate before we do anything
      ValidationRequest request = new ValidationRequest(configurationSource.getConfiguration());
      ValidationResponse response = configurationValidator.validateModel(request);
      if (!response.isValid()) {
        this.getLogger()
            .error("Saving nexus configuration caused unexpected error:\n" + response.toString());
        throw new IOException(
            "Saving nexus configuration caused unexpected error:\n" + response.toString());
      }
      // END <<<

      configurationSource.storeConfiguration();

      // we successfully saved config
      eventBus.post(new ConfigurationSaveEvent(this));
    }
  }
  public void addCatalogEntry(String catalogId, CCatalogEntry catalogEntry)
      throws InvalidConfigurationException {
    CCatalog catalog = readCatalog(catalogId);

    catalogEntry.setId(idGenerator.generateId());

    ValidationResponse vr = validator.validateCatalogEntry(catalogEntry);
    if (vr.getValidationErrors().size() > 0) {
      throw new InvalidConfigurationException(vr);
    }

    lock.lock();

    try {

      catalog.addEntry(catalogEntry);
      save();
    } finally {
      lock.unlock();
    }
  }
  /**
   * A method to append a validation response to this validation response. The errors list and
   * warnings list are simply appended, and the isValid is logically AND-ed and isModified is
   * logically OR-ed.
   */
  public void append(ValidationResponse validationResponse) {
    for (ValidationMessage msg : validationResponse.getValidationErrors()) {
      if (getValidationError(msg.getKey()) != null) {
        msg.setKey(msg.getKey() + "(" + key++ + ")");
      }

      addValidationError(msg);
    }

    for (ValidationMessage msg : validationResponse.getValidationWarnings()) {
      if (getValidationWarning(msg.getKey()) != null) {
        msg.setKey(msg.getKey() + "(" + key++ + ")");
      }

      addValidationWarning(msg);
    }

    setValid(isValid() && validationResponse.isValid());

    setModified(isModified() || validationResponse.isModified());
  }
  public void createOrUpdateCatalog(CCatalog catalog) throws InvalidConfigurationException {
    ValidationResponse vr = validator.validateCatalog(catalog);
    if (vr.getValidationErrors().size() > 0) {
      throw new InvalidConfigurationException(vr);
    }

    lock.lock();

    try {

      CCatalog current = getCatalog(catalog.getId());

      if (current != null) {
        getConfiguration().getCatalogs().remove(current);
      }

      getConfiguration().getCatalogs().add(catalog);

      save();
    } finally {
      lock.unlock();
    }
  }
  @Test
  public void testBad1() throws Exception {
    // get start with the default config
    this.copyDefaultConfigToPlace();
    Configuration config = this.loadNexusConfig(new File(this.getNexusConfiguration()));

    // make it bad

    // remove the name from a repository
    CRepository missingNameRepo = (CRepository) config.getRepositories().get(0);
    missingNameRepo.setName(null);

    // TDOD add 2 more warnings

    // wrong shadow type
    CRepository badShadow = new DefaultCRepository();
    badShadow.setId("badShadow");
    badShadow.setName("Does not follow");
    badShadow.setProviderRole(ShadowRepository.class.getName());
    badShadow.setProviderHint("m2-m1-shadow");
    // Manipulate the dom
    Xpp3Dom externalConfig = new Xpp3Dom("externalConfiguration");
    badShadow.setExternalConfiguration(externalConfig);
    ExternalConfigUtil.setNodeValue(externalConfig, "masterRepositoryId", "non-existent");
    config.addRepository(badShadow);

    // now validate it
    ValidationResponse response = underTest.validateModel(new ValidationRequest(config));

    assertThat(response.getValidationWarnings(), hasSize(1));
    assertThat(response.getValidationErrors(), hasSize(0));

    // codehaus-snapshots has no name, it will be defaulted
    assertThat(response.isModified(), is(true));

    assertThat(response.isValid(), is(true));
  }
  @Test
  public void testNexus1710Bad() throws Exception {

    // this one is easy because you can compare:
    // /org/sonatype/nexus/configuration/upgrade/nexus1710/nexus.xml.result-bad
    // with
    // /org/sonatype/nexus/configuration/upgrade/nexus1710/nexus.xml.result
    // and you have the diff, and you already have to manually update the good one.

    // this was before fix: groupId/repoId name clash
    ValidationResponse response =
        underTest.validateModel(
            new ValidationRequest(
                getConfigurationFromStream(
                    getClass()
                        .getResourceAsStream(
                            "/org/sonatype/nexus/configuration/upgrade/nexus1710/nexus.xml.result-bad"))));

    assertThat(response.isValid(), is(false));
    assertThat(response.isModified(), is(false));

    assertThat(response.getValidationErrors(), hasSize(1));
    assertThat(response.getValidationWarnings(), hasSize(0));
  }
  @Test
  public void repoEmptyId() {
    ApplicationValidationContext ctx = new ApplicationValidationContext();

    CRepository repo = new CRepository();
    repo.setLocalStatus(LocalStatus.IN_SERVICE.toString());
    repo.setName("name");
    ValidationResponse response = underTest.validateRepository(ctx, repo);

    assertThat(response.isValid(), is(false));
    assertThat(response.isModified(), is(false));

    assertThat(response.getValidationErrors(), hasSize(1));
    assertThat(response.getValidationWarnings(), hasSize(0));
    assertThat(response.getValidationErrors().get(0), hasKey("id"));
  }
  public Configuration loadConfiguration() throws ConfigurationException, IOException {
    // propagate call and fill in defaults too
    nexusDefaults.loadConfiguration();

    if (getConfigurationFile() == null || getConfigurationFile().getAbsolutePath().contains("${")) {
      throw new ConfigurationException(
          "The configuration file is not set or resolved properly: "
              + getConfigurationFile().getAbsolutePath());
    }

    if (!getConfigurationFile().exists()) {
      getLogger()
          .warn("No configuration file in place, copying the default one and continuing with it.");

      // get the defaults and stick it to place
      setConfiguration(nexusDefaults.getConfiguration());

      saveConfiguration(getConfigurationFile());

      configurationDefaulted = true;
    } else {
      configurationDefaulted = false;
    }

    try {
      loadConfiguration(getConfigurationFile());

      // was able to load configuration w/o upgrading it
      setConfigurationUpgraded(false);
    } catch (ConfigurationException e) {
      getLogger().info("Configuration file is invalid, attempting upgrade");

      upgradeConfiguration(getConfigurationFile());

      // had to upgrade configuration before I was able to load it
      setConfigurationUpgraded(true);

      loadConfiguration(getConfigurationFile());

      // if the configuration is upgraded we need to reload the security.
      // it would be great if this was put somewhere else, but I am out of ideas.
      // the problem is the default security was already loaded with the security-system component
      // was loaded
      // so it has the defaults, the upgrade from 1.0.8 -> 1.4 moves security out of the nexus.xml
      // and we cannot use the 'correct' way of updating the info, because that would cause an
      // infinit loop
      // loading the nexus.xml
      this.eventMulticaster.notifyEventListeners(new SecurityConfigurationChangedEvent(null));
    }

    upgradeNexusVersion();

    ValidationResponse vResponse =
        getConfigurationValidator().validateModel(new ValidationRequest(getConfiguration()));

    setValidationResponse(vResponse);

    if (vResponse.isValid()) {
      if (vResponse.isModified()) {
        getLogger().info("Validation has modified the configuration, storing the changes.");

        storeConfiguration();
      }

      return getConfiguration();
    } else {
      throw new InvalidConfigurationException(vResponse);
    }
  }