001/*
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2024, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014
015package ch.qos.logback.core.model.processor;
016
017import ch.qos.logback.core.Context;
018import ch.qos.logback.core.CoreConstants;
019import ch.qos.logback.core.model.ConversionRuleModel;
020import ch.qos.logback.core.model.Model;
021import ch.qos.logback.core.util.OptionHelper;
022
023import java.util.HashMap;
024import java.util.Map;
025
026import static ch.qos.logback.core.joran.JoranConstants.CONVERSION_WORD_ATTRIBUTE;
027
028public class ConversionRuleModelHandler extends ModelHandlerBase {
029
030    private boolean inError;
031
032    public ConversionRuleModelHandler(Context context) {
033        super(context);
034    }
035
036    static public ConversionRuleModelHandler makeInstance(Context context, ModelInterpretationContext mic) {
037        return new ConversionRuleModelHandler(context);
038    }
039
040    @Override
041    public void handle(ModelInterpretationContext mic, Model model) throws ModelHandlerException {
042
043        ConversionRuleModel conversionRuleModel = (ConversionRuleModel) model;
044        String converterClass = conversionRuleModel.getClassName();
045
046        if (OptionHelper.isNullOrEmptyOrAllSpaces(converterClass)) {
047            addWarn("Missing className. This should have been caught earlier.");
048            inError = true;
049            return;
050        } else {
051            converterClass = mic.getImport(converterClass);
052        }
053
054        String conversionWord = conversionRuleModel.getConversionWord();
055
056
057        try {
058            Map<String, String> ruleRegistry = (Map<String, String>) context
059                    .getObject(CoreConstants.PATTERN_RULE_REGISTRY);
060            if (ruleRegistry == null) {
061                ruleRegistry = new HashMap<String, String>();
062                context.putObject(CoreConstants.PATTERN_RULE_REGISTRY, ruleRegistry);
063            }
064            // put the new rule into the rule registry
065            addInfo("registering conversion word " + conversionWord + " with class [" + converterClass + "]");
066            ruleRegistry.put(conversionWord, converterClass);
067        } catch (Exception oops) {
068            inError = true;
069            String errorMsg = "Could not add conversion rule to PatternLayout.";
070            addError(errorMsg);
071        }
072
073
074
075    }
076}