diff options
Diffstat (limited to 'module/ri-engine/src/main/java/io/trygvis')
19 files changed, 221 insertions, 475 deletions
diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/core/Problem.java b/module/ri-engine/src/main/java/io/trygvis/rules/core/Problem.java deleted file mode 100644 index 04d1af3..0000000 --- a/module/ri-engine/src/main/java/io/trygvis/rules/core/Problem.java +++ /dev/null @@ -1,11 +0,0 @@ -package io.trygvis.rules.core; - -public class Problem { - public final String message; - public final Object object; - - public Problem(String message, Object object) { - this.message = message; - this.object = object; - } -} diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/dba/Cluster.java b/module/ri-engine/src/main/java/io/trygvis/rules/dba/Cluster.java deleted file mode 100644 index 0b65aaa..0000000 --- a/module/ri-engine/src/main/java/io/trygvis/rules/dba/Cluster.java +++ /dev/null @@ -1,13 +0,0 @@ -package io.trygvis.rules.dba; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; - -@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "name") -public class Cluster { - public String name; - - public Cluster(String name) { - this.name = name; - } -} diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/dba/Container.java b/module/ri-engine/src/main/java/io/trygvis/rules/dba/Container.java deleted file mode 100644 index 3888661..0000000 --- a/module/ri-engine/src/main/java/io/trygvis/rules/dba/Container.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.trygvis.rules.dba; - -import com.fasterxml.jackson.annotation.JsonIdentityReference; -import io.trygvis.rules.machine.Machine; -import io.trygvis.rules.machine.MachineSpecification; - -//@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") -public class Container { - public final String id; - -// @JsonIdentityReference(alwaysAsId = true) - public final Cluster cluster; - public final String name; - public final String machineRole; - public final String image; - public final String tag; - - private Machine machine; - public final MachineSpecification machineSpecification; - - public Container(Cluster cluster, String name, String machineRole, String image, String tag, - MachineSpecification machineSpecification) { - this.id = cluster.name + "-" + name; - this.cluster = cluster; - this.name = name; - this.machineRole = machineRole; - this.image = image; - this.tag = tag; - this.machineSpecification = machineSpecification; - } - - public Cluster getCluster() { - return cluster; - } - - public String getName() { - return name; - } - - public String getMachineRole() { - return machineRole; - } - - public String getImage() { - return image; - } - - public String getTag() { - return tag; - } - - public Machine getMachine() { - return machine; - } - - public void setMachine(Machine machine) { - this.machine = machine; - } -} diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/dns/DnsEntry.java b/module/ri-engine/src/main/java/io/trygvis/rules/dns/DnsEntry.java deleted file mode 100644 index 105ef79..0000000 --- a/module/ri-engine/src/main/java/io/trygvis/rules/dns/DnsEntry.java +++ /dev/null @@ -1,27 +0,0 @@ -package io.trygvis.rules.dns; - -public class DnsEntry { - public String fqdn; - public String type; - - public DnsEntry(String fqdn, String type) { - this.fqdn = fqdn; - this.type = type; - } - - public static DnsEntry a(String fqdn) { - return new DnsEntry(fqdn, "A"); - } - - public static DnsEntry aaaa(String fqdn) { - return new DnsEntry(fqdn, "AAAA"); - } - - public String getFqdn() { - return fqdn; - } - - public String getType() { - return type; - } -} diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/dns/DnsEntryTerraformExpression.java b/module/ri-engine/src/main/java/io/trygvis/rules/dns/DnsEntryTerraformExpression.java deleted file mode 100644 index 79bf934..0000000 --- a/module/ri-engine/src/main/java/io/trygvis/rules/dns/DnsEntryTerraformExpression.java +++ /dev/null @@ -1,21 +0,0 @@ -package io.trygvis.rules.dns; - -public class DnsEntryTerraformExpression { - public DnsEntry entry; - public String key; - public String expression; - - public DnsEntryTerraformExpression(DnsEntry entry, String key, String expression) { - this.entry = entry; - this.key = key; - this.expression = expression; - } - - public String getKey() { - return key; - } - - public String getExpression() { - return expression; - } -} diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/dns/DnsZone.java b/module/ri-engine/src/main/java/io/trygvis/rules/dns/DnsZone.java deleted file mode 100644 index 1af5c8f..0000000 --- a/module/ri-engine/src/main/java/io/trygvis/rules/dns/DnsZone.java +++ /dev/null @@ -1,9 +0,0 @@ -package io.trygvis.rules.dns; - -public class DnsZone { - public final String name; - - public DnsZone(String name) { - this.name = name; - } -} diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/engine/DbIo.java b/module/ri-engine/src/main/java/io/trygvis/rules/engine/DbIo.java index b8ee03a..d3d309a 100644 --- a/module/ri-engine/src/main/java/io/trygvis/rules/engine/DbIo.java +++ b/module/ri-engine/src/main/java/io/trygvis/rules/engine/DbIo.java @@ -14,6 +14,8 @@ import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; import org.drools.core.common.DefaultFactHandle; import org.drools.core.factmodel.GeneratedFact; import org.kie.api.KieBase; +import org.kie.api.definition.type.FactType; +import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.rule.FactHandle; import java.io.File; @@ -29,14 +31,14 @@ public class DbIo { private static final List<String> prioritizedKeys = List.of("key", "name", "fqdn"); - public DbIo(KieBase kieBase) { + public DbIo(KieContainer container, KieBase kieBase) { var factory = new YAMLFactory(); factory.enable(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID); factory.enable(YAMLGenerator.Feature.USE_NATIVE_OBJECT_ID); mapper = new ObjectMapper(factory); mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); var typeFactory = TypeFactory.defaultInstance() - .withClassLoader(new AcmeClassLoader(kieBase)); + .withClassLoader(new DbClassLoader(container, kieBase)); mapper.setTypeFactory(typeFactory); mapper.findAndRegisterModules(); @@ -50,7 +52,7 @@ public class DbIo { for (String name : prioritizedKeys) { try { final String getter = "get" + name.substring(0, 1).toUpperCase() + name.substring(1); - var f = klass.getMethod(getter); + klass.getMethod(getter); return new ObjectIdInfo(PropertyName.construct(name), null, ObjectIdGenerators.PropertyGenerator.class, null); } catch (NoSuchMethodException ignore) { } @@ -64,8 +66,8 @@ public class DbIo { }); } - public List<Object> load(String file) throws IOException { - var parser = mapper.getFactory().createParser(new File(file)); + public List<Object> load(File file) throws IOException { + var parser = mapper.getFactory().createParser(file); var objects = mapper.readValues(parser, DbObject.class).readAll(new ArrayList<>()); @@ -79,6 +81,8 @@ public class DbIo { } items.add(x); } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { + System.out.println("e.getClass() = " + e.getClass().getName()); + System.out.println("e.getMessage() = " + e.getMessage()); // ignore } } @@ -86,8 +90,8 @@ public class DbIo { return items; } - public void dump(String s, Collection<FactHandle> factHandles) throws IOException { - dump(s, factHandles, (o) -> true); + public void dump(File file, Collection<FactHandle> factHandles) throws IOException { + dump(file, factHandles, (o) -> true); } // This should just sort by all getters instead. @@ -221,10 +225,8 @@ public class DbIo { static record DbObject2(String type, Object data) { } - public void dump(String s, Collection<FactHandle> factHandles, Function<Object, Boolean> filter) throws IOException { - var yamlFile = new File("out", s + ".yaml"); - - FileUtil.createMissingParentDirectories(yamlFile); + public void dump(File file, Collection<FactHandle> factHandles, Function<Object, Boolean> filter) throws IOException { + FileUtil.createMissingParentDirectories(file); var facts = new TreeMap<Class<?>, FactCollection<Object>>(Comparator.comparing(Class::getName)); for (var handle : factHandles) { @@ -260,16 +262,18 @@ public class DbIo { objects.sort(new DbObjectComparator()); var factory = mapper.getFactory(); - try (var writer = new FileWriter(yamlFile); + try (var writer = new FileWriter(file); var g = factory.createGenerator(writer)) { g.writeObject(objects); } } - private static class AcmeClassLoader extends ClassLoader { + private static class DbClassLoader extends ClassLoader { private final KieBase kieBase; + private final KieContainer container; - public AcmeClassLoader(KieBase kieBase) { + public DbClassLoader(KieContainer container, KieBase kieBase) { + this.container = container; this.kieBase = kieBase; } @@ -287,7 +291,18 @@ public class DbIo { pkg = name.substring(0, i); klass = name.substring(i + 1); } - var clazz = kieBase.getFactType(pkg, klass); + + try { + return container.getClassLoader().loadClass(name); + } catch (ClassNotFoundException ignore) { + } + + FactType clazz = null; + try { + clazz = kieBase.getFactType(pkg, klass); + } catch (UnsupportedOperationException ignore) { + System.out.println("AcmeClassLoader.loadClass: " + name); + } if (clazz == null) { throw e; } diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/engine/Engine.java b/module/ri-engine/src/main/java/io/trygvis/rules/engine/Engine.java index b73e2e8..3db1625 100644 --- a/module/ri-engine/src/main/java/io/trygvis/rules/engine/Engine.java +++ b/module/ri-engine/src/main/java/io/trygvis/rules/engine/Engine.java @@ -2,41 +2,83 @@ package io.trygvis.rules.engine; import org.drools.core.audit.WorkingMemoryConsoleLogger; import org.kie.api.KieServices; +import org.kie.api.builder.Message; +import org.kie.api.builder.Message.Level; +import org.kie.api.builder.ReleaseId; import org.kie.api.event.rule.AgendaEventListener; import org.kie.api.event.rule.RuleRuntimeEventListener; import org.kie.api.runtime.KieSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.File; import java.io.IOException; public class Engine implements Closeable { + private final Logger logger = LoggerFactory.getLogger(getClass()); + public final DbIo io; public final KieSession session; - public Engine(String name, String database, File output, String[] agendaGroups) throws IOException { + public Engine(String name, File database, File output, String[] agendaGroups, File[] modules) throws IOException { + logger.info("Getting KieServices"); + var services = KieServices.Factory.get(); - var container = services.getKieClasspathContainer(); - var kieBase = container.getKieBase(name); - io = new DbIo(kieBase); - var objects = io.load(database); + ReleaseId releaseId = null; + for (File path : (modules == null ? new File[0] : modules)) { + logger.info("New KieBuilder: {}", path); + + +// var kieBuilder = services.newKieBuilder(fileSystem); + var kieBuilder = services.newKieBuilder(path); + logger.info("Building module"); + kieBuilder.buildAll(); + + logger.info("Module built!"); + + var results = kieBuilder.getResults(); + + for (Message message : results.getMessages(Level.INFO, Level.WARNING, Level.ERROR)) { +// logger.info("{} {}", message.getLevel(), message.getText()); + logger.info(message.toString()); + } + + var module = kieBuilder.getKieModule(); + releaseId = module.getReleaseId(); + logger.info("module.getReleaseId() = {}", releaseId); + logger.info("module.getClass() = {}", module.getClass()); + } + + logger.info("Creating classpath container"); +// var container = services.getKieClasspathContainer(); + var container = services.newKieContainer(releaseId); + + logger.info("Creating KieBase"); + logger.info("Available kie base names: {}", container.getKieBaseNames()); + var kieBase = container.getKieBase(name); session = container.newKieSession(name); - var logger = new WorkingMemoryConsoleLogger(session); - session.addEventListener((AgendaEventListener) logger); - session.addEventListener((RuleRuntimeEventListener) logger); + var l = new WorkingMemoryConsoleLogger(session); + session.addEventListener((AgendaEventListener) l); + session.addEventListener((RuleRuntimeEventListener) l); - session.setGlobal("te", new TemplateEngine(output)); + session.setGlobal("te", new JinjavaTemplateEngine(output)); + + logger.info("Loading data"); + io = new DbIo(container, kieBase); + var objects = io.load(database); + logger.info("Loaded {} objects", objects.size()); for (var object : objects) { - System.out.println("object = " + object); + logger.info("object = " + object); session.insert(object); } for (var agendaGroup : agendaGroups) { - System.out.println("Setting agenda: " + agendaGroup); + logger.info("Setting agenda: " + agendaGroup); session.getAgenda().getAgendaGroup(agendaGroup).setFocus(); session.fireAllRules(); } diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/engine/JinjavaTemplateEngine.java b/module/ri-engine/src/main/java/io/trygvis/rules/engine/JinjavaTemplateEngine.java new file mode 100644 index 0000000..42b2127 --- /dev/null +++ b/module/ri-engine/src/main/java/io/trygvis/rules/engine/JinjavaTemplateEngine.java @@ -0,0 +1,40 @@ +package io.trygvis.rules.engine; + +import ch.qos.logback.core.util.FileUtil; +import com.hubspot.jinjava.Jinjava; +import org.apache.commons.io.FileUtils; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; + +public class JinjavaTemplateEngine implements TemplateEngine { + private final Jinjava jinjava = new Jinjava(); + + private final File basedir; + + public JinjavaTemplateEngine(File basedir) { + this.basedir = basedir; + } + + @Override + public void clean() { + try { + System.out.println("Cleaning gen!"); + FileUtils.deleteDirectory(basedir); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public void template(String name, String output, Map<String, Object> params) throws IOException { + var template = Files.readString(Path.of("j2", name + ".j2")); + String renderedTemplate = jinjava.render(template, params); + var f = new File(basedir, output); + FileUtil.createMissingParentDirectories(f); + Files.writeString(f.toPath(), renderedTemplate); + } +} diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/engine/KeyValue.java b/module/ri-engine/src/main/java/io/trygvis/rules/engine/KeyValue.java deleted file mode 100644 index 5046169..0000000 --- a/module/ri-engine/src/main/java/io/trygvis/rules/engine/KeyValue.java +++ /dev/null @@ -1,14 +0,0 @@ -package io.trygvis.rules.engine; - -public class KeyValue { - public String key; - public String value; - - public KeyValue() { - } - - public KeyValue(String key, String value) { - this.key = key; - this.value = value; - } -} diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/engine/Main.java b/module/ri-engine/src/main/java/io/trygvis/rules/engine/Main.java new file mode 100644 index 0000000..4f06091 --- /dev/null +++ b/module/ri-engine/src/main/java/io/trygvis/rules/engine/Main.java @@ -0,0 +1,20 @@ +package io.trygvis.rules.engine; + +import io.trygvis.rules.engine.cli.DatabaseCommand; +import io.trygvis.rules.engine.cli.RunCommand; +import picocli.CommandLine; +import picocli.CommandLine.Command; + +@Command( + name = "engine", + subcommands = {RunCommand.class, DatabaseCommand.class}, + mixinStandardHelpOptions = true, + version = "UNSPECIFIED") +class Main { + + public static void main(String... args) { + //noinspection InstantiationOfUtilityClass + int exitCode = new CommandLine(new Main()).execute(args); + System.exit(exitCode); + } +} diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/engine/TemplateEngine.java b/module/ri-engine/src/main/java/io/trygvis/rules/engine/TemplateEngine.java index cc085c0..eafa6e4 100644 --- a/module/ri-engine/src/main/java/io/trygvis/rules/engine/TemplateEngine.java +++ b/module/ri-engine/src/main/java/io/trygvis/rules/engine/TemplateEngine.java @@ -1,38 +1,10 @@ package io.trygvis.rules.engine; -import ch.qos.logback.core.util.FileUtil; -import com.hubspot.jinjava.Jinjava; -import org.apache.commons.io.FileUtils; - -import java.io.File; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Map; -public class TemplateEngine { - private final Jinjava jinjava = new Jinjava(); - - private final File basedir; - - public TemplateEngine(File basedir) { - this.basedir = basedir; - } - - public void clean() { - try { - System.out.println("Cleaning gen!"); - FileUtils.deleteDirectory(basedir); - } catch (IOException e) { - throw new RuntimeException(e); - } - } +public interface TemplateEngine { + void clean(); - public void template(String name, String output, Map<String, Object> params) throws IOException { - var template = Files.readString(Path.of("j2", name + ".j2")); - String renderedTemplate = jinjava.render(template, params); - var f = new File(basedir, output); - FileUtil.createMissingParentDirectories(f); - Files.writeString(f.toPath(), renderedTemplate); - } + void template(String name, String output, Map<String, Object> params) throws IOException; } diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/engine/cli/DatabaseCommand.java b/module/ri-engine/src/main/java/io/trygvis/rules/engine/cli/DatabaseCommand.java new file mode 100644 index 0000000..03650b5 --- /dev/null +++ b/module/ri-engine/src/main/java/io/trygvis/rules/engine/cli/DatabaseCommand.java @@ -0,0 +1,20 @@ +package io.trygvis.rules.engine.cli; + +import picocli.CommandLine.Command; + +import java.util.concurrent.Callable; + +import static picocli.CommandLine.Option; + +@Command(name = "database") +public class DatabaseCommand implements Callable<Integer> { + + @Option(names = {"-v", "--verbose"}) + private boolean verbose; + + @Override + public Integer call() { + System.out.println("DatabaseCommand.call"); + return 0; + } +} diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/engine/cli/RunCommand.java b/module/ri-engine/src/main/java/io/trygvis/rules/engine/cli/RunCommand.java new file mode 100644 index 0000000..345d8b8 --- /dev/null +++ b/module/ri-engine/src/main/java/io/trygvis/rules/engine/cli/RunCommand.java @@ -0,0 +1,55 @@ +package io.trygvis.rules.engine.cli; + +import io.trygvis.rules.engine.Engine; + +import java.io.File; +import java.util.concurrent.Callable; + +import static picocli.CommandLine.Command; +import static picocli.CommandLine.Option; + +@Command(name = "run") +public class RunCommand implements Callable<Integer> { + + @Option(names = {"-n", "--name"}) + public String name; + + @Option(names = {"-i", "--input"}) + public File input; + + @Option(names = {"--output-state"}) + public File outputState; + + @Option(names = {"--generated-output"}) + public File generatedOutput; + + @Option(names = {"--agenda-groups"}) + public String[] agendaGroups; + + @Option(names = {"--modules"}, split = ",") + public File[] modules; + + @Override + public Integer call() throws Exception { + System.out.println("RunCommand.call"); + + if (agendaGroups == null || agendaGroups.length == 0) { + agendaGroups = new String[]{"init", "generate"}; + } + + try (var engine = new Engine(name, input, generatedOutput, agendaGroups, modules)) { + engine.io.dump(outputState, engine.session.getFactHandles(), (Object o) -> + o.getClass().getName().contains("Wg") || + o.getClass().getSimpleName().contains("Machine") || + o.getClass().getSimpleName().contains("DnsEntry") || + o.getClass().getSimpleName().contains("Ipv4Cidr") || + o.getClass().getSimpleName().contains("Ipv4Address") + ); + System.out.println("RunCommand.call"); + } + + System.out.println("RunCommand.call"); + + return 0; + } +} diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/machine/Machine.java b/module/ri-engine/src/main/java/io/trygvis/rules/machine/Machine.java deleted file mode 100644 index 34c17ca..0000000 --- a/module/ri-engine/src/main/java/io/trygvis/rules/machine/Machine.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.trygvis.rules.machine; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; - -@SuppressWarnings("unused") -@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "name") -public class Machine { - public String name; - private String fqdn; - - public Machine() { - } - - public Machine(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public String getFqdn() { - return fqdn; - } - - public void setFqdn(String fqdn) { - this.fqdn = fqdn; - } -} diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/machine/MachineSpecification.java b/module/ri-engine/src/main/java/io/trygvis/rules/machine/MachineSpecification.java deleted file mode 100644 index 2e17ae5..0000000 --- a/module/ri-engine/src/main/java/io/trygvis/rules/machine/MachineSpecification.java +++ /dev/null @@ -1,19 +0,0 @@ -package io.trygvis.rules.machine; - -public class MachineSpecification { - public final int cpu; - public final int memory; - - public MachineSpecification(int cpu, int memory) { - this.cpu = cpu; - this.memory = memory; - } - - public int getCpu() { - return cpu; - } - - public int getMemory() { - return memory; - } -} diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/network/IpCalc.java b/module/ri-engine/src/main/java/io/trygvis/rules/network/IpCalc.java deleted file mode 100644 index 7ec344c..0000000 --- a/module/ri-engine/src/main/java/io/trygvis/rules/network/IpCalc.java +++ /dev/null @@ -1,6 +0,0 @@ -package io.trygvis.rules.network; - -import java.util.regex.Pattern; - -public class IpCalc { -} diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/network/Ipv4Address.java b/module/ri-engine/src/main/java/io/trygvis/rules/network/Ipv4Address.java deleted file mode 100644 index 7ca9ca5..0000000 --- a/module/ri-engine/src/main/java/io/trygvis/rules/network/Ipv4Address.java +++ /dev/null @@ -1,57 +0,0 @@ -package io.trygvis.rules.network; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -import java.io.IOException; -import java.util.Objects; - -@JsonSerialize(using = Ipv4Address.Serializer.class) -public class Ipv4Address implements Comparable<Ipv4Address> { - public final int address; - - public Ipv4Address(int address) { - this.address = address; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o instanceof Ipv4Address other) { - return address == other.address; - } - - return false; - } - - @Override - public int hashCode() { - return Objects.hash(address); - } - - @Override - public int compareTo(Ipv4Address o) { - return address - o.address; - } - - @Override - public String toString() { - return "%d.%d.%d.%d".formatted( - address >> 24 & 0xff, - address >> 16 & 0xff, - address >> 8 & 0xff, - address & 0xff); - } - - public static class Serializer extends JsonSerializer<Ipv4Address> { - @Override - public void serialize(Ipv4Address value, JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeObjectField("value", value.toString()); - gen.writeEndObject(); - } - } -} diff --git a/module/ri-engine/src/main/java/io/trygvis/rules/network/Ipv4Cidr.java b/module/ri-engine/src/main/java/io/trygvis/rules/network/Ipv4Cidr.java deleted file mode 100644 index 6362107..0000000 --- a/module/ri-engine/src/main/java/io/trygvis/rules/network/Ipv4Cidr.java +++ /dev/null @@ -1,152 +0,0 @@ -package io.trygvis.rules.network; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import org.checkerframework.checker.nullness.compatqual.NonNullType; - -import javax.annotation.Nonnull; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.regex.Pattern; - -@JsonSerialize(using = Ipv4Cidr.Serializer.class) -public class Ipv4Cidr implements Comparable<Ipv4Cidr> { - public final int network; - public final int bits; - - public Ipv4Cidr(int network, int bits) { - if (bits < 0 || bits > 32) { - throw new IllegalArgumentException("bits must be [0, 32]"); - } - - int hostBits = 32 - bits; - int netmask = (-1 >> hostBits) << hostBits; - - int x = network & ~netmask; - - if (x != 0) { - throw new IllegalArgumentException("The host part of the address must be 0."); - } - - this.network = network; - this.bits = bits; - } - - @Override - public String toString() { - return "%d.%d.%d.%d/%d".formatted( - network >> 24 & 0xff, - network >> 16 & 0xff, - network >> 8 & 0xff, - network & 0xff, - bits); - } - - private String formatIpv4(int address) { - return "%d.%d.%d.%d".formatted(address >> 24 & 0xff, address >> 16 & 0xff, address >> 8 & 0xff, address & 0xff); - } - - public List<Ipv4Cidr> partition(int bits) { - if (bits <= 0 || bits <= this.bits || bits > 32) { - throw new IllegalArgumentException("Invalid new network size"); - } - - var list = new ArrayList<Ipv4Cidr>(); - - int count = 1 << (bits - this.bits); - for (int i = 0; i < count; i++) { - var network = this.network | (i << (32 - bits)); - - list.add(new Ipv4Cidr(network, bits)); - } - - return list; - } - - public List<Ipv4Address> addresses() { - int size = 1 << 32 - bits; - var end = network + size; - var addresses = new ArrayList<Ipv4Address>(size); - for (int address = network; address < end; address++) { - addresses.add(new Ipv4Address(address)); - } - - return addresses; - } - - @Override - public int compareTo(Ipv4Cidr o) { - if (this == o) { - return 0; - } - - var ret = network - o.network; - if (ret != 0) { - return ret; - } - - return bits - o.bits; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Ipv4Cidr ipv4Cidr = (Ipv4Cidr) o; - return network == ipv4Cidr.network && bits == ipv4Cidr.bits; - } - - @Override - public int hashCode() { - return Objects.hash(network, bits); - } - - private static final Pattern pattern = Pattern.compile("([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})/([0-9]{1,3})"); - - public static Ipv4Cidr parseCidr(String cidr) { - var matcher = pattern.matcher(cidr); - if (!matcher.matches()) { - throw new IllegalArgumentException("Not a CIDR: " + cidr); - } - - var b1 = matcher.group(1); - var b2 = matcher.group(2); - var b3 = matcher.group(3); - var b4 = matcher.group(4); - - int network = parse(b1) << 24 | - parse(b2) << 16 | - parse(b3) << 8 | - parse(b4); - -// System.out.printf("network = %x%n", network); - - var l = matcher.group(5); - var bits = Integer.parseInt(l); -// System.out.printf("netmask = %08x%n", netmask); - - return new Ipv4Cidr(network, bits); - } - - private static int parse(String s) { - var i = Integer.parseInt(s); - if (i > 255) { - throw new IllegalArgumentException("Not a CIDR"); - } - - return i; - } - - public static class Serializer extends JsonSerializer<Ipv4Cidr> { - @Override - public void serialize(Ipv4Cidr value, JsonGenerator gen, SerializerProvider serializers) throws IOException { - gen.writeStartObject(); - gen.writeObjectField("value", value.toString()); - gen.writeEndObject(); - } - } -} |