All Downloads are FREE. Search and download functionalities are using the official Maven repository.

tech.jhipster.lite.module.domain.replacement.TextNeedleBeforeReplacer Maven / Gradle / Ivy

There is a newer version: 1.22.0
Show newest version
package tech.jhipster.lite.module.domain.replacement;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import tech.jhipster.lite.module.domain.JHipsterModule;
import tech.jhipster.lite.shared.error.domain.Assert;

public record TextNeedleBeforeReplacer(ReplacementCondition condition, String text) implements ElementReplacer {
  public TextNeedleBeforeReplacer {
    Assert.notNull("condition", condition);
    Assert.notBlank("text", text);
  }

  @Override
  public boolean notMatchIn(String content) {
    Assert.notNull("content", content);

    return !content.contains(text());
  }

  @Override
  public BiFunction replacement() {
    return (content, replacement) -> {
      List needlesLinesIndexes = needlesLinesIndexes(content);

      if (needlesLinesIndexes.isEmpty()) {
        return content;
      }

      String replacementBlock = replacement + JHipsterModule.LINE_BREAK;
      return String.join(replacementBlock, buildBlocks(content, needlesLinesIndexes));
    };
  }

  private List needlesLinesIndexes(String content) {
    List indexes = new ArrayList<>();

    int textIndex = content.indexOf(text());
    while (textIndex != -1) {
      indexes.add(lineIndex(content, textIndex));

      textIndex = content.indexOf(text(), textIndex + text().length());
    }

    return indexes;
  }

  private int lineIndex(String content, int textIndex) {
    int index = content.substring(0, textIndex).lastIndexOf(JHipsterModule.LINE_BREAK);

    if (index == -1) {
      return 0;
    }

    return index + 1;
  }

  private List buildBlocks(String content, List needlesLinesIndexes) {
    List blocks = new ArrayList<>();

    for (int index = 0; index < needlesLinesIndexes.size(); index++) {
      blocks.add(content.substring(blockStart(needlesLinesIndexes, index), needlesLinesIndexes.get(index)));
    }

    blocks.add(content.substring(needlesLinesIndexes.getLast()));

    return blocks;
  }

  private int blockStart(List needlesLinesIndexes, int index) {
    if (index == 0) {
      return 0;
    }

    return needlesLinesIndexes.get(index - 1);
  }

  @Override
  public String searchMatcher() {
    return text();
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy