@Test
  public void testImportByConfig() {
    final ImpExResource mediaRes =
        new StreamBasedImpExResource(
            new ByteArrayInputStream("INSERT Language;isocode;active\n;test;true".getBytes()),
            CSVConstants.HYBRIS_ENCODING);

    final ImportConfig config = new ImportConfig();
    config.setScript(mediaRes);

    final ImportResult result = importService.importData(config);
    assertNotNull(result);
    assertTrue(result.isSuccessful());
    assertFalse(result.isError());
    assertFalse(result.hasUnresolvedLines());
    assertTrue(result.isFinished());
    assertNotNull("Language 'test' was not imported", getOrCreateLanguage("test"));
  }
  @Test
  public void shouldSeeFinishedStateForAsncImport() throws InterruptedException {
    // given
    final ImportConfig config = new ImportConfig();
    config.setScript( //
        "INSERT Title;code[unique=true]\n" //
            + ";foo;\n" //
            + "\"#% java.lang.Thread.sleep(2000);\";\n" //
            + ";bar;\n" //
        );
    config.setSynchronous(false);
    config.setFailOnError(true);
    config.setRemoveOnSuccess(false);
    config.setEnableCodeExecution(Boolean.TRUE);

    // when
    final long now = System.currentTimeMillis();
    final ImportResult importResult = importService.importData(config);
    final long maxWait = System.currentTimeMillis() + (30 * 1000);
    do {
      Thread.sleep(500);
    } while (!importResult.isFinished() && System.currentTimeMillis() < maxWait);

    // then
    assertThat(System.currentTimeMillis() - now).isGreaterThanOrEqualTo(2000);
    assertThat(importResult.isFinished()).isTrue();
    assertThat(importResult.isError()).isFalse();
  }
  @Test
  public void shouldImportScriptWithLegacyModeOffWhenGlobalSwitchIsOnUsingImportConfig() {
    // given
    Config.setParameter(ImpExConstants.Params.LEGACY_MODE_KEY, "true");
    final ImpExResource mediaRes =
        new StreamBasedImpExResource(
            new ByteArrayInputStream("INSERT Language;isocode;active\n;test;true".getBytes()),
            CSVConstants.HYBRIS_ENCODING);
    final ImportConfig config = new ImportConfig();
    config.setLegacyMode(Boolean.FALSE);
    config.setSynchronous(true);
    config.setFailOnError(true);
    config.setScript(mediaRes);
    config.setRemoveOnSuccess(false);

    // when
    final ImportResult importResult = importService.importData(config);

    // then
    assertThat(importResult.isFinished()).isTrue();
    assertThat(importResult.isError()).isFalse();
    assertThat(Boolean.parseBoolean(Config.getParameter(ImpExConstants.Params.LEGACY_MODE_KEY)))
        .isTrue();
    assertThat(importResult.getCronJob().getLegacyMode()).isFalse();
  }
  /**
   * Primary user method for importing a number of import candidates.
   *
   * @param config The configuration information.
   * @param candidates Hosts information about the files to import.
   * @return if the import did not exit because of an error
   */
  public boolean importCandidates(ImportConfig config, ImportCandidates candidates) {
    List<ImportContainer> containers = candidates.getContainers();
    if (containers != null) {
      int numDone = 0;
      for (int index = 0; index < containers.size(); index++) {
        ImportContainer ic = containers.get(index);
        ImportTarget target = config.getTarget();
        if (target != null) {
          try {
            IObject obj = target.load(store, ic);
            if (!(obj instanceof Annotation)) {
              ic.setTarget(obj);
            } else {
              // This is likely a "post-processing" annotation
              // so that we don't have to resolve the target
              // until later.
              ic.getCustomAnnotationList().add((Annotation) obj);
            }
          } catch (Exception e) {
            log.error("Could not load target: {}", target);
            throw new RuntimeException("Failed to load target", e);
          }
        }

        if (config.checksumAlgorithm.get() != null) {
          ic.setChecksumAlgorithm(config.checksumAlgorithm.get());
        }

        try {
          importImage(ic, index, numDone, containers.size());
          numDone++;
        } catch (Throwable t) {
          String message = "Error on import";
          if (t instanceof ServerError) {
            final ServerError se = (ServerError) t;
            if (StringUtils.isNotBlank(se.message)) {
              message += ": " + se.message;
            }
          }
          log.error(message, t);
          if (!config.contOnError.get()) {
            log.info("Exiting on error");
            return false;
          } else {
            log.info("Continuing after error");
          }
        }
      }
    }
    return true;
  }
  private void internalImportByConfigWithError(final boolean failOnError) {
    try {
      TestUtils.disableFileAnalyzer();
      final ImpExResource mediaRes =
          new StreamBasedImpExResource(
              new ByteArrayInputStream(
                  "UPDATE Language;isocode[unique=true];active\n;test;true".getBytes()),
              CSVConstants.HYBRIS_ENCODING);

      final ImportConfig config = new ImportConfig();
      config.setScript(mediaRes);
      config.setFailOnError(failOnError);

      final ImportResult result = importService.importData(config);
      assertNotNull(result);
      assertFalse(result.isSuccessful());
      assertTrue(result.isError());
      assertTrue(result.hasUnresolvedLines());
      assertNotNull(result.getUnresolvedLines());
      assertTrue(result.isFinished());
    } finally {
      TestUtils.enableFileAnalyzer();
    }
  }
 public static ImportConfig valueOf(ImportMode importMode) {
   ImportConfig config = new ImportConfig();
   switch (importMode) {
     case PARENT_AND_CHILD:
       config.exactMatch = ImportType.PREFER_THEIRS;
       config.possibleMatch = ImportType.PREFER_THEIRS;
       config.noMatch = ImportType.CREATE;
       config.confirmExactMatch = false;
       config.confirmPossibleMatch = true;
       config.confirmNoMatch = false;
       return config;
     case PEER_TO_PEER:
       config.exactMatch = ImportType.PREFER_MINE;
       config.possibleMatch = ImportType.PREFER_MINE;
       config.noMatch = ImportType.CREATE;
       config.confirmExactMatch = true;
       config.confirmPossibleMatch = true;
       config.confirmNoMatch = false;
       return config;
     case TEST:
       config.exactMatch = ImportType.PREFER_THEIRS;
       config.possibleMatch = ImportType.CREATE;
       config.noMatch = ImportType.CREATE;
       config.confirmExactMatch = false;
       config.confirmPossibleMatch = false;
       config.confirmNoMatch = false;
       return config;
     case MIRROR:
       config.exactMatch = ImportType.OVERWRITE_MINE;
       config.possibleMatch = ImportType.OVERWRITE_MINE;
       config.noMatch = ImportType.CREATE;
       config.confirmExactMatch = false;
       config.confirmPossibleMatch = false;
       config.confirmNoMatch = false;
       return config;
     default:
       return config;
   }
 }