@SuppressWarnings("unchecked")
  public void end(InterpretationContext ec, String e) {
    if (inError) {
      return;
    }

    if (evaluator instanceof LifeCycle) {
      ((LifeCycle) evaluator).start();
      addInfo("Starting evaluator named [" + evaluator.getName() + "]");
    }

    Object o = ec.peekObject();

    if (o != evaluator) {
      addWarn("The object on the top the of the stack is not the evaluator pushed earlier.");
    } else {
      ec.popObject();

      try {
        Map<String, EventEvaluator<?>> evaluatorMap = (Map<String, EventEvaluator<?>>) context
            .getObject(CoreConstants.EVALUATOR_MAP);
        if(evaluatorMap == null) {
          addError("Could not find EvaluatorMap");
        } else {
          evaluatorMap.put(evaluator.getName(), evaluator);
        }
      } catch (Exception ex) {
        addError("Could not set evaluator named [" + evaluator + "].", ex);
      }
    }
  }

Once the children elements are also parsed, now is the time to activate the
evaluator options.

Once the children elements are also parsed now is the time to activate the evaluator options .


public void init(LoggerContext defaultLoggerContext, Object key) throws ClassNotFoundException,
      NoSuchMethodException, InstantiationException, IllegalAccessException,
      InvocationTargetException  {
    if(this.key == null) {
      this.key = key;
    } else if (this.key != key) {
      throw new IllegalAccessException("Only certain classes can access this method.");
    }

    String contextSelectorStr = OptionHelper
        .getSystemProperty(ClassicConstants.LOGBACK_CONTEXT_SELECTOR);
    if (contextSelectorStr == null) {
      contextSelector = new DefaultContextSelector(defaultLoggerContext);
    } else if (contextSelectorStr.equals("JNDI")) {
      throw new RuntimeException("JNDI not supported");
    } else {
      contextSelector = dynamicalContextSelector(defaultLoggerContext,
          contextSelectorStr);
    }
  }

FOR INTERNAL USE. This method is intended for use by  StaticLoggerBinder.

@param defaultLoggerContext
@throws ClassNotFoundException
@throws NoSuchMethodException
@throws InstantiationException
@throws IllegalAccessException
@throws InvocationTargetException

FOR INTERNAL USE . This method is intended for use by StaticLoggerBinder .


static ContextSelector dynamicalContextSelector(
      LoggerContext defaultLoggerContext, String contextSelectorStr)
      throws ClassNotFoundException, SecurityException, NoSuchMethodException,
      IllegalArgumentException, InstantiationException, IllegalAccessException,
      InvocationTargetException {
    Class<?> contextSelectorClass = Loader.loadClass(contextSelectorStr);
    Constructor cons = contextSelectorClass
        .getConstructor(new Class[] { LoggerContext.class });
    return (ContextSelector) cons.newInstance(defaultLoggerContext);
  }

static ContextSelector dynamicalContextSelector ( LoggerContext defaultLoggerContext , String contextSelectorStr ) throws ClassNotFoundException , SecurityException , NoSuchMethodException , IllegalArgumentException , InstantiationException , IllegalAccessException , InvocationTargetException { Class < ? > contextSelectorClass = Loader . loadClass ( contextSelectorStr ) ; Constructor cons = contextSelectorClass . getConstructor ( new Class [ ] { LoggerContext . class } ) ; return ( ContextSelector ) cons . newInstance ( defaultLoggerContext ) ; }

Instantiate the context selector class designated by the user. The selector
must have a constructor taking a LoggerContext instance as an argument.

@param defaultLoggerContext
@param contextSelectorStr
@return an instance of the designated context selector class
@throws ClassNotFoundException
@throws SecurityException
@throws NoSuchMethodException
@throws IllegalArgumentException
@throws InstantiationException
@throws IllegalAccessException
@throws InvocationTargetException

Instantiate the context selector class designated by the user . The selector must have a constructor taking a LoggerContext instance as an argument .


public void setupProperties(LoggerContext context) {
    // legacy properties
    Properties props = new Properties();
    props.setProperty(CoreConstants.DATA_DIR_KEY, getFilesDirectoryPath());
    final String extDir = getMountedExternalStorageDirectoryPath();
    if (extDir != null) {
      props.setProperty(CoreConstants.EXT_DIR_KEY, extDir);
    }
    props.setProperty(CoreConstants.PACKAGE_NAME_KEY, getPackageName());
    props.setProperty(CoreConstants.VERSION_CODE_KEY, getVersionCode());
    props.setProperty(CoreConstants.VERSION_NAME_KEY, getVersionName());

    context.putProperties(props);
  }

public
void
setupProperties
(
LoggerContext
context
)
{
// legacy properties
Properties
props
=
new
Properties
(
)
;
props
.
setProperty
(
CoreConstants
.
DATA_DIR_KEY
,
getFilesDirectoryPath
(
)
)
;
final
String
extDir
=
getMountedExternalStorageDirectoryPath
(
)
;
if
(
extDir
!=
)
{
props
.
setProperty
(
CoreConstants
.
EXT_DIR_KEY
,
extDir
)
;
}
props
.
setProperty
(
CoreConstants
.
PACKAGE_NAME_KEY
,
getPackageName
(
)
)
;
props
.
setProperty
(
CoreConstants
.
VERSION_CODE_KEY
,
getVersionCode
(
)
)
;
props
.
setProperty
(
CoreConstants
.
VERSION_NAME_KEY
,
getVersionName
(
)
)
;
context
.
putProperties
(
props
)
;
}

Sets properties for use in configs
@param context logger context whose property map is updated


public String getMountedExternalStorageDirectoryPath() {
    String path = null;
    String state = Environment.getExternalStorageState();
    if (state.equals(Environment.MEDIA_MOUNTED) ||
        state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
      path = absPath(Environment.getExternalStorageDirectory());
    }
    return path;
  }

public String getMountedExternalStorageDirectoryPath ( ) { String path = null ; String state = Environment . getExternalStorageState ( ) ; if ( state . equals ( Environment . MEDIA_MOUNTED ) || state . equals ( Environment . MEDIA_MOUNTED_READ_ONLY ) ) { path = absPath ( Environment . getExternalStorageDirectory ( ) ) ; } return path ; }

Gets the path to the external storage directory only if
mounted.

@return the absolute path to the external storage directory;
or {@code null} if not mounted.

Gets the path to the external storage directory only if mounted .


public String getDatabaseDirectoryPath() {
    return this.context != null
            && this.context.getDatabasePath("x") != null
            ? this.context.getDatabasePath("x").getParent()
            : "";
  }

public String getDatabaseDirectoryPath ( ) { return this . context != null && this . context . getDatabasePath ( "x" ) != null ? this . context . getDatabasePath ( "x" ) . getParent ( ) : "" ; }

Returns the absolute path to the directory on the Android
filesystem where databases are stored for the current application.

@return the absolute path to the databases directory
(example: "/data/data/com.example/databases")

Returns the absolute path to the directory on the Android filesystem where databases are stored for the current application .


private String getAbsoluteFilePath(String filename) {
    // In Android, relative paths created with File() are relative
    // to root, so fix it by prefixing the path to the app's "files"
    // directory.
    // This transformation is rather expensive, since it involves loading the
    // Android manifest from the APK (which is a ZIP file), and parsing it to
    // retrieve the application package name. This should be avoided if
    // possible as it may perceptibly delay the app launch time.
    if (EnvUtil.isAndroidOS() && !new File(filename).isAbsolute()) {
      String dataDir = context.getProperty(CoreConstants.DATA_DIR_KEY);
      filename = FileUtil.prefixRelativePath(dataDir, filename);
    }
    return filename;
  }

Gets the absolute path to the filename, starting from the app's
"files" directory, if it is not already an absolute path

@param filename filename to evaluate
@return absolute path to the filename

Gets the absolute path to the filename starting from the app s files directory if it is not already an absolute path


public boolean evaluate(ILoggingEvent event) throws NullPointerException,
      EvaluationException {
    return event.getLevel().levelInt >= Level.ERROR_INT;
  }

public boolean evaluate ( ILoggingEvent event ) throws NullPointerException , EvaluationException { return event . getLevel ( ) . levelInt >= Level . ERROR_INT ; }

Return true if event passed as parameter has level ERROR or higher, returns
false otherwise.

Return true if event passed as parameter has level ERROR or higher returns false otherwise .


public String getDiscriminatingValue(ILoggingEvent event) {
    // http://jira.qos.ch/browse/LBCLASSIC-213
    Map<String, String> mdcMap = event.getMDCPropertyMap();
    if (mdcMap == null) {
      return defaultValue;
    }
    String mdcValue = mdcMap.get(key);
    if (mdcValue == null) {
      return defaultValue;
    } else {
      return mdcValue;
    }
  }

Return the value associated with an MDC entry designated by the Key
property. If that value is null, then return the value assigned to the
DefaultValue property.

Return the value associated with an MDC entry designated by the Key property . If that value is null then return the value assigned to the DefaultValue property .


private void updateMaskIfNecessary(long now) {
    final long timeElapsedSinceLastMaskUpdateCheck = now - lastMaskCheck;
    lastMaskCheck = now;
    if (timeElapsedSinceLastMaskUpdateCheck < MASK_INCREASE_THRESHOLD && (mask < MAX_MASK)) {
        mask = (mask << 1) | 1;
    } else if (timeElapsedSinceLastMaskUpdateCheck > MASK_DECREASE_THRESHOLD) {
      mask = mask >>> 2;
    }
  }

private void updateMaskIfNecessary ( long now ) { final long timeElapsedSinceLastMaskUpdateCheck = now - lastMaskCheck ; lastMaskCheck = now ; if ( timeElapsedSinceLastMaskUpdateCheck < MASK_INCREASE_THRESHOLD && ( mask < MAX_MASK ) ) { mask = ( mask << 1 ) | 1 ; } else if ( timeElapsedSinceLastMaskUpdateCheck > MASK_DECREASE_THRESHOLD ) { mask = mask >>> 2 ; } }

update the mask so as to execute change detection code about once every 100 to 8000 milliseconds.

update the mask so as to execute change detection code about once every 100 to 8000 milliseconds .


public FilterReply getFilterChainDecision(E event) {
    final Filter<E>[] filterArrray = filterList.asTypedArray();
    final int len = filterArrray.length;

    for (int i = 0; i < len; i++) {
      final FilterReply r = filterArrray[i].decide(event);
      if (r == FilterReply.DENY || r == FilterReply.ACCEPT) {
        return r;
      }
    }

    // no decision
    return FilterReply.NEUTRAL;
  }

public
FilterReply
getFilterChainDecision
(
E
event
)
{
final
Filter
<
E
>
[
]
filterArrray
=
filterList
.
asTypedArray
(
)
;
final
int
len
=
filterArrray
.
length
;
for
(
int
i
=
0
;
i
<
len
;
i
++
)
{
final
FilterReply
r
=
filterArrray
[
i
]
.
decide
(
event
)
;
if
(
r
==
FilterReply
.
DENY
||
r
==
FilterReply
.
ACCEPT
)
{
return
r
;
}
}
// no decision
return
FilterReply
.
NEUTRAL
;
}

Loop through the filters in the list. As soon as a filter decides on
ACCEPT or DENY, then that value is returned. If all of the filters return
NEUTRAL, then NEUTRAL is returned.

Loop through the filters in the list . As soon as a filter decides on ACCEPT or DENY then that value is returned . If all of the filters return NEUTRAL then NEUTRAL is returned .


private KeyManager[] createKeyManagers(ContextAware context)
      throws NoSuchProviderException, NoSuchAlgorithmException,
      UnrecoverableKeyException, KeyStoreException {

    if (getKeyStore() == null) return null;

    KeyStore keyStore = getKeyStore().createKeyStore();
    context.addInfo(
        "key store of type '" + keyStore.getType()
        + "' provider '" + keyStore.getProvider()
        + "': " + getKeyStore().getLocation());

    KeyManagerFactory kmf = getKeyManagerFactory().createKeyManagerFactory();
    context.addInfo("key manager algorithm '" + kmf.getAlgorithm()
        + "' provider '" + kmf.getProvider() + "'");

    char[] passphrase = getKeyStore().getPassword().toCharArray();
    kmf.init(keyStore, passphrase);
    return kmf.getKeyManagers();
  }

private
KeyManager
[
]
createKeyManagers
(
ContextAware
context
)
throws
NoSuchProviderException
,
NoSuchAlgorithmException
,
UnrecoverableKeyException
,
KeyStoreException
{
if
(
getKeyStore
(
)
==
)
return
;
KeyStore
keyStore
=
getKeyStore
(
)
.
createKeyStore
(
)
;
context
.
addInfo
(
"key store of type '"
+
keyStore
.
getType
(
)
+
"' provider '"
+
keyStore
.
getProvider
(
)
+
"': "
+
getKeyStore
(
)
.
getLocation
(
)
)
;
KeyManagerFactory
kmf
=
getKeyManagerFactory
(
)
.
createKeyManagerFactory
(
)
;
context
.
addInfo
(
"key manager algorithm '"
+
kmf
.
getAlgorithm
(
)
+
"' provider '"
+
kmf
.
getProvider
(
)
+
"'"
)
;
char
[
]
passphrase
=
getKeyStore
(
)
.
getPassword
(
)
.
toCharArray
(
)
;
kmf
.
init
(
keyStore
,
passphrase
)
;
return
kmf
.
getKeyManagers
(
)
;
}

Creates key managers using the receiver's key store configuration.
@param context context for status messages
@return an array of key managers or {@code null} if no key store
configuration was provided
@throws NoSuchProviderException if a provider specified for one
of the key manager components is not known to the platform
@throws NoSuchAlgorithmException if an algorithm specified for
one of the key manager components is not known to the relevant
provider
@throws KeyStoreException if an error occurs in reading a key store

Creates key managers using the receiver s key store configuration .


private TrustManager[] createTrustManagers(ContextAware context)
      throws NoSuchProviderException, NoSuchAlgorithmException,
      KeyStoreException {

    if (getTrustStore() == null) return null;

    KeyStore trustStore = getTrustStore().createKeyStore();
    context.addInfo(
        "trust store of type '" + trustStore.getType()
        + "' provider '" + trustStore.getProvider()
        + "': " + getTrustStore().getLocation());

    TrustManagerFactory tmf = getTrustManagerFactory()
        .createTrustManagerFactory();
    context.addInfo("trust manager algorithm '" + tmf.getAlgorithm()
        + "' provider '" + tmf.getProvider() + "'");

    tmf.init(trustStore);
    return tmf.getTrustManagers();
  }

private
TrustManager
[
]
createTrustManagers
(
ContextAware
context
)
throws
NoSuchProviderException
,
NoSuchAlgorithmException
,
KeyStoreException
{
if
(
getTrustStore
(
)
==
)
return
;
KeyStore
trustStore
=
getTrustStore
(
)
.
createKeyStore
(
)
;
context
.
addInfo
(
"trust store of type '"
+
trustStore
.
getType
(
)
+
"' provider '"
+
trustStore
.
getProvider
(
)
+
"': "
+
getTrustStore
(
)
.
getLocation
(
)
)
;
TrustManagerFactory
tmf
=
getTrustManagerFactory
(
)
.
createTrustManagerFactory
(
)
;
context
.
addInfo
(
"trust manager algorithm '"
+
tmf
.
getAlgorithm
(
)
+
"' provider '"
+
tmf
.
getProvider
(
)
+
"'"
)
;
tmf
.
init
(
trustStore
)
;
return
tmf
.
getTrustManagers
(
)
;
}

Creates trust managers using the receiver's trust store configuration.
@param context context for status messages
@return an array of trust managers or {@code null} if no trust store
configuration was provided
@throws NoSuchProviderException if a provider specified for one
of the trust manager components is not known to the platform
@throws NoSuchAlgorithmException if an algorithm specified for
one of the trust manager components is not known to the relevant
provider
@throws KeyStoreException if an error occurs in reading a key
store containing trust anchors

Creates trust managers using the receiver s trust store configuration .


private KeyStoreFactoryBean keyStoreFromSystemProperties(String property) {
    if (System.getProperty(property) == null) return null;
    KeyStoreFactoryBean keyStore = new KeyStoreFactoryBean();
    keyStore.setLocation(locationFromSystemProperty(property));
    keyStore.setProvider(System.getProperty(property + "Provider"));
    keyStore.setPassword(System.getProperty(property + "Password"));
    keyStore.setType(System.getProperty(property + "Type"));
    return keyStore;
  }

private KeyStoreFactoryBean keyStoreFromSystemProperties ( String property ) { if ( System . getProperty ( property ) == null ) return null ; KeyStoreFactoryBean keyStore = new KeyStoreFactoryBean ( ) ; keyStore . setLocation ( locationFromSystemProperty ( property ) ) ; keyStore . setProvider ( System . getProperty ( property + "Provider" ) ) ; keyStore . setPassword ( System . getProperty ( property + "Password" ) ) ; keyStore . setType ( System . getProperty ( property + "Type" ) ) ; return keyStore ; }

Constructs a key store factory bean using JSSE system properties.
@param property base property name (e.g. {@code javax.net.ssl.keyStore})
@return key store or {@code null} if no value is defined for the
base system property name

Constructs a key store factory bean using JSSE system properties .


private String locationFromSystemProperty(String name) {
    String location = System.getProperty(name);
    if (location != null && !location.startsWith("file:")) {
      location = "file:" + location;
    }
    return location;
  }

private String locationFromSystemProperty ( String name ) { String location = System . getProperty ( name ) ; if ( location != null && ! location . startsWith ( "file:" ) ) { location = "file:" + location ; } return location ; }

Constructs a resource location from a JSSE system property.
@param name property name (e.g. {@code javax.net.ssl.keyStore})
@return URL for the location specified in the property or {@code null}
if no value is defined for the property

Constructs a resource location from a JSSE system property .


public static URL urlForResource(String location)
      throws MalformedURLException, FileNotFoundException {
    if (location == null) {
      throw new NullPointerException("location is required");
    }
    URL url = null;
    if (!location.matches(SCHEME_PATTERN)) {
      url = Loader.getResourceBySelfClassLoader(location);
    }
    else if (location.startsWith(CLASSPATH_SCHEME)) {
      String path = location.substring(CLASSPATH_SCHEME.length());
      if (path.startsWith("/")) {
        path = path.substring(1);
      }
      if (path.length() == 0) {
        throw new MalformedURLException("path is required");
      }
      url = Loader.getResourceBySelfClassLoader(path);
    }
    else {
      url = new URL(location);
    }
    if (url == null) {
      throw new FileNotFoundException(location);
    }
    return url;
  }

public
static
URL
urlForResource
(
String
location
)
throws
MalformedURLException
,
FileNotFoundException
{
if
(
location
==
)
{
throw
new
NullPointerException
(
"location is required"
)
;
}
URL
url
=
;
if
(
!
location
.
matches
(
SCHEME_PATTERN
)
)
{
url
=
Loader
.
getResourceBySelfClassLoader
(
location
)
;
}
else
if
(
location
.
startsWith
(
CLASSPATH_SCHEME
)
)
{
String
path
=
location
.
substring
(
CLASSPATH_SCHEME
.
length
(
)
)
;
if
(
path
.
startsWith
(
"/"
)
)
{
path
=
path
.
substring
(
1
)
;
}
if
(
path
.
length
(
)
==
0
)
{
throw
new
MalformedURLException
(
"path is required"
)
;
}
url
=
Loader
.
getResourceBySelfClassLoader
(
path
)
;
}
else
{
url
=
new
URL
(
location
)
;
}
if
(
url
==
)
{
throw
new
FileNotFoundException
(
location
)
;
}
return
url
;
}

Converts a string describing the location of a resource into a URL object.
@param location String describing the location
@return URL object that refers to {@code location}
@throws MalformedURLException if {@code location} is not a syntatically
valid URL
@throws FileNotFoundException if {@code location} specifies a non-existent
classpath resource
@throws NullPointerException if {@code location} is {@code null}

Converts a string describing the location of a resource into a URL object .


public boolean chainHandlesThrowable(Converter<ILoggingEvent> head) {
    Converter<ILoggingEvent> c = head;
    while (c != null) {
      if (c instanceof ThrowableHandlingConverter) {
        return true;
      }
      c = c.getNext();
    }
    return false;
  }

public boolean chainHandlesThrowable ( Converter < ILoggingEvent > head ) { Converter < ILoggingEvent > c = head ; while ( c != null ) { if ( c instanceof ThrowableHandlingConverter ) { return true ; } c = c . getNext ( ) ; } return false ; }

This method computes whether a chain of converters handles exceptions or
not.

@param head
The first element of the chain
@return true if can handle throwables contained in logging events

This method computes whether a chain of converters handles exceptions or not .


protected void stop() {
        addInfo("Logback context being closed via shutdown hook");

        Context hookContext = getContext();
        if (hookContext instanceof ContextBase) {
            ContextBase context = (ContextBase) hookContext;
            context.stop();
        }
    }

Default method for stopping the Logback context


public static void printInCaseOfErrorsOrWarnings(Context context, long threshold) {
    if (context == null) {
      throw new IllegalArgumentException("Context argument cannot be null");
    }

    StatusManager sm = context.getStatusManager();
    if (sm == null) {
      ps.println("WARN: Context named \"" + context.getName()
          + "\" has no status manager");
    } else {
      StatusUtil statusUtil = new StatusUtil(context);
      if (statusUtil.getHighestLevel(threshold) >= ErrorStatus.WARN) {
        print(sm, threshold);
      }
    }
  }

public
static
void
printInCaseOfErrorsOrWarnings
(
Context
context
,
long
threshold
)
{
if
(
context
==
)
{
throw
new
IllegalArgumentException
(
"Context argument cannot be null"
)
;
}
StatusManager
sm
=
context
.
getStatusManager
(
)
;
if
(
sm
==
)
{
ps
.
println
(
"WARN: Context named \""
+
context
.
getName
(
)
+
"\" has no status manager"
)
;
}
else
{
StatusUtil
statusUtil
=
new
StatusUtil
(
context
)
;
if
(
statusUtil
.
getHighestLevel
(
threshold
)
>=
ErrorStatus
.
WARN
)
{
print
(
sm
,
threshold
)
;
}
}
}

Print the contents of the context status, but only if they contain
warnings or errors occurring later then the threshold.

@param context

Print the contents of the context status but only if they contain warnings or errors occurring later then the threshold .


public static void printIfErrorsOccured(Context context) {
    if (context == null) {
      throw new IllegalArgumentException("Context argument cannot be null");
    }

    StatusManager sm = context.getStatusManager();
    if (sm == null) {
      ps.println("WARN: Context named \"" + context.getName()
          + "\" has no status manager");
    } else {
      StatusUtil statusUtil = new StatusUtil(context);
      if (statusUtil.getHighestLevel(0) == ErrorStatus.ERROR) {
        print(sm);
      }
    }
  }

public
static
void
printIfErrorsOccured
(
Context
context
)
{
if
(
context
==
)
{
throw
new
IllegalArgumentException
(
"Context argument cannot be null"
)
;
}
StatusManager
sm
=
context
.
getStatusManager
(
)
;
if
(
sm
==
)
{
ps
.
println
(
"WARN: Context named \""
+
context
.
getName
(
)
+
"\" has no status manager"
)
;
}
else
{
StatusUtil
statusUtil
=
new
StatusUtil
(
context
)
;
if
(
statusUtil
.
getHighestLevel
(
0
)
==
ErrorStatus
.
ERROR
)
{
print
(
sm
)
;
}
}
}

Print the contents of the context statuses, but only if they contain
errors.

@param context

Print the contents of the context statuses but only if they contain errors .


public static void print(Context context, long threshold) {
     if (context == null) {
       throw new IllegalArgumentException("Context argument cannot be null");
     }

     StatusManager sm = context.getStatusManager();
     if (sm == null) {
       ps.println("WARN: Context named \"" + context.getName()
           + "\" has no status manager");
     } else {
       print(sm, threshold);
     }
   }

public
static
void
print
(
Context
context
,
long
threshold
)
{
if
(
context
==
)
{
throw
new
IllegalArgumentException
(
"Context argument cannot be null"
)
;
}
StatusManager
sm
=
context
.
getStatusManager
(
)
;
if
(
sm
==
)
{
ps
.
println
(
"WARN: Context named \""
+
context
.
getName
(
)
+
"\" has no status manager"
)
;
}
else
{
print
(
sm
,
threshold
)
;
}
}

Print context's status data with a timestamp higher than the threshold.
@param context

Print context s status data with a timestamp higher than the threshold .


private void handleThrowableFirstLine(OutputStream sw, IThrowableProxy tp, String stackTracePrefix, boolean isRootException) throws IOException {
    StringBuilder sb = new StringBuilder().append(stackTracePrefix);

    if (!isRootException) {
      sb.append(CoreConstants.CAUSED_BY);
    }
    sb.append(tp.getClassName()).append(": ").append(tp.getMessage());
    sw.write(sb.toString().getBytes());
    sw.flush();
  }

private
void
handleThrowableFirstLine
(
OutputStream
sw
,
IThrowableProxy
tp
,
String
stackTracePrefix
,
boolean
isRootException
)
throws
IOException
{
StringBuilder
sb
=
new
StringBuilder
(
)
.
append
(
stackTracePrefix
)
;
if
(
!
isRootException
)
{
sb
.
append
(
CoreConstants
.
CAUSED_BY
)
;
}
sb
.
append
(
tp
.
getClassName
(
)
)
.
append
(
": "
)
.
append
(
tp
.
getMessage
(
)
)
;
sw
.
write
(
sb
.
toString
(
)
.
getBytes
(
)
)
;
sw
.
flush
(
)
;
}


private Entry<C> getFromEitherMap(String key) {
    Entry<C> entry = liveMap.get(key);
    if (entry != null)
      return entry;
    else {
      return lingerersMap.get(key);
    }
  }

private Entry < C > getFromEitherMap ( String key ) { Entry < C > entry = liveMap . get ( key ) ; if ( entry != null ) return entry ; else { return lingerersMap . get ( key ) ; } }

Get an entry from the liveMap, if not found search the lingerersMap.

@param key
@return

Get an entry from the liveMap if not found search the lingerersMap .


public void endOfLife(String key) {
    Entry<C> entry = liveMap.remove(key);
    if (entry == null)
      return;
    lingerersMap.put(key, entry);
  }

public void endOfLife ( String key ) { Entry < C > entry = liveMap . remove ( key ) ; if ( entry == null ) return ; lingerersMap . put ( key , entry ) ; }

Mark component identified by 'key' as having reached its end-of-life.

@param key

Mark component identified by key as having reached its end - of - life .


public static FormatInfo valueOf(String str) throws IllegalArgumentException {
    if (str == null) {
      throw new NullPointerException("Argument cannot be null");
    }

    FormatInfo fi = new FormatInfo();

    int indexOfDot = str.indexOf('.');
    String minPart = null;
    String maxPart = null;
    if (indexOfDot != -1) {
      minPart = str.substring(0, indexOfDot);
      if (indexOfDot + 1 == str.length()) {
        throw new IllegalArgumentException("Formatting string [" + str
            + "] should not end with '.'");
      } else {
        maxPart = str.substring(indexOfDot + 1);
      }
    } else {
      minPart = str;
    }

    if (minPart != null && minPart.length() > 0) {
      int min = Integer.parseInt(minPart);
      if (min >= 0) {
        fi.min = min;
      } else {
        fi.min = -min;
        fi.leftPad = false;
      }
    }

    if (maxPart != null && maxPart.length() > 0) {
      int max = Integer.parseInt(maxPart);
      if (max >= 0) {
        fi.max = max;
      } else {
        fi.max = -max;
        fi.leftTruncate = false;
      }
    }

    return fi;

  }

public
static
FormatInfo
valueOf
(
String
str
)
throws
IllegalArgumentException
{
if
(
str
==
)
{
throw
new
NullPointerException
(
"Argument cannot be null"
)
;
}
FormatInfo
fi
=
new
FormatInfo
(
)
;
int
indexOfDot
=
str
.
indexOf
(
'
'
)
;
String
minPart
=
;
String
maxPart
=
;
if
(
indexOfDot
!=
1
)
{
minPart
=
str
.
substring
(
0
,
indexOfDot
)
;
if
(
indexOfDot
+
1
==
str
.
length
(
)
)
{
throw
new
IllegalArgumentException
(
"Formatting string ["
+
str
+
"] should not end with '.'"
)
;
}
else
{
maxPart
=
str
.
substring
(
indexOfDot
+
1
)
;
}
}
else
{
minPart
=
str
;
}
if
(
minPart
!=
&&
minPart
.
length
(
)
>
0
)
{
int
min
=
Integer
.
parseInt
(
minPart
)
;
if
(
min
>=
0
)
{
fi
.
min
=
min
;
}
else
{
fi
.
min
=
min
;
fi
.
leftPad
=
false
;
}
}
if
(
maxPart
!=
&&
maxPart
.
length
(
)
>
0
)
{
int
max
=
Integer
.
parseInt
(
maxPart
)
;
if
(
max
>=
0
)
{
fi
.
max
=
max
;
}
else
{
fi
.
max
=
max
;
fi
.
leftTruncate
=
false
;
}
}
return
fi
;
}

This method is used to parse a string such as "5", ".7", "5.7" or "-5.7" into
a FormatInfo.

@param str A String to convert into a FormatInfo object
@return A newly created and appropriately initialized FormatInfo object.
@throws IllegalArgumentException string is null or ends with '.'

This method is used to parse a string such as 5 . 7 5 . 7 or - 5 . 7 into a FormatInfo .


public void rename(String src, String target) throws RolloverFailure {
    if (src.equals(target)) {
      addWarn("Source and target files are the same [" + src + "]. Skipping.");
      return;
    }
    File srcFile = new File(src);

    if (srcFile.exists()) {
      File targetFile = new File(target);
      createMissingTargetDirsIfNecessary(targetFile);

      addInfo("Renaming file [" + srcFile + "] to [" + targetFile + "]");

      boolean result = srcFile.renameTo(targetFile);

      if (!result) {
        addWarn("Failed to rename file [" + srcFile + "] as [" + targetFile + "].");

        Boolean areOnDifferentVolumes = areOnDifferentVolumes(srcFile, targetFile);
        if (Boolean.TRUE.equals(areOnDifferentVolumes)) {
          addWarn("Detected different file systems for source [" + src + "] and target [" + target + "]. Attempting rename by copying.");
          renameByCopying(src, target);
          return;
        } else {
          addWarn("Please consider leaving the [file] option of " + RollingFileAppender.class.getSimpleName() + " empty.");
          addWarn("See also " + RENAMING_ERROR_URL);
        }
      }
    } else {
      throw new RolloverFailure("File [" + src + "] does not exist.");
    }
  }

A relatively robust file renaming method which in case of failure due to
src and target being on different volumes, falls back onto
renaming by copying.

@param src
@param target
@throws RolloverFailure

A relatively robust file renaming method which in case of failure due to src and target being on different volumes falls back onto renaming by copying .


Boolean areOnDifferentVolumes(File srcFile, File targetFile) throws RolloverFailure {
    if (!EnvUtil.isJDK7OrHigher()) {
      return false;
    }

    // target file is not certain to exist but its parent has to exist given the call hierarchy of this method
    File parentOfTarget = targetFile.getAbsoluteFile().getParentFile();

    if (parentOfTarget == null) {
      addWarn("Parent of target file ["+targetFile+"] is null");
      return null;
    }
    if (!parentOfTarget.exists()) {
      addWarn("Parent of target file [" + targetFile + "] does not exist");
      return null;
    }

    try {
      boolean onSameFileStore = FileStoreUtil.areOnSameFileStore(srcFile, parentOfTarget);
      return !onSameFileStore;
    } catch (RolloverFailure rf) {
      addWarn("Error while checking file store equality", rf);
      return null;
    }
  }

Attempts tp determine whether both files are on different volumes. Returns true if we could determine that
the files are on different volumes. Returns false otherwise or if an error occurred while doing the check.

@param srcFile
@param targetFile
@return true if on different volumes, false otherwise or if an error occurred

Attempts tp determine whether both files are on different volumes . Returns true if we could determine that the files are on different volumes . Returns false otherwise or if an error occurred while doing the check .


public static String getEnv(String key) {
    try {
      return System.getenv(key);
    } catch (SecurityException e) {
      return null;
    }
  }

public static String getEnv ( String key ) { try { return System . getenv ( key ) ; } catch ( SecurityException e ) { return null ; } }

Lookup a key from the environment.

@param key the environment variable's key
@return value corresponding to key from the OS environment


public static String getAndroidSystemProperty(String key) {
    try {
      return SystemPropertiesProxy.getInstance().get(key, null);
    } catch (IllegalArgumentException e) {
      return null;
    }
  }

public static String getAndroidSystemProperty ( String key ) { try { return SystemPropertiesProxy . getInstance ( ) . get ( key , null ) ; } catch ( IllegalArgumentException e ) { return null ; } }

Gets an Android system property

@param key The key to search for
@return the string value of the system property


public void setMDCPropertyMap(Map<String, String> map) {
    if (mdcPropertyMap != null) {
      throw new IllegalStateException(
              "The MDCPropertyMap has been already set for this event.");
    }
    this.mdcPropertyMap = map;

  }

Set the MDC map for this event.

@param map map of MDC properties to values
@since 1.0.8


private String outputMDCForAllKeys(Map<String, String> mdcPropertyMap) {
    StringBuilder buf = new StringBuilder();
    boolean first = true;
    for (Map.Entry<String, String> entry : mdcPropertyMap.entrySet()) {
      if (first) {
        first = false;
      } else {
        buf.append(", ");
      }
      //format: key0=value0, key1=value1
      buf.append(entry.getKey()).append('=').append(entry.getValue());
    }
    return buf.toString();
  }

private
String
outputMDCForAllKeys
(
Map
<
String
,
String
>
mdcPropertyMap
)
{
StringBuilder
buf
=
new
StringBuilder
(
)
;
boolean
first
=
true
;
for
(
Map
.
Entry
<
String
,
String
>
entry
:
mdcPropertyMap
.
entrySet
(
)
)
{
if
(
first
)
{
first
=
false
;
}
else
{
buf
.
append
(
", "
)
;
}
//format: key0=value0, key1=value1
buf
.
append
(
entry
.
getKey
(
)
)
.
append
(
'
'
)
.
append
(
entry
.
getValue
(
)
)
;
}
return
buf
.
toString
(
)
;
}

if no key is specified, return all the values present in the MDC, in the format "k1=v1, k2=v2, ..."

if no key is specified return all the values present in the MDC in the format k1 = v1 k2 = v2 ...


public static StackTraceElement[] extract(Throwable t,
                                            String fqnOfInvokingClass, final int maxDepth,
                                            List<String> frameworkPackageList) {
    if (t == null) {
      return null;
    }

    StackTraceElement[] steArray = t.getStackTrace();
    StackTraceElement[] callerDataArray;

    int found = LINE_NA;
    for (int i = 0; i < steArray.length; i++) {
      if (isInFrameworkSpace(steArray[i].getClassName(),
              fqnOfInvokingClass, frameworkPackageList)) {
        // the caller is assumed to be the next stack frame, hence the +1.
        found = i + 1;
      } else {
        if (found != LINE_NA) {
          break;
        }
      }
    }

    // we failed to extract caller data
    if (found == LINE_NA) {
      return EMPTY_CALLER_DATA_ARRAY;
    }

    int availableDepth = steArray.length - found;
    int desiredDepth = maxDepth < (availableDepth) ? maxDepth : availableDepth;

    callerDataArray = new StackTraceElement[desiredDepth];
    for (int i = 0; i < desiredDepth; i++) {
      callerDataArray[i] = steArray[found + i];
    }
    return callerDataArray;
  }

Extract caller data information as an array based on a Throwable passed as
parameter

@param t Throwable to extract data from
@param fqnOfInvokingClass Fully qualified name of invoking class
@param maxDepth maximum stack depth
@param frameworkPackageList list of framework package names to search
@return caller stack trace array


private static boolean isInFrameworkSpaceList(String currentClass, List<String> frameworkPackageList) {
    if (frameworkPackageList == null)
      return false;

    for (String s : frameworkPackageList) {
      if (currentClass.startsWith(s))
        return true;
    }
    return false;
  }

private static boolean isInFrameworkSpaceList ( String currentClass , List < String > frameworkPackageList ) { if ( frameworkPackageList == null ) return false ; for ( String s : frameworkPackageList ) { if ( currentClass . startsWith ( s ) ) return true ; } return false ; }

Is currentClass present in the list of packages considered part of the logging framework?


public void add(Status newStatus) {
    // LBCORE-72: fire event before the count check
    fireStatusAddEvent(newStatus);

    count++;
    if (newStatus.getLevel() > level) {
      level = newStatus.getLevel();
    }

    synchronized (statusListLock) {
      if (statusList.size() < MAX_HEADER_COUNT) {
        statusList.add(newStatus);
      } else {
        tailBuffer.add(newStatus);
      }
    }

  }

Add a new status object.

@param newStatus
the status message to add


public boolean add(StatusListener listener) {
    synchronized (statusListenerListLock) {
      if (listener instanceof OnConsoleStatusListener) {
        boolean alreadyPresent = checkForPresence(statusListenerList, listener.getClass());
        if (alreadyPresent) {
          return false;
        }
      }
      statusListenerList.add(listener);
    }
    return true;
  }

public boolean add ( StatusListener listener ) { synchronized ( statusListenerListLock ) { if ( listener instanceof OnConsoleStatusListener ) { boolean alreadyPresent = checkForPresence ( statusListenerList , listener . getClass ( ) ) ; if ( alreadyPresent ) { return false ; } } statusListenerList . add ( listener ) ; } return true ; }

This implementation does not allow duplicate installations of OnConsoleStatusListener
@param listener


List<Action> lookupImplicitAction(ElementPath elementPath, Attributes attributes,
      InterpretationContext ec) {
    int len = implicitActions.size();

    for (int i = 0; i < len; i++) {
      ImplicitAction ia = (ImplicitAction) implicitActions.get(i);

      if (ia.isApplicable(elementPath, attributes, ec)) {
        List<Action> actionList = new ArrayList<Action>(1);
        actionList.add(ia);

        return actionList;
      }
    }

    return null;
  }

List < Action > lookupImplicitAction ( ElementPath elementPath , Attributes attributes , InterpretationContext ec ) { int len = implicitActions . size ( ) ; for ( int i = 0 ; i < len ; i ++ ) { ImplicitAction ia = ( ImplicitAction ) implicitActions . get ( i ) ; if ( ia . isApplicable ( elementPath , attributes , ec ) ) { List < Action > actionList = new ArrayList < Action > ( 1 ) ; actionList . add ( ia ) ; return actionList ; } } return null ; }

Check if any implicit actions are applicable. As soon as an applicable
action is found, it is returned. Thus, the returned list will have at most
one element.

Check if any implicit actions are applicable . As soon as an applicable action is found it is returned . Thus the returned list will have at most one element .


List<Action> getApplicableActionList(ElementPath elementPath, Attributes attributes) {
    List<Action> applicableActionList = ruleStore.matchActions(elementPath);

    // logger.debug("set of applicable patterns: " + applicableActionList);
    if (applicableActionList == null) {
      applicableActionList = lookupImplicitAction(elementPath, attributes,
          interpretationContext);
    }

    return applicableActionList;
  }

Return the list of applicable patterns for this


public void setClassLoader(ClassLoader cl)
      throws ClassNotFoundException, SecurityException, NoSuchMethodException {
    if (cl == null) cl = this.getClass().getClassLoader();
    SystemProperties = cl.loadClass("android.os.SystemProperties");
    getString = SystemProperties.getMethod("get", new Class[]{ String.class, String.class });
    getBoolean = SystemProperties.getMethod("getBoolean", new Class[]{ String.class, boolean.class });
  }

public void setClassLoader ( ClassLoader cl ) throws ClassNotFoundException , SecurityException , NoSuchMethodException { if ( cl == null ) cl = this . getClass ( ) . getClassLoader ( ) ; SystemProperties = cl . loadClass ( "android.os.SystemProperties" ) ; getString = SystemProperties . getMethod ( "get" , new Class [ ] { String . class , String . class } ) ; getBoolean = SystemProperties . getMethod ( "getBoolean" , new Class [ ] { String . class , boolean . class } ) ; }

Sets the classloader to lookup the class for android.os.SystemProperties

@param cl desired classloader
@throws ClassNotFoundException android.os.SystemProperties class not found
@throws SecurityException security manager does not allow class loading
@throws NoSuchMethodException get/getBoolean method does not exist

Sets the classloader to lookup the class for android . os . SystemProperties


public String get(String key, String def)
      throws IllegalArgumentException {

    if (SystemProperties == null || getString == null) return null;

    String ret = null;
    try {
      ret = (String) getString.invoke(SystemProperties, new Object[]{ key, def });
    } catch (IllegalArgumentException e) {
      throw e;
    } catch (Exception e) {
    }
    // if return value is null or empty, use the default
    // since neither of those are valid values
    if (ret == null || ret.length() == 0) {
      ret = def;
    }
    return ret;
  }

Get the value for the given key in the Android system properties

@param key
the key to lookup
@param def
a default value to return
@return an empty string if the key isn't found
@throws IllegalArgumentException
if the key exceeds 32 characters


public Boolean getBoolean(String key, boolean def)
      throws IllegalArgumentException {

    if (SystemProperties == null || getBoolean == null) return def;

    Boolean ret = def;
    try {
      ret = (Boolean) getBoolean.invoke(SystemProperties, new Object[]{ key, def });
    } catch (IllegalArgumentException e) {
      throw e;
    } catch (Exception e) {
    }
    return ret;
  }

public Boolean getBoolean ( String key , boolean def ) throws IllegalArgumentException { if ( SystemProperties == null || getBoolean == null ) return def ; Boolean ret = def ; try { ret = ( Boolean ) getBoolean . invoke ( SystemProperties , new Object [ ] { key , def } ) ; } catch ( IllegalArgumentException e ) { throw e ; } catch ( Exception e ) { } return ret ; }

Get the value for the given key in the Android system properties, returned
as a boolean.

Values 'n', 'no', '0', 'false' or 'off' are considered false. Values 'y',
'yes', '1', 'true' or 'on' are considered true. (case insensitive). If the
key does not exist, or has any other value, then the default result is
returned.

@param key
the key to lookup
@param def
a default value to return
@return the key parsed as a boolean, or def if the key isn't found or is
not able to be parsed as a boolean.
@throws IllegalArgumentException
if the key exceeds 32 characters

Get the value for the given key in the Android system properties returned as a boolean .


static public String decapitalize(String name) {
    if (name == null || name.length() == 0) {
      return name;
    } else {
      String nm = name.substring(0, 1).toLowerCase(Locale.US);
      if (name.length() > 1) {
        nm += name.substring(1);
      }
      return nm;
    }
  }

static public String decapitalize ( String name ) { if ( name == null || name . length ( ) == 0 ) { return name ; } else { String nm = name . substring ( 0 , 1 ) . toLowerCase ( Locale . US ) ; if ( name . length ( ) > 1 ) { nm += name . substring ( 1 ) ; } return nm ; } }

Converts a name string's first letter to lowercase

@param name
name string to evaluate
@return the name with its first letter in lowercase

Converts a name string s first letter to lowercase


static public MethodDescriptor[] getMethodDescriptors(Class<?> clazz) {
    ArrayList<MethodDescriptor> methods = new ArrayList<MethodDescriptor>();
    for (Method m : clazz.getMethods()) {
      methods.add(new MethodDescriptor(m.getName(), m));
    }
    return methods.toArray(new MethodDescriptor[0]);
  }

static public MethodDescriptor [ ] getMethodDescriptors ( Class < ? > clazz ) { ArrayList < MethodDescriptor > methods = new ArrayList < MethodDescriptor > ( ) ; for ( Method m : clazz . getMethods ( ) ) { methods . add ( new MethodDescriptor ( m . getName ( ) , m ) ) ; } return methods . toArray ( new MethodDescriptor [ 0 ] ) ; }

Gets a class's method descriptors

@param clazz
class to be evaluated
@return method descriptors


static public PropertyDescriptor[] getPropertyDescriptors(Class<?> clazz) {
    final String SETTER_PREFIX = "set";
    final String GETTER_PREFIX = "get";
    final int LEN_PREFIX = SETTER_PREFIX.length();

    Map<String, PropertyDescriptor> map = new HashMap<String, PropertyDescriptor>();
    for (Method m : clazz.getMethods()) {
      PropertyDescriptor pd = null;
      String mName = m.getName();

      boolean isGet = mName.startsWith(GETTER_PREFIX) && (mName.length() > LEN_PREFIX);
      boolean isSet = mName.startsWith(SETTER_PREFIX) && (mName.length() > LEN_PREFIX);

      if (isGet || isSet) {
        String propName = decapitalize(mName.substring(LEN_PREFIX));

        pd = map.get(propName);
        if (pd == null) {
          pd = new PropertyDescriptor(propName);
          map.put(propName, pd);
        }

        Class<?>[] parmTypes = m.getParameterTypes();
        if (isSet) {
          if (parmTypes.length == 1) { // we only want the single-parm setter
            pd.setWriteMethod(m);
            pd.setPropertyType(parmTypes[0]);
          }
        } else if (isGet) {
          if (parmTypes.length == 0) { // we only want the zero-parm getter
            pd.setReadMethod(m);

            // let setter's type take priority
            if (pd.getPropertyType() == null) {
              pd.setPropertyType(m.getReturnType());
            }
          }
        }
      }
    }

    return map.values().toArray(new PropertyDescriptor[0]);
  }

static
public
PropertyDescriptor
[
]
getPropertyDescriptors
(
Class
<
>
clazz
)
{
final
String
SETTER_PREFIX
=
"set"
;
final
String
GETTER_PREFIX
=
"get"
;
final
int
LEN_PREFIX
=
SETTER_PREFIX
.
length
(
)
;
Map
<
String
,
PropertyDescriptor
>
map
=
new
HashMap
<
String
,
PropertyDescriptor
>
(
)
;
for
(
Method
m
:
clazz
.
getMethods
(
)
)
{
PropertyDescriptor
pd
=
;
String
mName
=
m
.
getName
(
)
;
boolean
isGet
=
mName
.
startsWith
(
GETTER_PREFIX
)
&&
(
mName
.
length
(
)
>
LEN_PREFIX
)
;
boolean
isSet
=
mName
.
startsWith
(
SETTER_PREFIX
)
&&
(
mName
.
length
(
)
>
LEN_PREFIX
)
;
if
(
isGet
||
isSet
)
{
String
propName
=
decapitalize
(
mName
.
substring
(
LEN_PREFIX
)
)
;
pd
=
map
.
get
(
propName
)
;
if
(
pd
==
)
{
pd
=
new
PropertyDescriptor
(
propName
)
;
map
.
put
(
propName
,
pd
)
;
}
Class
<
>
[
]
parmTypes
=
m
.
getParameterTypes
(
)
;
if
(
isSet
)
{
if
(
parmTypes
.
length
==
1
)
{
// we only want the single-parm setter
pd
.
setWriteMethod
(
m
)
;
pd
.
setPropertyType
(
parmTypes
[
0
]
)
;
}
}
else
if
(
isGet
)
{
if
(
parmTypes
.
length
==
0
)
{
// we only want the zero-parm getter
pd
.
setReadMethod
(
m
)
;
// let setter's type take priority
if
(
pd
.
getPropertyType
(
)
==
)
{
pd
.
setPropertyType
(
m
.
getReturnType
(
)
)
;
}
}
}
}
}
return
map
.
values
(
)
.
toArray
(
new
PropertyDescriptor
[
0
]
)
;
}

Gets a class's property descriptors. All properties have methods whose name
begins with "set" or "get". The setters must have a single parameter and
getters must have none.

@param clazz
class to be evaluated
@return property descriptors

Gets a class s property descriptors . All properties have methods whose name begins with set or get . The setters must have a single parameter and getters must have none .


public void start() {
    int errors = 0;
    if (this.encoder == null) {
      addStatus(new ErrorStatus("No encoder set for the appender named \""
          + name + "\".", this));
      errors++;
    }

    if (this.outputStream == null) {
      addStatus(new ErrorStatus(
          "No output stream set for the appender named \"" + name + "\".", this));
      errors++;
    }
    // only error free appenders should be activated
    if (errors == 0) {
      super.start();
    }
  }

Checks that requires parameters are set and if everything is in order,
activates this appender.

Checks that requires parameters are set and if everything is in order activates this appender .


static public void addOnConsoleListenerInstance(Context context, OnConsoleStatusListener onConsoleStatusListener) {
    onConsoleStatusListener.setContext(context);
    boolean effectivelyAdded = context.getStatusManager().add(onConsoleStatusListener);
    if (effectivelyAdded) {
      onConsoleStatusListener.start();
    }
  }

static public void addOnConsoleListenerInstance ( Context context , OnConsoleStatusListener onConsoleStatusListener ) { onConsoleStatusListener . setContext ( context ) ; boolean effectivelyAdded = context . getStatusManager ( ) . add ( onConsoleStatusListener ) ; if ( effectivelyAdded ) { onConsoleStatusListener . start ( ) ; } }

This utility method adds a new OnConsoleStatusListener to the context
passed as parameter.

@param context
@since 1.0.1

This utility method adds a new OnConsoleStatusListener to the context passed as parameter .


public void end(InterpretationContext ec, String name) {
    if (inError) {
      return;
    }

    Object o = ec.peekObject();

    if (o != definer) {
      addWarn("The object at the of the stack is not the property definer for property named ["
          + propertyName + "] pushed earlier.");
    } else {
      addInfo("Popping property definer for property named [" + propertyName
          + "] from the object stack");
      ec.popObject();
      // let's put defined property and value to context but only if it is
      // not null
      String propertyValue = definer.getPropertyValue();
      if(propertyValue != null) {
        ActionUtil.setProperty(ec, propertyName, propertyValue, scope);
      }
    }
  }

Now property definer is initialized by all properties and we can put
property value to context


public String getDiscriminatingValue(ILoggingEvent event) {
    String contextName = event.getLoggerContextVO().getName();

    if (contextName == null) {
      return defaultValue;
    } else {
      return contextName;
    }
  }

public String getDiscriminatingValue ( ILoggingEvent event ) { String contextName = event . getLoggerContextVO ( ) . getName ( ) ; if ( contextName == null ) { return defaultValue ; } else { return contextName ; } }

Return the name of the current context name as found in the logging event.

Return the name of the current context name as found in the logging event .


protected boolean isDiscardable(ILoggingEvent event) {
    Level level = event.getLevel();
    return level.toInt() <= Level.INFO_INT;
  }

protected boolean isDiscardable ( ILoggingEvent event ) { Level level = event . getLevel ( ) ; return level . toInt ( ) <= Level . INFO_INT ; }

Events of level TRACE, DEBUG and INFO are deemed to be discardable.
@param event
@return true if the event is of level TRACE, DEBUG or INFO false otherwise.

Events of level TRACE DEBUG and INFO are deemed to be discardable .


@Override
    public void begin(InterpretationContext ic, String name, Attributes attributes) throws ActionException {
        hook = null;
        inError = false;

        String className = attributes.getValue(CLASS_ATTRIBUTE);
        if (OptionHelper.isEmpty(className)) {
            className = DefaultShutdownHook.class.getName();
            addInfo("Assuming className [" + className + "]");
        }

        try {
            addInfo("About to instantiate shutdown hook of type [" + className + "]");

            hook = (ShutdownHookBase) OptionHelper.instantiateByClassName(className,
                    ShutdownHookBase.class, context);
            hook.setContext(context);

            ic.pushObject(hook);
        }catch (Exception e) {
            inError = true;
            addError("Could not create a shutdown hook of type [" + className + "].", e);
            throw new ActionException(e);
        }
    }

Instantiates a shutdown hook of the given class and sets its name.

The hook thus generated is placed in the {@link InterpretationContext}'s
shutdown hook bag.

Instantiates a shutdown hook of the given class and sets its name .


@Override
    public void end(InterpretationContext ic, String name) throws ActionException {
        if (inError) {
            return;
        }

        Object o = ic.peekObject();
        if (o != hook) {
            addWarn("The object at the of the stack is not the hook pushed earlier.");
        } else {
            ic.popObject();

            Thread hookThread = new Thread(hook, "Logback shutdown hook [" + context.getName() + "]");

            addInfo("Registering shutdown hook with JVM runtime");
            context.putObject(CoreConstants.SHUTDOWN_HOOK_THREAD, hookThread);
            Runtime.getRuntime().addShutdownHook(hookThread);
        }
    }

Once the children elements are also parsed, now is the time to activate the
shutdown hook options.

Once the children elements are also parsed now is the time to activate the shutdown hook options .


private String[] enabledProtocols(String[] supportedProtocols,
      String[] defaultProtocols) {
    if (enabledProtocols == null) {
      // we're assuming that the same engine is used for all configurables
      // so once we determine the enabled set, we won't do it again
      if (OptionHelper.isEmpty(getIncludedProtocols())
          && OptionHelper.isEmpty(getExcludedProtocols())) {
        enabledProtocols = Arrays.copyOf(defaultProtocols,
            defaultProtocols.length);
      }
      else {
        enabledProtocols = includedStrings(supportedProtocols,
            getIncludedProtocols(), getExcludedProtocols());
      }
      for (String protocol : enabledProtocols) {
        addInfo("enabled protocol: " + protocol);
       }
    }
    return enabledProtocols;
  }

Gets the set of enabled protocols based on the configuration.
@param supportedProtocols protocols supported by the SSL engine
@param defaultProtocols default protocols enabled by the SSL engine
@return enabled protocols

Gets the set of enabled protocols based on the configuration .


private String[] enabledCipherSuites(String[] supportedCipherSuites,
      String[] defaultCipherSuites) {
    if (enabledCipherSuites == null) {
      // we're assuming that the same engine is used for all configurables
      // so once we determine the enabled set, we won't do it again
      if (OptionHelper.isEmpty(getIncludedCipherSuites())
          && OptionHelper.isEmpty(getExcludedCipherSuites())) {
        enabledCipherSuites = Arrays.copyOf(defaultCipherSuites,
            defaultCipherSuites.length);
      }
      else {
        enabledCipherSuites = includedStrings(supportedCipherSuites,
            getIncludedCipherSuites(), getExcludedCipherSuites());
      }
      for (String cipherSuite : enabledCipherSuites) {
        addInfo("enabled cipher suite: " + cipherSuite);
      }
    }
    return enabledCipherSuites;
  }

Gets the set of enabled cipher suites based on the configuration.
@param supportedCipherSuites cipher suites supported by the SSL engine
@param defaultCipherSuites default cipher suites enabled by the SSL engine
@return enabled cipher suites

Gets the set of enabled cipher suites based on the configuration .


private String[] includedStrings(String[] defaults, String included,
      String excluded) {
    List<String> values = new ArrayList<String>(defaults.length);
    values.addAll(Arrays.asList(defaults));
    if (included != null) {
      StringCollectionUtil.retainMatching(values, stringToArray(included));
    }
    if (excluded != null) {
      StringCollectionUtil.removeMatching(values, stringToArray(excluded));
    }
    return values.toArray(new String[values.size()]);
  }

private String [ ] includedStrings ( String [ ] defaults , String included , String excluded ) { List < String > values = new ArrayList < String > ( defaults . length ) ; values . addAll ( Arrays . asList ( defaults ) ) ; if ( included != null ) { StringCollectionUtil . retainMatching ( values , stringToArray ( included ) ) ; } if ( excluded != null ) { StringCollectionUtil . removeMatching ( values , stringToArray ( excluded ) ) ; } return values . toArray ( new String [ values . size ( ) ] ) ; }

Applies include and exclude patterns to an array of default string values
to produce an array of strings included by the patterns.
@param defaults default list of string values
@param included comma-separated patterns that identity values to include
@param excluded comma-separated patterns that identity string to exclude
@return an array of strings containing those strings from {@code defaults}
that match at least one pattern in {@code included} that are not
matched by any pattern in {@code excluded}

Applies include and exclude patterns to an array of default string values to produce an array of strings included by the patterns .


static public Scope stringToScope(String scopeStr) {
    if(Scope.SYSTEM.toString().equalsIgnoreCase(scopeStr))
      return Scope.SYSTEM;
     if(Scope.CONTEXT.toString().equalsIgnoreCase(scopeStr))
      return Scope.CONTEXT;

    return Scope.LOCAL;
  }

static public Scope stringToScope ( String scopeStr ) { if ( Scope . SYSTEM . toString ( ) . equalsIgnoreCase ( scopeStr ) ) return Scope . SYSTEM ; if ( Scope . CONTEXT . toString ( ) . equalsIgnoreCase ( scopeStr ) ) return Scope . CONTEXT ; return Scope . LOCAL ; }

Convert a string into a scope. Scope.LOCAL is returned by default.
@param scopeStr the string to be converted
@return a scope corresponding to the input string;  Scope.LOCAL by default.

Convert a string into a scope . Scope . LOCAL is returned by default .


static public void setProperties(InterpretationContext ic, Properties props,
      Scope scope) {
    switch (scope) {
    case LOCAL:
      ic.addSubstitutionProperties(props);
      break;
    case CONTEXT:
      ContextUtil cu = new ContextUtil(ic.getContext());
      cu.addProperties(props);
      break;
    case SYSTEM:
      OptionHelper.setSystemProperties(ic, props);
    }
  }

static public void setProperties ( InterpretationContext ic , Properties props , Scope scope ) { switch ( scope ) { case LOCAL : ic . addSubstitutionProperties ( props ) ; break ; case CONTEXT : ContextUtil cu = new ContextUtil ( ic . getContext ( ) ) ; cu . addProperties ( props ) ; break ; case SYSTEM : OptionHelper . setSystemProperties ( ic , props ) ; } }

Add all the properties found in the argument named 'props' to an
InterpretationContext.

@param ic interpretation context
@param props the properties to set in the context
@param scope scope of properties

Add all the properties found in the argument named props to an InterpretationContext .


public void addAppender(Appender<E> newAppender) {
    if (newAppender == null) {
      throw new IllegalArgumentException("Null argument disallowed");
    }
     appenderList.addIfAbsent(newAppender);
  }

public
void
addAppender
(
Appender
<
E
>
newAppender
)
{
if
(
newAppender
==
)
{
throw
new
IllegalArgumentException
(
"Null argument disallowed"
)
;
}
appenderList
.
addIfAbsent
(
newAppender
)
;
}

Attach an appender. If the appender is already in the list in won't be
added again.

Attach an appender . If the appender is already in the list in won t be added again .


public boolean detachAppender(Appender<E> appender) {
    if (appender == null) {
      return false;
    }
    boolean result;
    result = appenderList.remove(appender);
    return result;
  }

public boolean detachAppender ( Appender < E > appender ) { if ( appender == null ) { return false ; } boolean result ; result = appenderList . remove ( appender ) ; return result ; }

Remove the appender passed as parameter form the list of attached
appenders.

Remove the appender passed as parameter form the list of attached appenders .


public boolean detachAppender(String name) {
    if (name == null) {
      return false;
    }
    boolean removed = false;
      for (Appender<E> a : appenderList) {
        if (name.equals((a).getName())) {
          removed = appenderList.remove(a);
          break;
        }
      }
    return removed;
  }

public boolean detachAppender ( String name ) { if ( name == null ) { return false ; } boolean removed = false ; for ( Appender < E > a : appenderList ) { if ( name . equals ( ( a ) . getName ( ) ) ) { removed = appenderList . remove ( a ) ; break ; } } return removed ; }

Remove the appender with the name passed as parameter form the list of
appenders.

Remove the appender with the name passed as parameter form the list of appenders .


private synchronized void handleParentLevelChange(int newParentLevelInt) {
    // changes in the parent levelInt affect children only if their levelInt is
    // null
    if (level == null) {
      effectiveLevelInt = newParentLevelInt;

      // propagate the parent levelInt change to this logger's children
      if (childrenList != null) {
        int len = childrenList.size();
        for (int i = 0; i < len; i++) {
          Logger child = (Logger) childrenList.get(i);
          child.handleParentLevelChange(newParentLevelInt);
        }
      }
    }
  }

This method is invoked by parent logger to let this logger know that the
prent's levelInt changed.

@param newParentLevelInt

This method is invoked by parent logger to let this logger know that the prent s levelInt changed .


public void callAppenders(ILoggingEvent event) {
    int writes = 0;
    for (Logger l = this; l != null; l = l.parent) {
      writes += l.appendLoopOnAppenders(event);
      if (!l.additive) {
        break;
      }
    }
    // No appenders in hierarchy
    if (writes == 0) {
      loggerContext.noAppenderDefinedWarning(this);
    }
  }

public
void
callAppenders
(
ILoggingEvent
event
)
{
int
writes
=
0
;
for
(
Logger
l
=
this
;
l
!=
;
l
=
l
.
parent
)
{
writes
+=
l
.
appendLoopOnAppenders
(
event
)
;
if
(
!
l
.
additive
)
{
break
;
}
}
// No appenders in hierarchy
if
(
writes
==
0
)
{
loggerContext
.
noAppenderDefinedWarning
(
this
)
;
}
}

Invoke all the appenders of this logger.

@param event
The event to log

Invoke all the appenders of this logger .


public boolean detachAppender(Appender<ILoggingEvent> appender) {
    if (aai == null) {
      return false;
    }
    return aai.detachAppender(appender);
  }

public boolean detachAppender ( Appender < ILoggingEvent > appender ) { if ( aai == null ) { return false ; } return aai . detachAppender ( appender ) ; }

Remove the appender passed as parameter form the list of appenders.

Remove the appender passed as parameter form the list of appenders .


Logger createChildByLastNamePart(final String lastPart) {
    int i_index = LoggerNameUtil.getFirstSeparatorIndexOf(lastPart);
    if (i_index != -1) {
      throw new IllegalArgumentException("Child name [" + lastPart
          + " passed as parameter, may not include [" + CoreConstants.DOT + "]");
    }

    if (childrenList == null) {
      childrenList = new CopyOnWriteArrayList<Logger>();
    }
    Logger childLogger;
    if (this.isRootLogger()) {
      childLogger = new Logger(lastPart, this, this.loggerContext);
    } else {
      childLogger = new Logger(name + CoreConstants.DOT + lastPart, this,
          this.loggerContext);
    }
    childrenList.add(childLogger);
    childLogger.effectiveLevelInt = this.effectiveLevelInt;
    return childLogger;
  }

Create a child of this logger by suffix, that is, the part of the name
extending this logger. For example, if this logger is named "x.y" and the
lastPart is "z", then the created child logger will be named "x.y.z".

<p>
IMPORTANT: Calls to this method must be within a synchronized block on this
logger.

@param lastPart
the suffix (i.e. last part) of the child logger name. This
parameter may not include dots, i.e. the logger separator
character.
@return

Create a child of this logger by suffix that is the part of the name extending this logger . For example if this logger is named x . y and the lastPart is z then the created child logger will be named x . y . z .


private FilterReply callTurboFilters(Marker marker, Level level) {
    return loggerContext.getTurboFilterChainDecision_0_3OrMore(marker, this,
        level, null, null, null);
  }

private FilterReply callTurboFilters ( Marker marker , Level level ) { return loggerContext . getTurboFilterChainDecision_0_3OrMore ( marker , this , level , null , null , null ) ; }

Method that calls the attached TurboFilter objects based on the logger and
the level.

It is used by isYYYEnabled() methods.

It returns the typical FilterReply values: ACCEPT, NEUTRAL or DENY.

@param level
@return the reply given by the TurboFilters

Method that calls the attached TurboFilter objects based on the logger and the level .


public void log(org.slf4j.event.LoggingEvent slf4jEvent) {
    Level level = Level.fromLocationAwareLoggerInteger(slf4jEvent.getLevel().toInt());
    filterAndLog_0_Or3Plus(FQCN, slf4jEvent.getMarker(), level, slf4jEvent.getMessage(), slf4jEvent.getArgumentArray(), slf4jEvent.getThrowable());
  }

public void log ( org . slf4j . event . LoggingEvent slf4jEvent ) { Level level = Level . fromLocationAwareLoggerInteger ( slf4jEvent . getLevel ( ) . toInt ( ) ) ; filterAndLog_0_Or3Plus ( FQCN , slf4jEvent . getMarker ( ) , level , slf4jEvent . getMessage ( ) , slf4jEvent . getArgumentArray ( ) , slf4jEvent . getThrowable ( ) ) ; }

Support SLF4J interception during initialization as introduced in SLF4J version 1.7.15
@since 1.1.4
@param slf4jEvent

Support SLF4J interception during initialization as introduced in SLF4J version 1 . 7 . 15


public Socket call() throws InterruptedException {
    useDefaultsForMissingFields();
    Socket socket = createSocket();
    while (socket == null && !Thread.currentThread().isInterrupted()) {
      Thread.sleep(delayStrategy.nextDelay());
      socket = createSocket();
    }
    return socket;
  }

public Socket call ( ) throws InterruptedException { useDefaultsForMissingFields ( ) ; Socket socket = createSocket ( ) ; while ( socket == null && ! Thread . currentThread ( ) . isInterrupted ( ) ) { Thread . sleep ( delayStrategy . nextDelay ( ) ) ; socket = createSocket ( ) ; } return socket ; }

Loops until the desired connection is established and returns the resulting connector.

Loops until the desired connection is established and returns the resulting connector .


static public boolean createMissingParentDirectories(File file) {
    File parent = file.getParentFile();
    if (parent == null) {
      // Parent directory not specified, therefore it's a request to
      // create nothing. Done! ;)
      return true;
    }
    // File.mkdirs() creates the parent directories only if they don't
    // already exist; and it's okay if they do.
    parent.mkdirs();
    return parent.exists();
  }

Creates the parent directories of a file. If parent directories not
specified in file's path, then nothing is done and this returns
gracefully.

@param file file whose parent directories (if any) should be created
@return {@code true} if either no parents were specified, or if all
parent directories were created successfully; {@code false} otherwise

Creates the parent directories of a file . If parent directories not specified in file s path then nothing is done and this returns gracefully .


public Integer toInteger() {
    switch (levelInt) {
      case ALL_INT:
        return ALL_INTEGER;
      case TRACE_INT:
        return TRACE_INTEGER;
      case DEBUG_INT:
        return DEBUG_INTEGER;
      case INFO_INT:
        return INFO_INTEGER;
      case WARN_INT:
        return WARN_INTEGER;
      case ERROR_INT:
        return ERROR_INTEGER;
      case OFF_INT:
        return OFF_INTEGER;
      default:
        throw new IllegalStateException("Level " + levelStr + ", " + levelInt
                + " is unknown.");
    }
  }

public
Integer
toInteger
(
)
{
switch
(
levelInt
)
{
case
ALL_INT
:
return
ALL_INTEGER
;
case
TRACE_INT
:
return
TRACE_INTEGER
;
case
DEBUG_INT
:
return
DEBUG_INTEGER
;
case
INFO_INT
:
return
INFO_INTEGER
;
case
WARN_INT
:
return
WARN_INTEGER
;
case
ERROR_INT
:
return
ERROR_INTEGER
;
case
OFF_INT
:
return
OFF_INTEGER
;
default
:
throw
new
IllegalStateException
(
"Level "
+
levelStr
+
", "
+
levelInt
+
" is unknown."
)
;
}
}

Convert a Level to an Integer object.

@return This level's Integer mapping.


public static Level toLevel(int val, Level defaultLevel) {
    switch (val) {
      case ALL_INT:
        return ALL;
      case TRACE_INT:
        return TRACE;
      case DEBUG_INT:
        return DEBUG;
      case INFO_INT:
        return INFO;
      case WARN_INT:
        return WARN;
      case ERROR_INT:
        return ERROR;
      case OFF_INT:
        return OFF;
      default:
        return defaultLevel;
    }
  }

public static Level toLevel ( int val , Level defaultLevel ) { switch ( val ) { case ALL_INT : return ALL ; case TRACE_INT : return TRACE ; case DEBUG_INT : return DEBUG ; case INFO_INT : return INFO ; case WARN_INT : return WARN ; case ERROR_INT : return ERROR ; case OFF_INT : return OFF ; default : return defaultLevel ; } }

Convert an integer passed as argument to a Level. If the conversion fails,
then this method returns the specified default.
@param val integer to be evaluated
@param defaultLevel default level if val could not be converted
@return the corresponding level

Convert an integer passed as argument to a Level . If the conversion fails then this method returns the specified default .


public static Set<URL> getResourceOccurrenceCount(String resource,
                                                    ClassLoader classLoader) throws IOException {
    // See LBCLASSIC-159
    Set<URL> urlSet = new HashSet<URL>();
    Enumeration<URL> urlEnum = classLoader.getResources(resource);
    while (urlEnum.hasMoreElements()) {
      URL url = urlEnum.nextElement();
      urlSet.add(url);
    }
    return urlSet;
  }

public
static
Set
<
URL
>
getResourceOccurrenceCount
(
String
resource
,
ClassLoader
classLoader
)
throws
IOException
{
// See LBCLASSIC-159
Set
<
URL
>
urlSet
=
new
HashSet
<
URL
>
(
)
;
Enumeration
<
URL
>
urlEnum
=
classLoader
.
getResources
(
resource
)
;
while
(
urlEnum
.
hasMoreElements
(
)
)
{
URL
url
=
urlEnum
.
nextElement
(
)
;
urlSet
.
add
(
url
)
;
}
return
urlSet
;
}

Compute the number of occurrences a resource can be found by a class
loader.

@param resource the resource name to look for
@param classLoader the classloader used for the search
@return matching resource URLs
@throws IOException

Compute the number of occurrences a resource can be found by a class loader .


public static URL getResource(String resource, ClassLoader classLoader) {
    try {
      return classLoader.getResource(resource);
    } catch (Throwable t) {
      return null;
    }
  }

public static URL getResource ( String resource , ClassLoader classLoader ) { try { return classLoader . getResource ( resource ) ; } catch ( Throwable t ) { return null ; } }

Search for a resource using the classloader passed as parameter.

@param resource    the resource name to look for
@param classLoader the classloader used for the search

Search for a resource using the classloader passed as parameter .


public static ClassLoader getClassLoaderOfObject(Object o) {
    if (o == null) {
      throw new NullPointerException("Argument cannot be null");
    }
    return getClassLoaderOfClass(o.getClass());
  }

public
static
ClassLoader
getClassLoaderOfObject
(
Object
o
)
{
if
(
o
==
)
{
throw
new
NullPointerException
(
"Argument cannot be null"
)
;
}
return
getClassLoaderOfClass
(
o
.
getClass
(
)
)
;
}

Get the class loader of the object passed as argument. Return the system
class loader if appropriate.

@param o object to evaluate
@return the classloader of the object

Get the class loader of the object passed as argument . Return the system class loader if appropriate .


public static ClassLoader getClassLoaderAsPrivileged(final Class<?> clazz) {
    if (!HAS_GET_CLASS_LOADER_PERMISSION)
      return null;
    else
      return AccessController.doPrivileged(
              new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                  return clazz.getClassLoader();
                }
              });
  }

public static ClassLoader getClassLoaderAsPrivileged ( final Class < ? > clazz ) { if ( ! HAS_GET_CLASS_LOADER_PERMISSION ) return null ; else return AccessController . doPrivileged ( new PrivilegedAction < ClassLoader > ( ) { public ClassLoader run ( ) { return clazz . getClassLoader ( ) ; } } ) ; }

Returns the class loader of clazz in an access privileged section.

@param clazz the class to evaluate
@return the classloader of the object

Returns the class loader of clazz in an access privileged section .


public static ClassLoader getClassLoaderOfClass(final Class<?> clazz) {
    ClassLoader cl = clazz.getClassLoader();
    if (cl == null) {
      return ClassLoader.getSystemClassLoader();
    } else {
      return cl;
    }
  }

public static ClassLoader getClassLoaderOfClass ( final Class < ? > clazz ) { ClassLoader cl = clazz . getClassLoader ( ) ; if ( cl == null ) { return ClassLoader . getSystemClassLoader ( ) ; } else { return cl ; } }

Return the class loader which loaded the class passed as argument. Return
the system class loader if appropriate.

@param clazz the class to evaluate
@return the classloader of the object

Return the class loader which loaded the class passed as argument . Return the system class loader if appropriate .


@Override
  public void start() {
    if ((this.encoder == null) || (this.encoder.getLayout() == null)) {
      addError("No layout set for the appender named [" + name + "].");
      return;
    }

    // tag encoder is optional but needs a layout
    if (this.tagEncoder != null) {
      final Layout<?> layout = this.tagEncoder.getLayout();

      if (layout == null) {
        addError("No tag layout set for the appender named [" + name + "].");
        return;
      }

      // prevent stack traces from showing up in the tag
      // (which could lead to very confusing error messages)
      if (layout instanceof PatternLayout) {
        String pattern = this.tagEncoder.getPattern();
        if (!pattern.contains("%nopex")) {
          this.tagEncoder.stop();
          this.tagEncoder.setPattern(pattern + "%nopex");
          this.tagEncoder.start();
        }

        PatternLayout tagLayout = (PatternLayout) layout;
        tagLayout.setPostCompileProcessor(null);
      }
    }

    super.start();
  }

Checks that required parameters are set, and if everything is in order,
activates this appender.

Checks that required parameters are set and if everything is in order activates this appender .


protected String getTag(ILoggingEvent event) {
    // format tag based on encoder layout; truncate if max length
    // exceeded (only necessary for isLoggable(), which throws
    // IllegalArgumentException)
    String tag = (this.tagEncoder != null) ? this.tagEncoder.getLayout().doLayout(event) : event.getLoggerName();
    if (checkLoggable && (tag.length() > MAX_TAG_LENGTH)) {
      tag = tag.substring(0, MAX_TAG_LENGTH - 1) + "*";
    }
    return tag;
  }

Gets the logcat tag string of a logging event
@param event logging event to evaluate
@return the tag string, truncated if max length exceeded


public void begin(InterpretationContext ec, String localName,
      Attributes attributes) {

    if ("substitutionProperty".equals(localName)) {
      addWarn("[substitutionProperty] element has been deprecated. Please use the [property] element instead.");
    }

    String name = attributes.getValue(NAME_ATTRIBUTE);
    String value = attributes.getValue(VALUE_ATTRIBUTE);
    String scopeStr = attributes.getValue(SCOPE_ATTRIBUTE);

    Scope scope = ActionUtil.stringToScope(scopeStr);

    if (checkFileAttributeSanity(attributes)) {
      String file = attributes.getValue(FILE_ATTRIBUTE);
      file = ec.subst(file);
      try {
        FileInputStream istream = new FileInputStream(file);
        loadAndSetProperties(ec, istream, scope);
      } catch (FileNotFoundException e) {
        addError("Could not find properties file [" + file + "].");
      } catch (IOException e1) {
        addError("Could not read properties file [" + file + "].", e1);
      }
    } else if (checkResourceAttributeSanity(attributes)) {
      String resource = attributes.getValue(RESOURCE_ATTRIBUTE);
      resource = ec.subst(resource);
      URL resourceURL = Loader.getResourceBySelfClassLoader(resource);
      if (resourceURL == null) {
        addError("Could not find resource [" + resource + "].");
      } else {
        try {
          InputStream istream = resourceURL.openStream();
          loadAndSetProperties(ec, istream, scope);
        } catch (IOException e) {
          addError("Could not read resource file [" + resource + "].", e);
        }
      }
    } else if (checkValueNameAttributesSanity(attributes)) {
      value = RegularEscapeUtil.basicEscape(value);
      // now remove both leading and trailing spaces
      value = value.trim();
      value = ec.subst(value);
      ActionUtil.setProperty(ec, name, value, scope);

    } else {
      addError(INVALID_ATTRIBUTES);
    }
  }

Set a new property for the execution context by name, value pair, or adds
all the properties found in the given file.

Set a new property for the execution context by name value pair or adds all the properties found in the given file .


public static int getSeparatorIndexOf(String name, int fromIndex) {
    int dotIndex = name.indexOf(CoreConstants.DOT, fromIndex);
    int dollarIndex = name.indexOf(CoreConstants.DOLLAR, fromIndex);

    if (dotIndex == -1 && dollarIndex == -1) return -1;
    if (dotIndex == -1) return dollarIndex;
    if (dollarIndex == -1) return dotIndex;

    return dotIndex < dollarIndex ? dotIndex : dollarIndex;
  }

public static int getSeparatorIndexOf ( String name , int fromIndex ) { int dotIndex = name . indexOf ( CoreConstants . DOT , fromIndex ) ; int dollarIndex = name . indexOf ( CoreConstants . DOLLAR , fromIndex ) ; if ( dotIndex == - 1 && dollarIndex == - 1 ) return - 1 ; if ( dotIndex == - 1 ) return dollarIndex ; if ( dollarIndex == - 1 ) return dotIndex ; return dotIndex < dollarIndex ? dotIndex : dollarIndex ; }

Get the position of the separator character, if any, starting at position
'fromIndex'.

@param name string to search
@param fromIndex starting search index
@return position of separator

Get the position of the separator character if any starting at position fromIndex .


public boolean evaluate(ILoggingEvent event) throws NullPointerException,
      EvaluationException {

    Marker eventsMarker = event.getMarker();
    if (eventsMarker == null) {
      return false;
    }

    for (String markerStr : markerList) {
      if (eventsMarker.contains(markerStr)) {
        return true;
      }
    }
    return false;
  }

public boolean evaluate ( ILoggingEvent event ) throws NullPointerException , EvaluationException { Marker eventsMarker = event . getMarker ( ) ; if ( eventsMarker == null ) { return false ; } for ( String markerStr : markerList ) { if ( eventsMarker . contains ( markerStr ) ) { return true ; } } return false ; }

Return true if event passed as parameter contains one of the specified
user-markers.

Return true if event passed as parameter contains one of the specified user - markers .


protected String getClientThreadName(Socket socket) {
    return String.format(Locale.US, "Logback SocketNode (client: %s)", socket.getRemoteSocketAddress());
  }

protected
String
getClientThreadName
(
Socket
socket
)
{
return
String
.
format
(
Locale
.
US
,
"Logback SocketNode (client: %s)"
,
socket
.
getRemoteSocketAddress
(
)
)
;
}

Returns a name to identify each client thread.

Returns a name to identify each client thread .


static public boolean areOnSameFileStore(File a, File b) throws RolloverFailure {
    if (!a.exists()) {
      throw new IllegalArgumentException("File [" + a + "] does not exist.");
    }
    if (!b.exists()) {
      throw new IllegalArgumentException("File [" + b + "] does not exist.");
    }

// Implements the following by reflection
//    Path pathA = a.toPath();
//    Path pathB = b.toPath();
//
//    FileStore fileStoreA = Files.getFileStore(pathA);
//    FileStore fileStoreB = Files.getFileStore(pathB);
//
//    return fileStoreA.equals(fileStoreB);

    try {
      Class<?> pathClass = Class.forName(PATH_CLASS_STR);
      Class<?> filesClass = Class.forName(FILES_CLASS_STR);

      Method toPath = File.class.getMethod("toPath");
      Method getFileStoreMethod = filesClass.getMethod("getFileStore", pathClass);

      Object pathA = toPath.invoke(a);
      Object pathB = toPath.invoke(b);

      Object fileStoreA = getFileStoreMethod.invoke(null, pathA);
      Object fileStoreB = getFileStoreMethod.invoke(null, pathB);
      return fileStoreA.equals(fileStoreB);
    } catch (Exception e) {
      throw new RolloverFailure("Failed to check file store equality for [" + a + "] and [" + b + "]", e);
    }
  }

This method assumes that both files a and b exists.

@param a first file
@param b second file
@return whether files are on same store
@throws IllegalArgumentException

This method assumes that both files a and b exists .


public void start() {

    if (cbTracker == null) {
      cbTracker = new CyclicBufferTracker<E>();
    }

    session = buildSessionFromProperties();

    if (session == null) {
      addError("Failed to obtain javax.mail.Session. Cannot start.");
      return;
    }

    subjectLayout = makeSubjectLayout(subjectStr);

    started = true;
  }


protected void append(E eventObject) {

    if (!checkEntryConditions()) {
      return;
    }

    String key = discriminator.getDiscriminatingValue(eventObject);
    long now = System.currentTimeMillis();
    final CyclicBuffer<E> cb = cbTracker.getOrCreate(key, now);
    subAppend(cb, eventObject);

    try {
      if (eventEvaluator.evaluate(eventObject)) {
        // clone the CyclicBuffer before sending out asynchronously
        CyclicBuffer<E> cbClone = new CyclicBuffer<E>(cb);
        // see http://jira.qos.ch/browse/LBCLASSIC-221
        cb.clear();

        if (asynchronousSending) {
          // perform actual sending asynchronously
          SenderRunnable senderRunnable = new SenderRunnable(cbClone, eventObject);
          context.getScheduledExecutorService().execute(senderRunnable);
        } else {
          // synchronous sending
          sendBuffer(cbClone, eventObject);
        }
      }
    } catch (EvaluationException ex) {
      errorCount++;
      if (errorCount < CoreConstants.MAX_ERROR_COUNT) {
        addError("SMTPAppender's EventEvaluator threw an Exception-", ex);
      }
    }

    // immediately remove the buffer if asked by the user
    if (eventMarksEndOfLife(eventObject)) {
      cbTracker.endOfLife(key);
    }

    cbTracker.removeStaleComponents(now);

    if (lastTrackerStatusPrint + delayBetweenStatusMessages < now) {
      addInfo("SMTPAppender [" + name + "] is tracking [" + cbTracker.getComponentCount() + "] buffers");
      lastTrackerStatusPrint = now;
      // quadruple 'delay' assuming less than max delay
      if (delayBetweenStatusMessages < MAX_DELAY_BETWEEN_STATUS_MESSAGES) {
        delayBetweenStatusMessages *= 4;
      }
    }
  }

Perform SMTPAppender specific appending actions, delegating some of them to
a subclass and checking if the event triggers an e-mail to be sent.

Perform SMTPAppender specific appending actions delegating some of them to a subclass and checking if the event triggers an e - mail to be sent .


protected void sendBuffer(CyclicBuffer<E> cb, E lastEventObject) {

    // Note: this code already owns the monitor for this
    // appender. This frees us from needing to synchronize on 'cb'.
    try {
      MimeBodyPart part = new MimeBodyPart();

      StringBuffer sbuf = new StringBuffer();

      String header = layout.getFileHeader();
      if (header != null) {
        sbuf.append(header);
      }
      String presentationHeader = layout.getPresentationHeader();
      if (presentationHeader != null) {
        sbuf.append(presentationHeader);
      }
      fillBuffer(cb, sbuf);
      String presentationFooter = layout.getPresentationFooter();
      if (presentationFooter != null) {
        sbuf.append(presentationFooter);
      }
      String footer = layout.getFileFooter();
      if (footer != null) {
        sbuf.append(footer);
      }

      String subjectStr = "Undefined subject";
      if (subjectLayout != null) {
        subjectStr = subjectLayout.doLayout(lastEventObject);

        // The subject must not contain new-line characters, which cause
        // an SMTP error (LOGBACK-865). Truncate the string at the first
        // new-line character.
        int newLinePos = (subjectStr != null) ? subjectStr.indexOf('\n') : -1;
        if (newLinePos > -1) {
          subjectStr = subjectStr.substring(0, newLinePos);
        }
      }

      MimeMessage mimeMsg = new MimeMessage(session);

      if (from != null) {
        mimeMsg.setFrom(getAddress(from));
      } else {
        mimeMsg.setFrom();
      }

      mimeMsg.setSubject(subjectStr, charsetEncoding);

      List<InternetAddress> destinationAddresses = parseAddress(lastEventObject);
      if (destinationAddresses.isEmpty()) {
        addInfo("Empty destination address. Aborting email transmission");
        return;
      }

      InternetAddress[] toAddressArray = destinationAddresses.toArray(EMPTY_IA_ARRAY);
      mimeMsg.setRecipients(Message.RecipientType.TO, toAddressArray);

      String contentType = layout.getContentType();

      if (ContentTypeUtil.isTextual(contentType)) {
        part.setText(sbuf.toString(), charsetEncoding, ContentTypeUtil
                .getSubType(contentType));
      } else {
        part.setContent(sbuf.toString(), layout.getContentType());
      }

      Multipart mp = new MimeMultipart();
      mp.addBodyPart(part);
      mimeMsg.setContent(mp);

      updateMimeMsg(mimeMsg, cb, lastEventObject);

      mimeMsg.setSentDate(new Date());
      addInfo("About to send out SMTP message \"" + subjectStr + "\" to " + Arrays.toString(toAddressArray));
      Transport.send(mimeMsg);
    } catch (Exception e) {
      addError("Error occurred while sending e-mail notification.", e);
    }
  }

Send the contents of the cyclic buffer as an e-mail message.
@param cb the cyclic buffer
@param lastEventObject the log event

Send the contents of the cyclic buffer as an e - mail message .


public void addMDCValueLevelPair(MDCValueLevelPair mdcValueLevelPair) {
    if (valueLevelMap.containsKey(mdcValueLevelPair.getValue())) {
      addError(mdcValueLevelPair.getValue() + " has been already set");
    } else {
      valueLevelMap.put(mdcValueLevelPair.getValue(), mdcValueLevelPair
          .getLevel());
    }
  }

public
void
addMDCValueLevelPair
(
MDCValueLevelPair
mdcValueLevelPair
)
{
if
(
valueLevelMap
.
containsKey
(
mdcValueLevelPair
.
getValue
(
)
)
)
{
addError
(
mdcValueLevelPair
.
getValue
(
)
+
" has been already set"
)
;
}
else
{
valueLevelMap
.
put
(
mdcValueLevelPair
.
getValue
(
)
,
mdcValueLevelPair
.
getLevel
(
)
)
;
}
}


@SuppressWarnings("unchecked")
  DynamicConverter<E> createConverter(SimpleKeywordNode kn) {
    String keyword = (String) kn.getValue();
    String converterClassStr = (String) converterMap.get(keyword);

    if (converterClassStr != null) {
      try {
        return (DynamicConverter<E>) OptionHelper.instantiateByClassName(
                converterClassStr, DynamicConverter.class, context);
      } catch (Exception e) {
        addError("Failed to instantiate converter class [" + converterClassStr
                + "] for keyword ["+keyword+"]", e);
        return null;
      }
    } else {
      addError("There is no conversion class registered for conversion word ["
              + keyword + "]");
      return null;
    }
  }

Attempt to create a converter using the information found in
'converterMap'.

@param kn
@return

Attempt to create a converter using the information found in converterMap .


@SuppressWarnings("unchecked")
  CompositeConverter<E> createCompositeConverter(CompositeNode cn) {
    String keyword = (String) cn.getValue();
    String converterClassStr = (String) converterMap.get(keyword);

    if (converterClassStr != null) {
      try {
        return (CompositeConverter<E>) OptionHelper.instantiateByClassName(
                converterClassStr, CompositeConverter.class, context);
      } catch (Exception e) {
        addError("Failed to instantiate converter class [" + converterClassStr
                + "] as a composite converter for keyword ["+keyword+"]", e);
        return null;
      }
    } else {
      addError("There is no conversion class registered for composite conversion word ["
              + keyword + "]");
      return null;
    }
  }

Attempt to create a converter using the information found in
'compositeConverterMap'.

@param cn
@return

Attempt to create a converter using the information found in compositeConverterMap .


protected void determineCompressionMode() {
    if (fileNamePatternStr.endsWith(".gz")) {
      addInfo("Will use gz compression");
      compressionMode = CompressionMode.GZ;
    } else if (fileNamePatternStr.endsWith(".zip")) {
      addInfo("Will use zip compression");
      compressionMode = CompressionMode.ZIP;
    } else {
      addInfo("No compression will be used");
      compressionMode = CompressionMode.NONE;
    }
  }

protected
void
determineCompressionMode
(
)
{
if
(
fileNamePatternStr
.
endsWith
(
".gz"
)
)
{
addInfo
(
"Will use gz compression"
)
;
compressionMode
=
CompressionMode
.
GZ
;
}
else
if
(
fileNamePatternStr
.
endsWith
(
".zip"
)
)
{
addInfo
(
"Will use zip compression"
)
;
compressionMode
=
CompressionMode
.
ZIP
;
}
else
{
addInfo
(
"No compression will be used"
)
;
compressionMode
=
CompressionMode
.
;
}
}

Given the FileNamePattern string, this method determines the compression
mode depending on last letters of the fileNamePatternStr. Patterns ending
with .gz imply GZIP compression, endings with '.zip' imply ZIP compression.
Otherwise and by default, there is no compression.

Given the FileNamePattern string this method determines the compression mode depending on last letters of the fileNamePatternStr . Patterns ending with . gz imply GZIP compression endings with . zip imply ZIP compression . Otherwise and by default there is no compression .


public final void doConfigure(URL url) throws JoranException {
    InputStream in = null;
    try {
      informContextOfURLUsedForConfiguration(getContext(), url);
      URLConnection urlConnection = url.openConnection();
      // per http://jira.qos.ch/browse/LBCORE-105
      // per http://jira.qos.ch/browse/LBCORE-127
      urlConnection.setUseCaches(false);

      // this closes the stream for us
      in = urlConnection.getInputStream();
      doConfigure(in, url.toExternalForm());
    } catch (IOException ioe) {
      String errMsg = "Could not open URL [" + url + "].";
      addError(errMsg, ioe);
      throw new JoranException(errMsg, ioe);
    } finally {
      CloseUtil.closeQuietly(in);
    }
  }

Configures logback with the configuration XML read from a file,
located at the given URL

@param url URL to the file, containing the configuration XML
@throws JoranException configuration error occurred

Configures logback with the configuration XML read from a file located at the given URL


public final void doConfigure(File file) throws JoranException {
    FileInputStream fis = null;
    try {
      URL url = file.toURI().toURL();
      informContextOfURLUsedForConfiguration(getContext(), url);
      fis = new FileInputStream(file);

      // this closes the stream for us
      doConfigure(fis, url.toExternalForm());
    } catch (IOException ioe) {
      String errMsg = "Could not open [" + file.getPath() + "].";
      addError(errMsg, ioe);
      throw new JoranException(errMsg, ioe);
    } finally {
      CloseUtil.closeQuietly(fis);
    }
  }

public
final
void
doConfigure
(
File
file
)
throws
JoranException
{
FileInputStream
fis
=
;
try
{
URL
url
=
file
.
toURI
(
)
.
toURL
(
)
;
informContextOfURLUsedForConfiguration
(
getContext
(
)
,
url
)
;
fis
=
new
FileInputStream
(
file
)
;
// this closes the stream for us
doConfigure
(
fis
,
url
.
toExternalForm
(
)
)
;
}
catch
(
IOException
ioe
)
{
String
errMsg
=
"Could not open ["
+
file
.
getPath
(
)
+
"]."
;
addError
(
errMsg
,
ioe
)
;
throw
new
JoranException
(
errMsg
,
ioe
)
;
}
finally
{
CloseUtil
.
closeQuietly
(
fis
)
;
}
}

Configures logback with the configuration XML read from a given file

@param file the file, containing the configuration XML
@throws JoranException configuration error occurred


public final void doConfigure(InputStream inputStream) throws JoranException {
    try {
      doConfigure(new InputSource(inputStream));
    } finally {
      try {
        inputStream.close();
      } catch (IOException ioe) {
        String errMsg = "Could not close the stream";
        addError(errMsg, ioe);
        throw new JoranException(errMsg, ioe);
      }
    }
  }

public
final
void
doConfigure
(
InputStream
inputStream
)
throws
JoranException
{
try
{
doConfigure
(
new
InputSource
(
inputStream
)
)
;
}
finally
{
try
{
inputStream
.
close
(
)
;
}
catch
(
IOException
ioe
)
{
String
errMsg
=
"Could not close the stream"
;
addError
(
errMsg
,
ioe
)
;
throw
new
JoranException
(
errMsg
,
ioe
)
;
}
}
}

Configures logback with the configuraiton XML read from an input stream,
and then closes the stream

@param inputStream stream to contents of configuration XML
@throws JoranException configuration error occurred

Configures logback with the configuraiton XML read from an input stream and then closes the stream


protected void buildInterpreter() {
    RuleStore rs = new SimpleRuleStore(context);
    addInstanceRules(rs);
    this.interpreter = new Interpreter(context, rs, initialElementPath());
    InterpretationContext interpretationContext = interpreter.getInterpretationContext();
    interpretationContext.setContext(context);
    addImplicitRules(interpreter);
    addDefaultNestedComponentRegistryRules(interpretationContext.getDefaultNestedComponentRegistry());
  }

protected void buildInterpreter ( ) { RuleStore rs = new SimpleRuleStore ( context ) ; addInstanceRules ( rs ) ; this . interpreter = new Interpreter ( context , rs , initialElementPath ( ) ) ; InterpretationContext interpretationContext = interpreter . getInterpretationContext ( ) ; interpretationContext . setContext ( context ) ; addImplicitRules ( interpreter ) ; addDefaultNestedComponentRegistryRules ( interpretationContext . getDefaultNestedComponentRegistry ( ) ) ; }

Builds a generic configuration-XML interpreter

Builds a generic configuration - XML interpreter


private final void doConfigure(final InputSource inputSource)
          throws JoranException {

    long threshold = System.currentTimeMillis();
//    if (!ConfigurationWatchListUtil.wasConfigurationWatchListReset(context)) {
//      informContextOfURLUsedForConfiguration(getContext(), null);
//    }
    SaxEventRecorder recorder = new SaxEventRecorder(context);
    recorder.recordEvents(inputSource);
    doConfigure(recorder.getSaxEventList());
    // no exceptions a this level
    StatusUtil statusUtil = new StatusUtil(context);
    if (statusUtil.noXMLParsingErrorsOccurred(threshold)) {
      addInfo("Registering current configuration as safe fallback point");
      registerSafeConfiguration(recorder.getSaxEventList());
    }
  }

Configures logback with the configuration XML read from an input source.

@param inputSource the input source, containing the configuration XML
@throws JoranException

Configures logback with the configuration XML read from an input source .


public void doConfigure(final List<SaxEvent> eventList)
          throws JoranException {
    buildInterpreter();
    // disallow simultaneous configurations of the same context
    synchronized (context.getConfigurationLock()) {
      interpreter.getEventPlayer().play(eventList);
    }
  }

Configures logback with SAX events of configuration XML

@param eventList list of SAX events
@throws JoranException configuration error occurred


public String getProperty(String key) {
    if (CONTEXT_NAME_KEY.equals(key))
      return getName();

    return (String) this.propertyMap.get(key);
  }

public String getProperty ( String key ) { if ( CONTEXT_NAME_KEY . equals ( key ) ) return getName ( ) ; return ( String ) this . propertyMap . get ( key ) ; }

Given a key, return the corresponding property value. If invoked with
the special key "CONTEXT_NAME", the name of the context is returned.

@param key the property's key
@return the string value associated with the key

Given a key return the corresponding property value . If invoked with the special key CONTEXT_NAME the name of the context is returned .


public void setName(String name) throws IllegalStateException {
    if (name != null && name.equals(this.name)) {
      return; // idempotent naming
    }
    if (this.name == null
            || CoreConstants.DEFAULT_CONTEXT_NAME.equals(this.name)) {
      this.name = name;
    } else {
      throw new IllegalStateException("Context has been already given a name");
    }
  }

public
void
setName
(
String
name
)
throws
IllegalStateException
{
if
(
name
!=
&&
name
.
equals
(
this
.
name
)
)
{
return
;
// idempotent naming
}
if
(
this
.
name
==
||
CoreConstants
.
DEFAULT_CONTEXT_NAME
.
equals
(
this
.
name
)
)
{
this
.
name
=
name
;
}
else
{
throw
new
IllegalStateException
(
"Context has been already given a name"
)
;
}
}

The context name can be set only if it is not already set, or if the
current name is the default context name, namely "default", or if the
current name and the old name are the same.

@throws IllegalStateException if the context already has a name, other than "default".

The context name can be set only if it is not already set or if the current name is the default context name namely default or if the current name and the old name are the same .


static public boolean contextHasStatusListener(Context context) {
    StatusManager sm = context.getStatusManager();
    if(sm == null)
      return false;
    List<StatusListener> listeners = sm.getCopyOfStatusListenerList();
    if(listeners == null || listeners.size() == 0)
      return false;
    else
      return true;
  }

static public boolean contextHasStatusListener ( Context context ) { StatusManager sm = context . getStatusManager ( ) ; if ( sm == null ) return false ; List < StatusListener > listeners = sm . getCopyOfStatusListenerList ( ) ; if ( listeners == null || listeners . size ( ) == 0 ) return false ; else return true ; }

Returns true if the StatusManager associated with the context passed
as parameter has one or more StatusListener instances registered. Returns
false otherwise.

@param context
@return true if one or more StatusListeners registered, false otherwise
@since 1.0.8

Returns true if the StatusManager associated with the context passed as parameter has one or more StatusListener instances registered . Returns false otherwise .