From 22ed31f878ce414554319895938a9552db90d32d Mon Sep 17 00:00:00 2001 From: Nicolai Ommer Date: Wed, 28 Oct 2015 16:20:40 +0100 Subject: [PATCH] reverted deletion of base package --- .../ConfigAnnotationProcessor.java | 41 +++++++++++++++++-- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/configurable/ConfigAnnotationProcessor.java b/src/main/java/com/github/configurable/ConfigAnnotationProcessor.java index 6397ac8..1e10af6 100644 --- a/src/main/java/com/github/configurable/ConfigAnnotationProcessor.java +++ b/src/main/java/com/github/configurable/ConfigAnnotationProcessor.java @@ -96,6 +96,7 @@ public HierarchicalConfiguration getDefaultConfig(final Set> classes, f classesAndSubClasses.addAll(getAllSubClasses(clazz)); } + String basePackage = classesAndSubClasses.iterator().next().getPackage().getName(); Map, List> classesAndSubClassesMap = new LinkedHashMap, List>(); for (Class clazz : classesAndSubClasses) { @@ -103,15 +104,24 @@ public HierarchicalConfiguration getDefaultConfig(final Set> classes, f if (!dataRead.isEmpty()) { classesAndSubClassesMap.put(clazz, dataRead); + + String packageName = clazz.getPackage().getName(); + basePackage = greatestCommonPrefix(basePackage, packageName); } } config.getRoot().setName(name); + config.getRoot().addAttribute(new HierarchicalConfiguration.Node("base", basePackage)); for (Map.Entry, List> entry : classesAndSubClassesMap.entrySet()) { Class clazz = entry.getKey(); String clazzName = clazz.getName(); - String clazzKey = clazzName; + if (!clazzName.startsWith(basePackage)) + { + log.error("Invalid class: " + clazzName + ". Must start with: " + basePackage); + continue; + } + String clazzKey = clazzName.substring(basePackage.length() + 1); List dataRead = entry.getValue(); for (ConfigurableFieldData fieldData : dataRead) @@ -131,6 +141,28 @@ public HierarchicalConfiguration getDefaultConfig(final Set> classes, f } + private String greatestCommonPrefix(final String a, final String b) + { + String[] pkgsA = a.split("\\."); + String[] pkgsB = b.split("\\."); + int minLength = Math.min(pkgsA.length, pkgsB.length); + StringBuilder prefix = new StringBuilder(); + for (int i = 0; i < minLength; i++) + { + if (!pkgsA[i].equals(pkgsB[i])) + { + return prefix.toString(); + } + if (i != 0) + { + prefix.append('.'); + } + prefix.append(pkgsA[i]); + } + return prefix.toString(); + } + + private Map getClassNodesFromConfigRec(final String basePackage, final List nodes) { @@ -163,11 +195,12 @@ public void loadConfiguration(final HierarchicalConfiguration config) data.clear(); List attrs = config.getRoot().getAttributes("base"); - String base = ""; - if (attrs.size() == 1) + if (attrs.size() != 1) { - base = attrs.get(0).getValue().toString(); + log.error("No unique base package path found: " + attrs); + return; } + String base = attrs.get(0).getValue().toString(); List classNodes = config.getRoot().getChildren();