bool StringHelper::endsWith(const LogString& s, const LogString& suffix)
{
    if (suffix.length() <= s.length()) {
      return s.compare(s.length() - suffix.length(), suffix.length(), suffix) == 0;
    }
    return false;
}
void BufferedWriter::write(const LogString& str, Pool& p) {
  if (buf.length() + str.length() > sz) {
    out->write(buf, p);
    buf.erase(buf.begin(), buf.end());
  }
  if (str.length() > sz) {
    out->write(str, p);
  } else {
    buf.append(str);
  }
}
/**
 * {@inheritDoc}
 */
RolloverDescriptionPtr TimeBasedRollingPolicy::initialize(
  const LogString& currentActiveFile,
  const bool append,
  Pool& pool) {
  apr_time_t n = apr_time_now();
  nextCheck = ((n / APR_USEC_PER_SEC) + 1) * APR_USEC_PER_SEC;

  File currentFile(currentActiveFile);

  LogString buf;
  ObjectPtr obj(new Date(currentFile.exists(pool) ? currentFile.lastModified(pool) : n));
  formatFileName(obj, buf, pool);
  lastFileName = buf;

  ActionPtr noAction;

  if (currentActiveFile.length() > 0) {
    return new RolloverDescription(
      currentActiveFile, append, noAction, noAction);
  } else {
      bRefreshCurFile = true;
    return new RolloverDescription(
      lastFileName.substr(0, lastFileName.length() - suffixLength), append,
      noAction, noAction);
  }
}
void PropertySetter::setProperties(helpers::Properties& properties,
        const LogString& prefix,
        Pool& p)
{
        int len = prefix.length();

        std::vector<LogString> names = properties.propertyNames();
        std::vector<LogString>::iterator it;

        for (it = names.begin(); it != names.end(); it++)
        {
                LogString key = *it;

                // handle only properties that start with the desired frefix.
                if (key.find(prefix) == 0)
                {
                        // ignore key if it contains dots after the prefix
                        if (key.find(0x2E /* '.' */, len + 1) != LogString::npos)
                        {
                                continue;
                        }

                        LogString value = OptionConverter::findAndSubst(key, properties);
                        key = key.substr(len);
                        if (key == LOG4CXX_STR("layout")
                                && obj != 0
                                && obj->instanceof(Appender::getStaticClass()))
                        {
                                continue;
                        }
                        setProperty(key, value, p);
                }
        }
        activate(p);
}
void ClassNamePatternConverter::format(
   const LoggingEventPtr& event,
   LogString& toAppendTo,
   Pool& /* p */) const {
    int initialLength = toAppendTo.length();
    append(toAppendTo, event->getLocationInformation().getClassName());
    abbreviate(initialLength, toAppendTo);
  }
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;
}
    /**
     * Abbreviate name.
     * @param buf buffer that abbreviated name is appended.
     * @param nameStart start of name.
     */
    void abbreviate(LogString::size_type nameStart, LogString& buf) const {
      //
      //  all non-terminal patterns are executed once
      //
      LogString::size_type pos = nameStart;

      for (LogString::size_type i = 0; (i < (fragments.size() - 1)) && (pos < buf.length());
          i++) {
        pos = fragments[i].abbreviate(buf, pos);
      }

      //
      //   last pattern in executed repeatedly
      //
      PatternAbbreviatorFragment terminalFragment =
        fragments[fragments.size() - 1];

      while (pos < buf.length()) {
        pos = terminalFragment.abbreviate(buf, pos);
      }
    }
Exemple #8
0
/**
 * Finds start of millisecond field in formatted time.
 * @param time long time, must be integral number of seconds
 * @param formatted String corresponding formatted string
 * @param formatter DateFormat date format
 * @return int position in string of first digit of milliseconds,
 *    -1 indicates no millisecond field, -2 indicates unrecognized
 *    field (likely RelativeTimeDateFormat)
 */
int CachedDateFormat::findMillisecondStart(
  log4cxx_time_t time, const LogString& formatted,
  const DateFormatPtr& formatter,
  Pool& pool) {

  apr_time_t slotBegin = (time / 1000000) * 1000000;
  if (slotBegin > time) {
     slotBegin -= 1000000;
  }
  int millis = (int) (time - slotBegin)/1000;

  int magic = magic1;
  LogString magicString(magicString1);
  if (millis == magic1) {
      magic = magic2;
      magicString = magicString2;
  }

  LogString plusMagic;
  formatter->format(plusMagic, slotBegin + magic, pool);

  /**
   *   If the string lengths differ then
   *      we can't use the cache except for duplicate requests.
   */
  if (plusMagic.length() != formatted.length()) {
      return UNRECOGNIZED_MILLISECONDS;
  } else {
      // find first difference between values
     for (LogString::size_type i = 0; i < formatted.length(); i++) {
        if (formatted[i] != plusMagic[i]) {
           //
           //   determine the expected digits for the base time
           const logchar abc[] = { 0x41, 0x42, 0x43, 0 };
           LogString formattedMillis(abc);
           millisecondFormat(millis, formattedMillis, 0);

           LogString plusZero;
           formatter->format(plusZero, slotBegin, pool);

           //   If the next 3 characters match the magic
           //      strings and the remaining fragments are identical
           //
           //
           if (plusZero.length() == formatted.length()
              && regionMatches(magicString, 0, plusMagic, i, magicString.length())
              && regionMatches(formattedMillis, 0, formatted, i, magicString.length())
              && regionMatches(zeroString, 0, plusZero, i, 3)
              && (formatted.length() == i + 3
                 || plusZero.compare(i + 3,
                       LogString::npos, plusMagic, i+3, LogString::npos) == 0)) {
              return i;
           } else {
              return UNRECOGNIZED_MILLISECONDS;
          }
        }
     }
  }
  return  NO_MILLISECONDS;
}
 void decode7() {
     //
     //   normal characters striding over a buffer boundary
     //
     std::string longMsg(BUFSIZE - 2, 'A');
     longMsg.append("Hello");
     LogString decoded;
     Transcoder::decode(longMsg, decoded);
     LOGUNIT_ASSERT_EQUAL((size_t) BUFSIZE + 3, decoded.length());
     LOGUNIT_ASSERT_EQUAL(LogString(BUFSIZE -2, LOG4CXX_STR('A')),
           decoded.substr(0, BUFSIZE - 2));
     LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXX_STR("Hello"),
           decoded.substr(BUFSIZE -2 ));
 }
void PatternLayout::format(LogString& output,
      const spi::LoggingEventPtr& event,
      Pool& pool) const
{
  std::vector<FormattingInfoPtr>::const_iterator formatterIter =
     patternFields.begin();
  for(std::vector<LoggingEventPatternConverterPtr>::const_iterator
           converterIter = patternConverters.begin();
      converterIter != patternConverters.end();
      converterIter++, formatterIter++) {
      int startField = output.length();
      (*converterIter)->format(event, output, pool);
      (*formatterIter)->format(startField, output);
  }

}
 void assertFormattedEquals(const LogString& pattern,
      const PatternMap& patternMap,
      const LogString& expected) {
    std::vector<PatternConverterPtr> converters;
    std::vector<FormattingInfoPtr> fields;
    PatternParser::parse(pattern, converters, fields, patternMap);
    Pool p;
    LogString actual;
    std::vector<FormattingInfoPtr>::const_iterator fieldIter = fields.begin();
    for(std::vector<PatternConverterPtr>::const_iterator converterIter = converters.begin();
        converterIter != converters.end();
        converterIter++, fieldIter++) {
        int fieldStart = actual.length();
        (*converterIter)->format(event, actual, p);
        (*fieldIter)->format(fieldStart, actual);
    }
    LOGUNIT_ASSERT_EQUAL(expected, actual);
 }
void OutputStreamWriter::write(const LogString& str, Pool& p) {
  if (str.length() > 0) {
    enum { BUFSIZE = 1024 };
    char rawbuf[BUFSIZE];
    ByteBuffer buf(rawbuf, (size_t) BUFSIZE);
    enc->reset();
    LogString::const_iterator iter = str.begin();
    while(iter != str.end()) {
      CharsetEncoder::encode(enc, str, iter, buf);
      buf.flip();
      out->write(buf, p);
      buf.clear();
    }
    CharsetEncoder::encode(enc, str, iter, buf);
    enc->flush(buf);
    buf.flip();
    out->write(buf, p);
  }
}
 LogString format(const LogString& pattern,
     const ObjectPtr& obj) {
     std::vector<PatternConverterPtr> converters;
     std::vector<FormattingInfoPtr> fields;
     PatternMap rules;
     rules.insert(PatternMap::value_type(LOG4CXX_STR("d"), (PatternConstructor) FileDatePatternConverter::newInstance));
     rules.insert(PatternMap::value_type(LOG4CXX_STR("i"), (PatternConstructor) IntegerPatternConverter::newInstance));
     PatternParser::parse(pattern, converters, fields, rules);
     LogString result;
     Pool pool;
     std::vector<FormattingInfoPtr>::const_iterator fieldIter = fields.begin();
     for(std::vector<PatternConverterPtr>::const_iterator converterIter = converters.begin();
         converterIter != converters.end();
         converterIter++, fieldIter++) {
         LogString::size_type i = result.length();
         (*converterIter)->format(obj, result, pool);
         (*fieldIter)->format(i, result);
     }
     return result;
 }
/**
 * {@inheritDoc}
 */
RolloverDescriptionPtr FixedWindowRollingPolicy::initialize(
  const LogString& file, bool append, log4cxx::helpers::Pool& p) {
  LogString newActiveFile(file);
  explicitActiveFile = false;

  if (file.length() > 0) {
    explicitActiveFile = true;
    newActiveFile = file;
  }

  if (!explicitActiveFile) {
    LogString buf;
    ObjectPtr obj(new Integer(minIndex));
    formatFileName(obj, buf, p);
    newActiveFile = buf;
  }

  ActionPtr noAction;

  return new RolloverDescription(newActiveFile, append, noAction, noAction);
}
Exemple #15
0
LevelPtr Level::toLevelLS(const LogString& sArg, const LevelPtr& defaultLevel)
{
    const size_t len = sArg.length();

    if (len == 4) {
      if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("INFO"), LOG4CXX_STR("info"))) {
        return getInfo();
      }
      if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("WARN"), LOG4CXX_STR("warn"))) {
        return getWarn();
      }
    } else {
      if (len == 5) {
        if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("DEBUG"), LOG4CXX_STR("debug"))) {
          return getDebug();
        }
        if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("TRACE"), LOG4CXX_STR("trace"))) {
          return getTrace();
        }
        if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("ERROR"), LOG4CXX_STR("error"))) {
          return getError();
        }
        if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("FATAL"), LOG4CXX_STR("fatal"))) {
          return getFatal();
        }
      } else {
        if (len == 3) {
          if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("OFF"), LOG4CXX_STR("off"))) {
            return getOff();
          }
          if (StringHelper::equalsIgnoreCase(sArg, LOG4CXX_STR("ALL"), LOG4CXX_STR("all"))) {
            return getAll();
          }
        }
      }
    }

    return defaultLevel;
}
Exemple #16
0
/**
 * Gets maximum cache validity for the specified SimpleDateTime
 *    conversion pattern.
 *  @param pattern conversion pattern, may not be null.
 *  @returns Duration in microseconds from an integral second
 *      that the cache will return consistent results.
 */
int CachedDateFormat::getMaximumCacheValidity(const LogString& pattern) {
   //
   //   If there are more "S" in the pattern than just one "SSS" then
   //      (for example, "HH:mm:ss,SSS SSS"), then set the expiration to
   //      one millisecond which should only perform duplicate request caching.
   //
   const logchar S = 0x53;
   const logchar SSS[] = { 0x53, 0x53, 0x53, 0 };
   size_t firstS = pattern.find(S);
   size_t len = pattern.length();
   //
   //   if there are no S's or
   //      three that start with the first S and no fourth S in the string
   //
   if (firstS == LogString::npos ||
       (len >= firstS + 3 && pattern.compare(firstS, 3, SSS) == 0
           && (len == firstS + 3 ||
                pattern.find(S, firstS + 3) == LogString::npos))) {
           return 1000000;
   }
   return 1000;
}
const TimeZonePtr TimeZone::getTimeZone( const LogString & id )
{
  const logchar gmt[] = { 0x47, 0x4D, 0x54, 0 };
  if ( id == gmt )
  {
    return log4cxx::helpers::TimeZoneImpl::GMTTimeZone::getInstance();
  }
  if ( id.length() >= 5 && id.substr( 0, 3 ) == gmt )
  {
    int hours = 0;
    int minutes = 0;
    int sign = 1;
    if (id[3] == 0x2D /* '-' */) {
      sign = -1;
    }
    LogString off( id.substr( 4 ) );
    if ( id.length() >= 7 )
    {
      size_t colonPos = off.find( 0x3A /* ':' */);
      if ( colonPos == LogString::npos )
      {
        minutes = StringHelper::toInt(off.substr(off.length() - 2));
        hours = StringHelper::toInt(off.substr(0, off.length() - 2));
      }
      else
      {
        minutes = StringHelper::toInt(off.substr(colonPos + 1));
        hours = StringHelper::toInt(off.substr(0, colonPos));
      }
    } else {
      hours = StringHelper::toInt(off);
    }
    LogString s(gmt);
    Pool p;
    LogString hh;
    StringHelper::toString(hours, p, hh);
    if (sign > 0) {
      s.append(1, (logchar) 0x2B /* '+' */);
    } else {
      s.append(1, (logchar) 0x2D /* '-' */);
    }
    if (hh.length() == 1) {
      s.append(1, (logchar) 0x30 /* '0' */);
    }
    s.append(hh);
    s.append(1, (logchar) 0x3A /*' :' */);
    LogString mm;
    StringHelper::toString(minutes, p, mm);
    if (mm.length() == 1) {
      s.append(1, (logchar) 0x30 /* '0' */);
    }
    s.append(mm);
    apr_int32_t offset = sign * (hours * 3600 + minutes * 60);
    return new log4cxx::helpers::TimeZoneImpl::FixedTimeZone( s, offset );
  }
  const TimeZonePtr & ltz = getDefault();
  if ( ltz->getID() == id )
  {
    return ltz;
  }
  return getGMT();
}
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;
                        }
                }
        }
}
bool StringHelper::startsWith(const LogString& s, const LogString& prefix)
{
    return s.compare(0, prefix.length(), prefix) == 0;
}