|
| 1 | +package io.javaoperatorsdk.operator.processing.annotation; |
| 2 | + |
| 3 | +import javax.annotation.processing.ProcessingEnvironment; |
| 4 | +import javax.tools.StandardLocation; |
| 5 | +import java.io.BufferedReader; |
| 6 | +import java.io.IOException; |
| 7 | +import java.io.InputStreamReader; |
| 8 | +import java.io.PrintWriter; |
| 9 | +import java.util.Map; |
| 10 | +import java.util.concurrent.ConcurrentHashMap; |
| 11 | +import java.util.stream.Collectors; |
| 12 | + |
| 13 | +import static io.javaoperatorsdk.operator.ControllerUtils.CONTROLLERS_RESOURCE_PATH; |
| 14 | + |
| 15 | +public class ControllersResourceWriter { |
| 16 | + private Map<String, String> mappings = new ConcurrentHashMap<>(); |
| 17 | + private final ProcessingEnvironment processingEnvironment; |
| 18 | + |
| 19 | + public ControllersResourceWriter(ProcessingEnvironment processingEnvironment) { |
| 20 | + this.processingEnvironment = processingEnvironment; |
| 21 | + } |
| 22 | + |
| 23 | + public ControllersResourceWriter loadExistingMappings() { |
| 24 | + try { |
| 25 | + final var readonlyResource = processingEnvironment |
| 26 | + .getFiler() |
| 27 | + .getResource(StandardLocation.CLASS_OUTPUT, "", CONTROLLERS_RESOURCE_PATH); |
| 28 | + |
| 29 | + final var existingLines = new BufferedReader(new InputStreamReader(readonlyResource.openInputStream())) |
| 30 | + .lines() |
| 31 | + .map(l -> l.split(",")) |
| 32 | + .collect(Collectors.toMap(parts -> parts[0], parts -> parts[1])); |
| 33 | + mappings.putAll(existingLines); |
| 34 | + } catch (IOException e) { |
| 35 | + } |
| 36 | + return this; |
| 37 | + } |
| 38 | + |
| 39 | + public ControllersResourceWriter add(String controllerClassName, String customResourceTypeName) { |
| 40 | + this.mappings.put(controllerClassName, customResourceTypeName); |
| 41 | + return this; |
| 42 | + } |
| 43 | + |
| 44 | + public void flush() { |
| 45 | + try { |
| 46 | + final var resource = processingEnvironment |
| 47 | + .getFiler() |
| 48 | + .createResource(StandardLocation.CLASS_OUTPUT, "", CONTROLLERS_RESOURCE_PATH); |
| 49 | + final var printWriter = new PrintWriter(resource.openOutputStream()); |
| 50 | + for (Map.Entry<String, String> entry : mappings.entrySet()) { |
| 51 | + printWriter.println(entry.getKey() + "," + entry.getValue()); |
| 52 | + } |
| 53 | + } catch (IOException e) { |
| 54 | + throw new RuntimeException(e); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments