@Override public void createConfiguration(final Node node, final LogEvent event) { final PluginType<?> type = node.getType(); if (type != null && type.isDeferChildren()) { node.setObject(createPluginObject(type, node, event)); } else { for (final Node child : node.getChildren()) { createConfiguration(child, event); } if (type == null) { if (node.getParent() != null) { LOGGER.error("Unable to locate plugin for {}", node.getName()); } } else { node.setObject(createPluginObject(type, node, event)); } } }
/** * Constructs an Interpolator using a given StrLookup and a list of packages to find Lookup plugins in. * * @param defaultLookup the default StrLookup to use as a fallback * @param pluginPackages a list of packages to scan for Lookup plugins * @since 2.1 */ public Interpolator(final StrLookup defaultLookup, final List<String> pluginPackages) { this.defaultLookup = defaultLookup == null ? new MapLookup(new HashMap<String, String>()) : defaultLookup; final PluginManager manager = new PluginManager(CATEGORY); manager.collectPlugins(pluginPackages); final Map<String, PluginType<?>> plugins = manager.getPlugins(); for (final Map.Entry<String, PluginType<?>> entry : plugins.entrySet()) { try { final Class<? extends StrLookup> clazz = entry.getValue().getPluginClass().asSubclass(StrLookup.class); strLookupMap.put(entry.getKey(), ReflectionUtil.instantiate(clazz)); } catch (final Throwable t) { handleError(entry.getKey(), t); } } }
private static Collection<ConfigurationFactory> findFactories() { final PluginManager manager = new PluginManager(ConfigurationFactory.CATEGORY); manager.collectPlugins(); final Collection<ConfigurationFactory> factories = new ArrayList<>(); for (final PluginType<?> type : manager.getPlugins().values()) { final ConfigurationFactory factory = tryCreateFactory(type); if (factory != null) { factories.add(factory); } } return factories; }
private static ConfigurationFactory tryCreateFactory(final PluginType<?> pluginType) { try { return pluginType.getPluginClass().asSubclass(ConfigurationFactory.class).newInstance(); } catch (final Exception ignored) { return null; } }
/** * Constructor. * * @param config * The current Configuration. * @param converterKey * The key to lookup the converters. * @param expectedClass * The expected base Class of each Converter. * @param filterClass * Filter the returned plugins after calling the plugin manager. */ public PatternParser(final Configuration config, final String converterKey, final Class<?> expectedClass, final Class<?> filterClass) { this.config = config; final PluginManager manager = new PluginManager(converterKey); manager.collectPlugins(config == null ? null : config.getPluginPackages()); final Map<String, PluginType<?>> plugins = manager.getPlugins(); final Map<String, Class<PatternConverter>> converters = new LinkedHashMap<>(); for (final PluginType<?> type : plugins.values()) { try { @SuppressWarnings("unchecked") final Class<PatternConverter> clazz = (Class<PatternConverter>) type.getPluginClass(); if (filterClass != null && !filterClass.isAssignableFrom(clazz)) { continue; } final ConverterKeys keys = clazz.getAnnotation(ConverterKeys.class); if (keys != null) { for (final String key : keys.value()) { if (converters.containsKey(key)) { LOGGER.warn("Converter key '{}' is already mapped to '{}'. " + "Sorry, Dave, I can't let you do that! Ignoring plugin [{}].", key, converters.get(key), clazz); } else { converters.put(key, clazz); } } } } catch (final Exception ex) { LOGGER.error("Error processing plugin " + type.getElementName(), ex); } } converterRules = converters; }
private void constructHierarchy(final Node node, final Element element) { processAttributes(node, element); final StringBuilder buffer = new StringBuilder(); final NodeList list = element.getChildNodes(); final List<Node> children = node.getChildren(); for (int i = 0; i < list.getLength(); i++) { final org.w3c.dom.Node w3cNode = list.item(i); if (w3cNode instanceof Element) { final Element child = (Element) w3cNode; final String name = getType(child); final PluginType<?> type = pluginManager.getPluginType(name); final Node childNode = new Node(node, name, type); constructHierarchy(childNode, child); if (type == null) { final String value = childNode.getValue(); if (!childNode.hasChildren() && value != null) { node.getAttributes().put(name, value); } else { status.add(new Status(name, element, ErrorType.CLASS_NOT_FOUND)); } } else { children.add(childNode); } } else if (w3cNode instanceof Text) { final Text data = (Text) w3cNode; buffer.append(data.getData()); } } final String text = buffer.toString().trim(); if (text.length() > 0 || (!node.hasChildren() && !node.isRoot())) { node.setValue(text); } }
/** * Returns the ConfigurationFactory. * @return the ConfigurationFactory. */ public static ConfigurationFactory getInstance() { // volatile works in Java 1.6+, so double-checked locking also works properly //noinspection DoubleCheckedLocking if (factories == null) { LOCK.lock(); try { if (factories == null) { final List<ConfigurationFactory> list = new ArrayList<>(); final String factoryClass = PropertiesUtil.getProperties().getStringProperty(CONFIGURATION_FACTORY_PROPERTY); if (factoryClass != null) { addFactory(list, factoryClass); } final PluginManager manager = new PluginManager(CATEGORY); manager.collectPlugins(); final Map<String, PluginType<?>> plugins = manager.getPlugins(); final List<Class<? extends ConfigurationFactory>> ordered = new ArrayList<>(plugins.size()); for (final PluginType<?> type : plugins.values()) { try { ordered.add(type.getPluginClass().asSubclass(ConfigurationFactory.class)); } catch (final Exception ex) { LOGGER.warn("Unable to add class {}", type.getPluginClass(), ex); } } Collections.sort(ordered, OrderComparator.getInstance()); for (final Class<? extends ConfigurationFactory> clazz : ordered) { addFactory(list, clazz); } // see above comments about double-checked locking //noinspection NonThreadSafeLazyInitialization factories = Collections.unmodifiableList(list); } } finally { LOCK.unlock(); } } LOGGER.debug("Using configurationFactory {}", configFactory); return configFactory; }
protected Node convertToNode(final Node parent, final Component component) { final String name = component.getPluginType(); final PluginType<?> pluginType = pluginManager.getPluginType(name); final Node node = new Node(parent, name, pluginType); node.getAttributes().putAll(component.getAttributes()); node.setValue(component.getValue()); final List<Node> children = node.getChildren(); for (final Component child : component.getComponents()) { children.add(convertToNode(node, child)); } return node; }
private void loadKnownTypeConverters(final Collection<PluginType<?>> knownTypes) { for (final PluginType<?> knownType : knownTypes) { final Class<?> clazz = knownType.getPluginClass(); if (TypeConverter.class.isAssignableFrom(clazz)) { @SuppressWarnings("rawtypes") final Class<? extends TypeConverter> pluginClass = clazz.asSubclass(TypeConverter.class); final Type conversionType = getTypeConverterSupportedType(pluginClass); final TypeConverter<?> converter = ReflectionUtil.instantiate(pluginClass); if (registry.putIfAbsent(conversionType, converter) != null) { LOGGER.warn("Found a TypeConverter [{}] for type [{}] that already exists.", converter, conversionType); } } } }
private Node findNamedNode(final String name, final Iterable<Node> children) { for (final Node child : children) { final PluginType<?> childType = child.getType(); if (childType == null) { //System.out.println(); } if (name.equalsIgnoreCase(childType.getElementName()) || this.conversionType.isAssignableFrom(childType.getPluginClass())) { // FIXME: check child.getObject() for null? // doing so would be more consistent with the array version return child; } } return null; }
@SuppressWarnings("unchecked") @Before public void setUp() throws Exception { final PluginManager manager = new PluginManager("Test"); manager.collectPlugins(); plugin = (PluginType<ValidatingPlugin>) manager.getPluginType("Validator"); assertNotNull("Rebuild this module to make sure annotaion processing kicks in.", plugin); node = new Node(null, "Validator", plugin); }
@SuppressWarnings("unchecked") @Before public void setUp() throws Exception { final PluginManager manager = new PluginManager("Test"); manager.collectPlugins(); plugin = (PluginType<ValidatingPluginWithGenericBuilder>) manager.getPluginType("ValidatingPluginWithGenericBuilder"); assertNotNull("Rebuild this module to make sure annotaion processing kicks in.", plugin); node = new Node(null, "Validator", plugin); }
@SuppressWarnings("unchecked") @Before public void setUp() throws Exception { final PluginManager manager = new PluginManager("Test"); manager.collectPlugins(); plugin = (PluginType<ValidatingPluginWithTypedBuilder>) manager .getPluginType("ValidatingPluginWithTypedBuilder"); assertNotNull("Rebuild this module to make sure annotaion processing kicks in.", plugin); node = new Node(null, "Validator", plugin); }
@SuppressWarnings("unchecked") @Before public void setUp() throws Exception { final PluginManager manager = new PluginManager("Test"); manager.collectPlugins(); plugin = (PluginType<HostAndPort>) manager.getPluginType("HostAndPort"); assertNotNull("Rebuild this module to ensure annotation processing has been done.", plugin); node = new Node(null, "HostAndPort", plugin); }
@SuppressWarnings("unchecked") @Before public void setUp() throws Exception { final PluginManager manager = new PluginManager("Test"); manager.collectPlugins(); plugin = (PluginType<PluginWithGenericSubclassFoo1Builder>) manager.getPluginType("PluginWithGenericSubclassFoo1Builder"); assertNotNull("Rebuild this module to make sure annotaion processing kicks in.", plugin); node = new Node(null, "Validator", plugin); }
@SuppressWarnings("unchecked") @Before public void setUp() throws Exception { final PluginManager manager = new PluginManager("Test"); manager.collectPlugins(); plugin = (PluginType<HostAndPort>) manager.getPluginType("HostAndPort"); assertNotNull("Rebuild this module to ensure annotation processing has been done.", plugin); node = new Node(null, "HostAndPort", plugin); node.getAttributes().put("host", "localhost"); }
private Node constructNode(final String name, final Node parent, final JsonNode jsonNode) { final PluginType<?> type = pluginManager.getPluginType(name); final Node node = new Node(parent, name, type); processAttributes(node, jsonNode); final Iterator<Map.Entry<String, JsonNode>> iter = jsonNode.fields(); final List<Node> children = node.getChildren(); while (iter.hasNext()) { final Map.Entry<String, JsonNode> entry = iter.next(); final JsonNode n = entry.getValue(); if (n.isArray() || n.isObject()) { if (type == null) { status.add(new Status(name, n, ErrorType.CLASS_NOT_FOUND)); } if (n.isArray()) { LOGGER.debug("Processing node for array {}", entry.getKey()); for (int i = 0; i < n.size(); ++i) { final String pluginType = getType(n.get(i), entry.getKey()); final PluginType<?> entryType = pluginManager.getPluginType(pluginType); final Node item = new Node(node, entry.getKey(), entryType); processAttributes(item, n.get(i)); if (pluginType.equals(entry.getKey())) { LOGGER.debug("Processing {}[{}]", entry.getKey(), i); } else { LOGGER.debug("Processing {} {}[{}]", pluginType, entry.getKey(), i); } final Iterator<Map.Entry<String, JsonNode>> itemIter = n.get(i).fields(); final List<Node> itemChildren = item.getChildren(); while (itemIter.hasNext()) { final Map.Entry<String, JsonNode> itemEntry = itemIter.next(); if (itemEntry.getValue().isObject()) { LOGGER.debug("Processing node for object {}", itemEntry.getKey()); itemChildren.add(constructNode(itemEntry.getKey(), item, itemEntry.getValue())); } else if (itemEntry.getValue().isArray()) { final JsonNode array = itemEntry.getValue(); final String entryName = itemEntry.getKey(); LOGGER.debug("Processing array for object {}", entryName); for (int j = 0; j < array.size(); ++j) { itemChildren.add(constructNode(entryName, item, array.get(j))); } } } children.add(item); } } else { LOGGER.debug("Processing node for object {}", entry.getKey()); children.add(constructNode(entry.getKey(), node, n)); } } else { LOGGER.debug("Node {} is of type {}", entry.getKey(), n.getNodeType()); } } String t; if (type == null) { t = "null"; } else { t = type.getElementName() + ':' + type.getPluginClass(); } final String p = node.getParent() == null ? "null" : node.getParent().getName() == null ? LoggerConfig.ROOT : node.getParent().getName(); LOGGER.debug("Returning {} with parent {} of type {}", node.getName(), p, t); return node; }
public PluginType<?> getType() { return type; }
@Override public Object visit(final Configuration configuration, final Node node, final LogEvent event, final StringBuilder log) { final String name = this.annotation.value(); if (this.conversionType.isArray()) { setConversionType(this.conversionType.getComponentType()); final List<Object> values = new ArrayList<>(); final Collection<Node> used = new ArrayList<>(); log.append("={"); boolean first = true; for (final Node child : node.getChildren()) { final PluginType<?> childType = child.getType(); if (name.equalsIgnoreCase(childType.getElementName()) || this.conversionType.isAssignableFrom(childType.getPluginClass())) { if (!first) { log.append(", "); } first = false; used.add(child); final Object childObject = child.getObject(); if (childObject == null) { LOGGER.error("Null object returned for {} in {}.", child.getName(), node.getName()); continue; } if (childObject.getClass().isArray()) { log.append(Arrays.toString((Object[]) childObject)).append('}'); return childObject; } log.append(child.toString()); values.add(childObject); } } log.append('}'); // note that we need to return an empty array instead of null if the types are correct if (!values.isEmpty() && !this.conversionType.isAssignableFrom(values.get(0).getClass())) { LOGGER.error("Attempted to assign attribute {} to list of type {} which is incompatible with {}.", name, values.get(0).getClass(), this.conversionType); return null; } node.getChildren().removeAll(used); // we need to use reflection here because values.toArray() will cause type errors at runtime final Object[] array = (Object[]) Array.newInstance(this.conversionType, values.size()); for (int i = 0; i < array.length; i++) { array[i] = values.get(i); } return array; } final Node namedNode = findNamedNode(name, node.getChildren()); if (namedNode == null) { log.append(name).append("=null"); return null; } log.append(namedNode.getName()).append('(').append(namedNode.toString()).append(')'); node.getChildren().remove(namedNode); return namedNode.getObject(); }
@Test public void testPlugin(){ PluginManager pm = new PluginManager(PatternConverter.CATEGORY); pm.collectPlugins(); for(Entry<String, PluginType<?>> entry : pm.getPlugins().entrySet()){ logger.info("{} : {}", entry.getKey(), entry.getValue()); } logger.error("[testPlugin]", new IOException("io exception message...")); }
/** * Creates a new instance of {@code Node} and initializes it * with a name and the corresponding XML element. * * @param parent the node's parent. * @param name the node's name. * @param type The Plugin Type associated with the node. */ public Node(final Node parent, final String name, final PluginType<?> type) { this.parent = parent; this.name = name; this.type = type; }