summaryrefslogtreecommitdiff
path: root/src/main/cpp/optionconverter.cpp
blob: 030e2e7eb4ab825c85d63ef49e8ebeea80614687 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <log4cxx/logstring.h>
#include <log4cxx/spi/loggerfactory.h>
#include <log4cxx/spi/loggerrepository.h>
#include <log4cxx/appenderskeleton.h>
#include <log4cxx/helpers/optionconverter.h>
#include <algorithm>
#include <ctype.h>
#include <log4cxx/helpers/stringhelper.h>
#include <log4cxx/helpers/exception.h>
#include <stdlib.h>
#include <log4cxx/helpers/properties.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/level.h>
#include <log4cxx/helpers/object.h>
#include <log4cxx/helpers/class.h>
#include <log4cxx/helpers/loader.h>
#include <log4cxx/helpers/system.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/helpers/transcoder.h>
#include <log4cxx/file.h>
#include <log4cxx/xml/domconfigurator.h>

using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;


LogString OptionConverter::convertSpecialChars(const LogString& s)
{
    logchar c;
    LogString sbuf;

    LogString::const_iterator i = s.begin();
    while(i != s.end())
        {
                c = *i++;
                if (c == 0x5C /* '\\' */)
                {
                        c =  *i++;

                        switch (c)
                        {
                        case 0x6E: //'n'
                                c = 0x0A;
                                break;

                        case 0x72: //'r'
                                c = 0x0D;
                                break;

                        case 0x74: //'t'
                                c = 0x09;
                                break;

                        case 0x66: //'f'
                                c = 0x0C;
                                break;
                        default:
                                break;
                        }
                }
                sbuf.append(1, c);
    }
    return sbuf;
}


bool OptionConverter::toBoolean(const LogString& value, bool dEfault)
{
        if (value.length() >= 4) {
          if (StringHelper::equalsIgnoreCase(value.substr(0,4),
             LOG4CXX_STR("TRUE"), LOG4CXX_STR("true"))) {
               return true;
          }
        }

        if (dEfault && value.length() >= 5) {
          if (StringHelper::equalsIgnoreCase(value.substr(0,5),
             LOG4CXX_STR("FALSE"), LOG4CXX_STR("false"))) {
               return false;
          }
        }

        return dEfault;
}

int OptionConverter::toInt(const LogString& value, int dEfault)
{
        LogString trimmed(StringHelper::trim(value));
        if (trimmed.empty())
        {
                return dEfault;
        }
        LOG4CXX_ENCODE_CHAR(cvalue, trimmed);

        return (int) atol(cvalue.c_str());
}

long OptionConverter::toFileSize(const LogString& s, long dEfault)
{
        if(s.empty())
        {
                return dEfault;
        }

        size_t index = s.find_first_of(LOG4CXX_STR("bB"));
        if (index != LogString::npos && index > 0) {
          long multiplier = 1;
          index--;
          if (s[index] == 0x6B /* 'k' */ || s[index] == 0x4B /* 'K' */) {
                multiplier = 1024;
          } else if(s[index] == 0x6D /* 'm' */ || s[index] == 0x4D /* 'M' */) {
                multiplier = 1024*1024;
          } else if(s[index] == 0x67 /* 'g'*/ || s[index] == 0x47 /* 'G' */) {
                multiplier = 1024*1024*1024;
          }
          return toInt(s.substr(0, index), 1) * multiplier;
        }

        return toInt(s, 1);
}

LogString OptionConverter::findAndSubst(const LogString& key, Properties& props)
{
        LogString value(props.getProperty(key));

        if(value.empty())
                return value;

        try
        {
                return substVars(value, props);
        }
        catch(IllegalArgumentException& e)
        {
                LogLog::error(((LogString) LOG4CXX_STR("Bad option value ["))
                     + value + LOG4CXX_STR("]."), e);
                return value;
        }
}

LogString OptionConverter::substVars(const LogString& val, Properties& props)
{
        LogString sbuf;
        const logchar delimStartArray[] = { 0x24, 0x7B, 0 };
        const LogString delimStart(delimStartArray);
        const logchar delimStop = 0x7D; // '}';
        const size_t DELIM_START_LEN = 2;
        const size_t DELIM_STOP_LEN = 1;

        int i = 0;
        int j, k;

        while(true)
        {
                j = val.find(delimStart, i);
                if(j == -1)
                {
                        // no more variables
                        if(i==0)
                        { // this is a simple string
                                return val;
                        }
                        else
                        { // add the tail string which contails no variables and return the result.
                                sbuf.append(val.substr(i, val.length() - i));
                                return sbuf;
                        }
                }
                else
                {
                        sbuf.append(val.substr(i, j - i));
                        k = val.find(delimStop, j);
                        if(k == -1)
                        {
                            LogString msg(1, (logchar) 0x22 /* '\"' */);
                            msg.append(val);
                            msg.append(LOG4CXX_STR("\" has no closing brace. Opening brace at position "));
                            Pool p;
                            StringHelper::toString(j, p, msg);
                            msg.append(1, (logchar) 0x2E /* '.' */);
                            throw IllegalArgumentException(msg);
                        }
                        else
                        {
                                j += DELIM_START_LEN;
                                LogString key = val.substr(j, k - j);
                                // first try in System properties
                                LogString replacement(getSystemProperty(key, LogString()));
                                // then try props parameter
                                if(replacement.empty())
                                {
                                        replacement = props.getProperty(key);
                                }

                                if(!replacement.empty())
                                {
                                        // Do variable substitution on the replacement string
                                        // such that we can solve "Hello ${x2}" as "Hello p1"
                                        // the where the properties are
                                        // x1=p1
                                        // x2=${x1}
                                        LogString recursiveReplacement = substVars(replacement, props);
                                        sbuf.append(recursiveReplacement);
                                }
                                i = k + DELIM_STOP_LEN;
                        }
                }
        }
}

LogString OptionConverter::getSystemProperty(const LogString& key, const LogString& def)
{
        if (!key.empty())
        {
                LogString value(System::getProperty(key));

                if (!value.empty())
                {
                        return value;
                }
        }
        return def;
}

LevelPtr OptionConverter::toLevel(const LogString& value,
        const LevelPtr& defaultValue)
{
    size_t hashIndex = value.find(LOG4CXX_STR("#"));

        if (hashIndex == LogString::npos)
        {
                if (value.empty())
                {
                        return defaultValue;
                }
                else
                {
                        LogLog::debug(
                ((LogString) LOG4CXX_STR("OptionConverter::toLevel: no class name specified, level=["))
                         + value
                         +LOG4CXX_STR("]"));
                        // no class name specified : use standard Level class
                        return Level::toLevelLS(value, defaultValue);
                }
        }

        LogString clazz = value.substr(hashIndex + 1);
        LogString levelName = value.substr(0, hashIndex);
        LogLog::debug(((LogString) LOG4CXX_STR("OptionConverter::toLevel: class=["))
           + clazz + LOG4CXX_STR("], level=[") + levelName + LOG4CXX_STR("]"));

        // This is degenerate case but you never know.
        if (levelName.empty())
        {
                return Level::toLevelLS(value, defaultValue);
        }

        try
        {
                Level::LevelClass& levelClass =
                        (Level::LevelClass&)Loader::loadClass(clazz);
                return levelClass.toLevel(levelName);
        }
        catch (ClassNotFoundException&)
        {
                LogLog::warn(((LogString) LOG4CXX_STR("custom level class ["))
                   + clazz + LOG4CXX_STR("] not found."));
        }
        catch(Exception& oops)
        {
                LogLog::warn(
                        LOG4CXX_STR("class [") + clazz + LOG4CXX_STR("], level [") + levelName +
                        LOG4CXX_STR("] conversion) failed."), oops);
        }
        catch(...)
        {
                LogLog::warn(
                        LOG4CXX_STR("class [") + clazz + LOG4CXX_STR("], level [") + levelName +
                        LOG4CXX_STR("] conversion) failed."));
        }

        return defaultValue;
}


ObjectPtr OptionConverter::instantiateByKey(Properties& props, const LogString& key,
        const Class& superClass, const ObjectPtr& defaultValue)
{
        // Get the value of the property in string form
        LogString className(findAndSubst(key, props));
        if(className.empty())
        {
                LogLog::error(
                   ((LogString) LOG4CXX_STR("Could not find value for key ")) + key);
                return defaultValue;
        }

        // Trim className to avoid trailing spaces that cause problems.
        return OptionConverter::instantiateByClassName(
                StringHelper::trim(className), superClass, defaultValue);
}

ObjectPtr OptionConverter::instantiateByClassName(const LogString& className,
        const Class& superClass, const ObjectPtr& defaultValue)
{
        if(!className.empty())
        {
                try
                {
                        const Class& classObj = Loader::loadClass(className);
                        ObjectPtr newObject =  classObj.newInstance();
                        if (!newObject->instanceof(superClass))
                        {
                                return defaultValue;
                        }

                        return newObject;
                }
                catch (Exception& e)
                {
                        LogLog::error(LOG4CXX_STR("Could not instantiate class [") +
                                className + LOG4CXX_STR("]."), e);
                }
        }
        return defaultValue;
}

void OptionConverter::selectAndConfigure(const File& configFileName,
         const LogString& _clazz, spi::LoggerRepositoryPtr& hierarchy)
{
        ConfiguratorPtr configurator;
        LogString clazz = _clazz;

        LogString filename(configFileName.getPath());
        if(clazz.empty() 
                && filename.length() > 4
                && StringHelper::equalsIgnoreCase(
                   filename.substr(filename.length() -4), 
                   LOG4CXX_STR(".XML"), LOG4CXX_STR(".xml")))
        {
            clazz = log4cxx::xml::DOMConfigurator::getStaticClass().toString();
        }

        if(!clazz.empty())
        {
                LogLog::debug(LOG4CXX_STR("Preferred configurator class: ") + clazz);
                configurator = instantiateByClassName(clazz,
                        Configurator::getStaticClass(),
                        0);
                if(configurator == 0)
                {
                        LogLog::error(LOG4CXX_STR("Could not instantiate configurator [")
                                 + clazz + LOG4CXX_STR("]."));
                        return;
                }
        }
        else
        {
                configurator = new PropertyConfigurator();
        }

        configurator->doConfigure(configFileName, hierarchy);
}