public long timeOfLastReset() {
    List<Status> statusList = sm.getCopyOfStatusList();
    if (statusList == null)
      return -1;

    int len = statusList.size();
    for (int i = len - 1; i >= 0; i--) {
      Status s = statusList.get(i);
      if (CoreConstants.RESET_MSG_PREFIX.equals(s.getMessage())) {
        return s.getDate();
      }
    }
    return -1;
  }

public long timeOfLastReset ( ) { List < Status > statusList = sm . getCopyOfStatusList ( ) ; if ( statusList == null ) return - 1 ; int len = statusList . size ( ) ; for ( int i = len - 1 ; i >= 0 ; i -- ) { Status s = statusList . get ( i ) ; if ( CoreConstants . RESET_MSG_PREFIX . equals ( s . getMessage ( ) ) ) { return s . getDate ( ) ; } } return - 1 ; }

Return the time of last reset. -1 if last reset time could not be found

@return time of last reset or -1

Return the time of last reset . - 1 if last reset time could not be found


@Override
  public void start() {
    int errorCount = 0;

    try {
      Parser<E> p = new Parser<E>(pattern);
      p.setContext(getContext());
      Node t = p.parse();
      this.head = p.compile(t, getEffectiveConverterMap());
      ConverterUtil.startConverters(this.head);
    } catch (ScanException ex) {
      addError("Incorrect pattern found", ex);
      errorCount++;
    }

    if (errorCount == 0) {
      super.started = true;
    }
  }

@
Override
public
void
start
(
)
{
int
errorCount
=
0
;
try
{
Parser
<
E
>
p
=
new
Parser
<
E
>
(
pattern
)
;
p
.
setContext
(
getContext
(
)
)
;
Node
t
=
p
.
parse
(
)
;
this
.
head
=
p
.
compile
(
t
,
getEffectiveConverterMap
(
)
)
;
ConverterUtil
.
startConverters
(
this
.
head
)
;
}
catch
(
ScanException
ex
)
{
addError
(
"Incorrect pattern found"
,
ex
)
;
errorCount
++
;
}
if
(
errorCount
==
0
)
{
super
.
started
=
true
;
}
}

Parses the pattern and creates the Converter linked list.

Parses the pattern and creates the Converter linked list .


public Map<String, String> getEffectiveConverterMap() {
    Map<String, String> effectiveMap = new HashMap<String, String>();

    // add the least specific map fist
    Map<String, String> defaultMap = getDefaultConverterMap();
    if (defaultMap != null) {
      effectiveMap.putAll(defaultMap);
    }

    // contextMap is more specific than the default map
    Context context = getContext();
    if (context != null) {
      @SuppressWarnings("unchecked")
      Map<String, String> contextMap = (Map<String, String>) context
          .getObject(CoreConstants.PATTERN_RULE_REGISTRY);
      if (contextMap != null) {
        effectiveMap.putAll(contextMap);
      }
    }
    return effectiveMap;
  }

Returns a map where the default converter map is merged with the map
contained in the context.
@return the converter map

Returns a map where the default converter map is merged with the map contained in the context .


@Override
  public String getFileHeader() {
    StringBuilder sbuf = new StringBuilder();
    sbuf.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"");
    sbuf.append(" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
    sbuf.append(LINE_SEPARATOR);
    sbuf.append("<html>");
    sbuf.append(LINE_SEPARATOR);
    sbuf.append("  <head>");
    sbuf.append(LINE_SEPARATOR);
    sbuf.append("    <title>");
    sbuf.append(title);
    sbuf.append("</title>");
    sbuf.append(LINE_SEPARATOR);

    cssBuilder.addCss(sbuf);

    sbuf.append(LINE_SEPARATOR);
    sbuf.append("  </head>");
    sbuf.append(LINE_SEPARATOR);
    sbuf.append("<body>");
    sbuf.append(LINE_SEPARATOR);

    return sbuf.toString();
  }

Returns appropriate HTML headers.
@return the headers


@Override
  public String getFileFooter() {
    StringBuilder sbuf = new StringBuilder();
    sbuf.append(LINE_SEPARATOR);
    sbuf.append("");
    return sbuf.toString();
  }

@ Override public String getFileFooter ( ) { StringBuilder sbuf = new StringBuilder ( ) ; sbuf . append ( LINE_SEPARATOR ) ; sbuf . append ( "" ) ; return sbuf . toString ( ) ; }


@SuppressWarnings("unchecked")
  public void begin(InterpretationContext ec, String localName,
      Attributes attributes) throws ActionException {
    // We are just beginning, reset variables
    appender = null;
    inError = false;

    String className = attributes.getValue(CLASS_ATTRIBUTE);
    if (OptionHelper.isEmpty(className)) {
      addError("Missing class name for appender. Near [" + localName
          + "] line " + getLineNumber(ec));
      inError = true;
      return;
    }

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

      appender = (Appender<E>) OptionHelper.instantiateByClassName(className,
          ch.qos.logback.core.Appender.class, context);

      appender.setContext(context);

      String appenderName = ec.subst(attributes.getValue(NAME_ATTRIBUTE));

      if (OptionHelper.isEmpty(appenderName)) {
        addWarn("No appender name given for appender of type " + className
            + "].");
      } else {
        appender.setName(appenderName);
        addInfo("Naming appender as [" + appenderName + "]");
      }

      // The execution context contains a bag which contains the appenders
      // created thus far.
      HashMap<String, Appender<E>> appenderBag = (HashMap<String, Appender<E>>) ec.getObjectMap().get(
          ActionConst.APPENDER_BAG);

      // add the appender just created to the appender bag.
      appenderBag.put(appenderName, appender);

      ec.pushObject(appender);
    } catch (Exception oops) {
      inError = true;
      addError("Could not create an Appender of type [" + className + "].",
          oops);
      throw new ActionException(oops);
    }
  }

Instantiates an appender of the given class and sets its name.

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

Instantiates an appender of the given class and sets its name .


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

    if (appender instanceof LifeCycle) {
      ((LifeCycle) appender).start();
    }

    Object o = ec.peekObject();

    if (o != appender) {
      addWarn("The object at the of the stack is not the appender named ["
          + appender.getName() + "] pushed earlier.");
    } else {
      ec.popObject();
    }
  }

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

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


private Collection<T> copyClients() {
    clientsLock.lock();
    try {
      Collection<T> copy = new ArrayList<T>(clients);
      return copy;
    }
    finally {
      clientsLock.unlock();
    }
  }

private Collection < T > copyClients ( ) { clientsLock . lock ( ) ; try { Collection < T > copy = new ArrayList < T > ( clients ) ; return copy ; } finally { clientsLock . unlock ( ) ; } }

Creates a copy of the collection of all clients that are presently
being tracked by the server.
@return collection of client objects

Creates a copy of the collection of all clients that are presently being tracked by the server .


private void addClient(T client) {
    clientsLock.lock();
    try {
      clients.add(client);
    }
    finally {
      clientsLock.unlock();
    }
  }

private void addClient ( T client ) { clientsLock . lock ( ) ; try { clients . add ( client ) ; } finally { clientsLock . unlock ( ) ; } }

Adds a client to the collection of those being tracked by the server.
@param client the client to add

Adds a client to the collection of those being tracked by the server .


private void removeClient(T client) {
    clientsLock.lock();
    try {
      clients.remove(client);
    }
    finally {
      clientsLock.unlock();
    }
  }

private void removeClient ( T client ) { clientsLock . lock ( ) ; try { clients . remove ( client ) ; } finally { clientsLock . unlock ( ) ; } }

Removes a client from the collection of those being tracked by the server.
@param client the client to remote

Removes a client from the collection of those being tracked by the server .


public Map<String, String> getCopyOfContextMap() {
    Map<String, String> hashMap = copyOnThreadLocal.get();
    if (hashMap == null) {
      return null;
    } else {
      return new HashMap<String, String>(hashMap);
    }
  }

public Map < String , String > getCopyOfContextMap ( ) { Map < String , String > hashMap = copyOnThreadLocal . get ( ) ; if ( hashMap == null ) { return null ; } else { return new HashMap < String , String > ( hashMap ) ; } }

Return a copy of the current thread's context map. Returned value may be
null.

Return a copy of the current thread s context map . Returned value may be null .


public static Method getValueOfMethod(Class<?> type) {
    try {
      return type.getMethod(CoreConstants.VALUE_OF, STING_CLASS_PARAMETER);
    } catch (NoSuchMethodException e) {
      return null;
    } catch (SecurityException e) {
      return null;
    }
  }

public static Method getValueOfMethod ( Class < ? > type ) { try { return type . getMethod ( CoreConstants . VALUE_OF , STING_CLASS_PARAMETER ) ; } catch ( NoSuchMethodException e ) { return null ; } catch ( SecurityException e ) { return null ; } }

returned value may be null and in most cases it is null.

returned value may be null and in most cases it is null .


public FilterReply getTurboFilterChainDecision(final Marker marker,
      final Logger logger, final Level level, final String format,
      final Object[] params, final Throwable t) {

    final int size = size();
//    if (size == 0) {
//      return FilterReply.NEUTRAL;
//    }
    if (size == 1) {
      try {
        TurboFilter tf = get(0);
        return tf.decide(marker, logger, level, format, params, t);
      } catch (IndexOutOfBoundsException iobe) {
        return FilterReply.NEUTRAL;
      }
    }

    Object[] tfa = toArray();
    final int len = tfa.length;
    for (int i = 0; i < len; i++) {
    //for (TurboFilter tf : this) {
      final TurboFilter tf = (TurboFilter) tfa[i];
      final FilterReply r = tf.decide(marker, logger, level, format, params, t);
      if (r == FilterReply.DENY || r == FilterReply.ACCEPT) {
        return r;
      }
    }
    return FilterReply.NEUTRAL;
  }

public
FilterReply
getTurboFilterChainDecision
(
final
Marker
marker
,
final
Logger
logger
,
final
Level
level
,
final
String
format
,
final
Object
[
]
params
,
final
Throwable
t
)
{
final
int
size
=
size
(
)
;
//    if (size == 0) {
//      return FilterReply.NEUTRAL;
//    }
if
(
size
==
1
)
{
try
{
TurboFilter
tf
=
get
(
0
)
;
return
tf
.
decide
(
marker
,
logger
,
level
,
format
,
params
,
t
)
;
}
catch
(
IndexOutOfBoundsException
iobe
)
{
return
FilterReply
.
NEUTRAL
;
}
}
Object
[
]
tfa
=
toArray
(
)
;
final
int
len
=
tfa
.
length
;
for
(
int
i
=
0
;
i
<
len
;
i
++
)
{
//for (TurboFilter tf : this) {
final
TurboFilter
tf
=
(
TurboFilter
)
tfa
[
i
]
;
final
FilterReply
r
=
tf
.
decide
(
marker
,
logger
,
level
,
format
,
params
,
t
)
;
if
(
r
==
FilterReply
.
DENY
||
r
==
FilterReply
.
ACCEPT
)
{
return
r
;
}
}
return
FilterReply
.
NEUTRAL
;
}

Loop through the filters in the chain. 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 chain . 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 .


static public boolean isAndroidOS() {
    String osname = OptionHelper.getSystemProperty("os.name");
    String root = OptionHelper.getEnv("ANDROID_ROOT");
    String data = OptionHelper.getEnv("ANDROID_DATA");

    return osname != null && osname.contains("Linux") &&
        root != null && root.contains("/system") &&
        data != null && data.contains("/data");
  }

static public boolean isAndroidOS ( ) { String osname = OptionHelper . getSystemProperty ( "os.name" ) ; String root = OptionHelper . getEnv ( "ANDROID_ROOT" ) ; String data = OptionHelper . getEnv ( "ANDROID_DATA" ) ; return osname != null && osname . contains ( "Linux" ) && root != null && root . contains ( "/system" ) && data != null && data . contains ( "/data" ) ; }

Heuristically determines whether the current OS is Android


void init() {
    try {
      try {
        new ContextInitializer(defaultLoggerContext).autoConfig();
      } catch (JoranException je) {
        Util.report("Failed to auto configure default logger context", je);
      }
      // logback-292
      if(!StatusUtil.contextHasStatusListener(defaultLoggerContext)) {
        StatusPrinter.printInCaseOfErrorsOrWarnings(defaultLoggerContext);
      }
      contextSelectorBinder.init(defaultLoggerContext, KEY);
      initialized = true;
    } catch (Exception t) { // see LOGBACK-1159
      Util.report("Failed to instantiate [" + LoggerContext.class.getName()
          + "]", t);
    }
  }


public static File[] filesInFolderMatchingStemRegex(File file,
      final String stemRegex) {

    if (file == null) {
      return new File[0];
    }
    if (!file.exists() || !file.isDirectory()) {
      return new File[0];
    }
    return file.listFiles(new FilenameFilter() {
      public boolean accept(File dir, String name) {
        return name.matches(stemRegex);
      }
    });
  }

public static File [ ] filesInFolderMatchingStemRegex ( File file , final String stemRegex ) { if ( file == null ) { return new File [ 0 ] ; } if ( ! file . exists ( ) || ! file . isDirectory ( ) ) { return new File [ 0 ] ; } return file . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . matches ( stemRegex ) ; } } ) ; }

Return the set of files matching the stemRegex as found in 'directory'. A
stemRegex does not contain any slash characters or any folder separators.

@param file folder's file object
@param stemRegex regex file pattern to match
@return matching files

Return the set of files matching the stemRegex as found in directory . A stemRegex does not contain any slash characters or any folder separators .


private void retrospectivePrint() {
    if(context == null)
      return;
    long now = System.currentTimeMillis();
    StatusManager sm = context.getStatusManager();
    List<Status> statusList = sm.getCopyOfStatusList();
    for (Status status : statusList) {
      long timestampOfStatusMesage = status.getDate();
      if (isElapsedTimeLongerThanThreshold(now, timestampOfStatusMesage)) {
        print(status);
      }
    }
  }

private void retrospectivePrint ( ) { if ( context == null ) return ; long now = System . currentTimeMillis ( ) ; StatusManager sm = context . getStatusManager ( ) ; List < Status > statusList = sm . getCopyOfStatusList ( ) ; for ( Status status : statusList ) { long timestampOfStatusMesage = status . getDate ( ) ; if ( isElapsedTimeLongerThanThreshold ( now , timestampOfStatusMesage ) ) { print ( status ) ; } } }


static public int facilityStringToint(String facilityStr) {
    if ("KERN".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_KERN;
    } else if ("USER".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_USER;
    } else if ("MAIL".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_MAIL;
    } else if ("DAEMON".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_DAEMON;
    } else if ("AUTH".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_AUTH;
    } else if ("SYSLOG".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_SYSLOG;
    } else if ("LPR".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_LPR;
    } else if ("NEWS".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_NEWS;
    } else if ("UUCP".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_UUCP;
    } else if ("CRON".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_CRON;
    } else if ("AUTHPRIV".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_AUTHPRIV;
    } else if ("FTP".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_FTP;
    } else if ("NTP".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_NTP;
    } else if ("AUDIT".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_AUDIT;
    } else if ("ALERT".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_ALERT;
    } else if ("CLOCK".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_CLOCK;
    } else if ("LOCAL0".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_LOCAL0;
    } else if ("LOCAL1".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_LOCAL1;
    } else if ("LOCAL2".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_LOCAL2;
    } else if ("LOCAL3".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_LOCAL3;
    } else if ("LOCAL4".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_LOCAL4;
    } else if ("LOCAL5".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_LOCAL5;
    } else if ("LOCAL6".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_LOCAL6;
    } else if ("LOCAL7".equalsIgnoreCase(facilityStr)) {
      return SyslogConstants.LOG_LOCAL7;
    } else {
      throw new IllegalArgumentException(facilityStr
          + " is not a valid syslog facility string");
    }
  }

Returns the integer value corresponding to the named syslog facility.

@param facilityStr the syslog facility name
@return the syslog facility code
@throws IllegalArgumentException
if the facility string is not recognized

Returns the integer value corresponding to the named syslog facility .


public File getDatabaseFile(String filename) {
    File dbFile = null;
    if (filename != null && filename.trim().length() > 0) {
      dbFile = new File(filename);
    }
    if (dbFile == null || dbFile.isDirectory()) {
      dbFile = new File(new AndroidContextUtil().getDatabasePath("logback.db"));
    }
    return dbFile;
  }

public File getDatabaseFile ( String filename ) { File dbFile = null ; if ( filename != null && filename . trim ( ) . length ( ) > 0 ) { dbFile = new File ( filename ) ; } if ( dbFile == null || dbFile . isDirectory ( ) ) { dbFile = new File ( new AndroidContextUtil ( ) . getDatabasePath ( "logback.db" ) ) ; } return dbFile ; }

Gets a file object from a file path to a SQLite database
@param filename absolute path to database file
@return the file object if a valid file found; otherwise, null


private void clearExpiredLogs(SQLiteDatabase db) {
    if (lastCheckExpired(this.maxHistory, this.lastCleanupTime)) {
      this.lastCleanupTime = this.clock.currentTimeMillis();
      this.getLogCleaner().performLogCleanup(db, this.maxHistory);
    }
  }

private void clearExpiredLogs ( SQLiteDatabase db ) { if ( lastCheckExpired ( this . maxHistory , this . lastCleanupTime ) ) { this . lastCleanupTime = this . clock . currentTimeMillis ( ) ; this . getLogCleaner ( ) . performLogCleanup ( db , this . maxHistory ) ; } }

Removes expired logs from the database
@param db


private boolean lastCheckExpired(Duration expiry, long lastCleanupTime) {
    boolean isExpired = false;
    if (expiry != null && expiry.getMilliseconds() > 0) {
      final long now = this.clock.currentTimeMillis();
      final long timeDiff = now - lastCleanupTime;
      isExpired = (lastCleanupTime <= 0) || (timeDiff >= expiry.getMilliseconds());
    }
    return isExpired;
  }

private boolean lastCheckExpired ( Duration expiry , long lastCleanupTime ) { boolean isExpired = false ; if ( expiry != null && expiry . getMilliseconds ( ) > 0 ) { final long now = this . clock . currentTimeMillis ( ) ; final long timeDiff = now - lastCleanupTime ; isExpired = ( lastCleanupTime <= 0 ) || ( timeDiff >= expiry . getMilliseconds ( ) ) ; } return isExpired ; }

Determines whether it's time to clear expired logs
@param expiry max time duration between checks
@param lastCleanupTime timestamp (ms) of last cleanup
@return true if last check has expired

Determines whether it s time to clear expired logs


private long subAppend(ILoggingEvent event, SQLiteStatement insertStatement) throws SQLException {

    bindLoggingEvent(insertStatement, event);
    bindLoggingEventArguments(insertStatement, event.getArgumentArray());

    // This is expensive... should we do it every time?
    bindCallerData(insertStatement, event.getCallerData());

    long insertId = -1;
    try {
      insertId = insertStatement.executeInsert();
    } catch (SQLiteException e) {
      addWarn("Failed to insert loggingEvent", e);
    }
    return insertId;
  }

Inserts the main details of a log event into the database

@param event the event to insert
@param insertStatement the SQLite statement used to insert the event
@return the row ID of the newly inserted event; -1 if the insertion failed
@throws SQLException


private void secondarySubAppend(ILoggingEvent event, long eventId) throws SQLException {
    Map<String, String> mergedMap = mergePropertyMaps(event);
    insertProperties(mergedMap, eventId);

    if (event.getThrowableProxy() != null) {
      insertThrowable(event.getThrowableProxy(), eventId);
    }
  }

private void secondarySubAppend ( ILoggingEvent event , long eventId ) throws SQLException { Map < String , String > mergedMap = mergePropertyMaps ( event ) ; insertProperties ( mergedMap , eventId ) ; if ( event . getThrowableProxy ( ) != null ) { insertThrowable ( event . getThrowableProxy ( ) , eventId ) ; } }

Updates an existing row of an event with the secondary details of the event.
This includes MDC properties and any exception information.

@param event the event containing the details to insert
@param eventId the row ID of the event to modify
@throws SQLException

Updates an existing row of an event with the secondary details of the event . This includes MDC properties and any exception information .


private void bindLoggingEvent(SQLiteStatement stmt, ILoggingEvent event) throws SQLException {
    stmt.bindLong(TIMESTMP_INDEX, event.getTimeStamp());
    stmt.bindString(FORMATTED_MESSAGE_INDEX, event.getFormattedMessage());
    stmt.bindString(LOGGER_NAME_INDEX, event.getLoggerName());
    stmt.bindString(LEVEL_STRING_INDEX, event.getLevel().toString());
    stmt.bindString(THREAD_NAME_INDEX, event.getThreadName());
    stmt.bindLong(REFERENCE_FLAG_INDEX, computeReferenceMask(event));
  }

private void bindLoggingEvent ( SQLiteStatement stmt , ILoggingEvent event ) throws SQLException { stmt . bindLong ( TIMESTMP_INDEX , event . getTimeStamp ( ) ) ; stmt . bindString ( FORMATTED_MESSAGE_INDEX , event . getFormattedMessage ( ) ) ; stmt . bindString ( LOGGER_NAME_INDEX , event . getLoggerName ( ) ) ; stmt . bindString ( LEVEL_STRING_INDEX , event . getLevel ( ) . toString ( ) ) ; stmt . bindString ( THREAD_NAME_INDEX , event . getThreadName ( ) ) ; stmt . bindLong ( REFERENCE_FLAG_INDEX , computeReferenceMask ( event ) ) ; }

Binds the main details of a log event to a SQLite statement's parameters

@param stmt the SQLite statement to modify
@param event the event containing the details to bind
@throws SQLException

Binds the main details of a log event to a SQLite statement s parameters


private String asStringTruncatedTo254(Object o) {
    String s = null;
    if (o != null) {
      s = o.toString();
    }
    if (s != null && s.length() > 254) {
      s = s.substring(0, 254);
    }
    return s == null ? "" : s;
  }

private String asStringTruncatedTo254 ( Object o ) { String s = null ; if ( o != null ) { s = o . toString ( ) ; } if ( s != null && s . length ( ) > 254 ) { s = s . substring ( 0 , 254 ) ; } return s == null ? "" : s ; }

Gets the first 254 characters of an object's string representation. This is
used to truncate a logging event's argument binding if necessary.

@param o the object
@return up to 254 characters of the object's string representation; or empty
string if the object string is itself null

Gets the first 254 characters of an object s string representation . This is used to truncate a logging event s argument binding if necessary .


private static short computeReferenceMask(ILoggingEvent event) {
    short mask = 0;

    int mdcPropSize = 0;
    if (event.getMDCPropertyMap() != null) {
      mdcPropSize = event.getMDCPropertyMap().keySet().size();
    }
    int contextPropSize = 0;
    if (event.getLoggerContextVO().getPropertyMap() != null) {
      contextPropSize = event.getLoggerContextVO().getPropertyMap().size();
    }

    if (mdcPropSize > 0 || contextPropSize > 0) {
      mask = PROPERTIES_EXIST;
    }
    if (event.getThrowableProxy() != null) {
      mask |= EXCEPTION_EXISTS;
    }
    return mask;
  }

private static short computeReferenceMask ( ILoggingEvent event ) { short mask = 0 ; int mdcPropSize = 0 ; if ( event . getMDCPropertyMap ( ) != null ) { mdcPropSize = event . getMDCPropertyMap ( ) . keySet ( ) . size ( ) ; } int contextPropSize = 0 ; if ( event . getLoggerContextVO ( ) . getPropertyMap ( ) != null ) { contextPropSize = event . getLoggerContextVO ( ) . getPropertyMap ( ) . size ( ) ; } if ( mdcPropSize > 0 || contextPropSize > 0 ) { mask = PROPERTIES_EXIST ; } if ( event . getThrowableProxy ( ) != null ) { mask |= EXCEPTION_EXISTS ; } return mask ; }

Computes the reference mask for a logging event, including
flags to indicate whether MDC properties or exception info
is available for the event.

@param event the logging event to evaluate
@return the 16-bit reference mask

Computes the reference mask for a logging event including flags to indicate whether MDC properties or exception info is available for the event .


private Map<String, String> mergePropertyMaps(ILoggingEvent event) {
    Map<String, String> mergedMap = new HashMap<String, String>();
    // we add the context properties first, then the event properties, since
    // we consider that event-specific properties should have priority over
    // context-wide properties.
    Map<String, String> loggerContextMap = event.getLoggerContextVO().getPropertyMap();
    if (loggerContextMap != null) {
      mergedMap.putAll(loggerContextMap);
    }

    Map<String, String> mdcMap = event.getMDCPropertyMap();
    if (mdcMap != null) {
      mergedMap.putAll(mdcMap);
    }

    return mergedMap;
  }

Merges a log event's properties with the properties of the logger context.
The context properties are first in the map, and then the event's properties
are appended.

@param event the logging event to evaluate
@return the merged properties map

Merges a log event s properties with the properties of the logger context . The context properties are first in the map and then the event s properties are appended .


private void insertException(SQLiteStatement stmt, String txt, short i, long eventId) throws SQLException {
    stmt.bindLong(1, eventId);
    stmt.bindLong(2, i);
    stmt.bindString(3, txt);
    stmt.executeInsert();
  }

private void insertException ( SQLiteStatement stmt , String txt , short i , long eventId ) throws SQLException { stmt . bindLong ( 1 , eventId ) ; stmt . bindLong ( 2 , i ) ; stmt . bindString ( 3 , txt ) ; stmt . executeInsert ( ) ; }

Inserts an exception into the logging_exceptions table

@param stmt
@param txt
@param i
@param eventId


public int getPrefixMatchLength(ElementPath p) {
    if (p == null) {
      return 0;
    }

    int lSize = this.partList.size();
    int rSize = p.partList.size();

    // no match possible for empty sets
    if ((lSize == 0) || (rSize == 0)) {
      return 0;
    }

    int minLen = (lSize <= rSize) ? lSize : rSize;
    int match = 0;

    for (int i = 0; i < minLen; i++) {
      String l = this.partList.get(i);
      String r = p.partList.get(i);

      if (equalityCheck(l, r)) {
        match++;
      } else {
        break;
      }
    }

    return match;
  }

public
int
getPrefixMatchLength
(
ElementPath
p
)
{
if
(
p
==
)
{
return
0
;
}
int
lSize
=
this
.
partList
.
size
(
)
;
int
rSize
=
p
.
partList
.
size
(
)
;
// no match possible for empty sets
if
(
(
lSize
==
0
)
||
(
rSize
==
0
)
)
{
return
0
;
}
int
minLen
=
(
lSize
<=
rSize
)
lSize
:
rSize
;
int
match
=
0
;
for
(
int
i
=
0
;
i
<
minLen
;
i
++
)
{
String
l
=
this
.
partList
.
get
(
i
)
;
String
r
=
p
.
partList
.
get
(
i
)
;
if
(
equalityCheck
(
l
,
r
)
)
{
match
++
;
}
else
{
break
;
}
}
return
match
;
}

Returns the number of "prefix" components that this pattern has in common
with the pattern p passed as parameter. By "prefix" components we mean the
components at the beginning of the pattern.
@param p element path
@return the number of "prefix" components in common with p

Returns the number of prefix components that this pattern has in common with the pattern p passed as parameter . By prefix components we mean the components at the beginning of the pattern .


public synchronized int getEffectiveLevel() {
    int result = level;
    int effLevel;

    Iterator it = iterator();
    Status s;
    while (it.hasNext()) {
      s = (Status) it.next();
      effLevel = s.getEffectiveLevel();
      if (effLevel > result) {
        result = effLevel;
      }
    }
    return result;
  }

public synchronized int getEffectiveLevel ( ) { int result = level ; int effLevel ; Iterator it = iterator ( ) ; Status s ; while ( it . hasNext ( ) ) { s = ( Status ) it . next ( ) ; effLevel = s . getEffectiveLevel ( ) ; if ( effLevel > result ) { result = effLevel ; } } return result ; }

different status objects lying on the same cycle


public void setProperty(String name, String value) {
    if (value == null) {
      return;
    }

    name = Introspector.decapitalize(name);

    PropertyDescriptor prop = getPropertyDescriptor(name);

    if (prop == null) {
      addWarn("No such property [" + name + "] in " + objClass.getName() + ".");
    } else {
      try {
        setProperty(prop, name, value);
      } catch (PropertySetterException ex) {
        addWarn("Failed to set property [" + name + "] to value \"" + value
            + "\". ", ex);
      }
    }
  }

public
void
setProperty
(
String
name
,
String
value
)
{
if
(
value
==
)
{
return
;
}
name
=
Introspector
.
decapitalize
(
name
)
;
PropertyDescriptor
prop
=
getPropertyDescriptor
(
name
)
;
if
(
prop
==
)
{
addWarn
(
"No such property ["
+
name
+
"] in "
+
objClass
.
getName
(
)
+
"."
)
;
}
else
{
try
{
setProperty
(
prop
,
name
,
value
)
;
}
catch
(
PropertySetterException
ex
)
{
addWarn
(
"Failed to set property ["
+
name
+
"] to value \""
+
value
+
"\". "
,
ex
)
;
}
}
}

Set a property on this PropertySetter's Object. If successful, this method
will invoke a setter method on the underlying Object. The setter is the one
for the specified property name and the value is determined partly from the
setter argument type and partly from the value specified in the call to
this method.

<p>
If the setter expects a String no conversion is necessary. If it expects an
int, then an attempt is made to convert 'value' to an int using new
Integer(value). If the setter expects a boolean, the conversion is by new
Boolean(value).

@param name
name of the property
@param value
String value of the property

Set a property on this PropertySetter s Object . If successful this method will invoke a setter method on the underlying Object . The setter is the one for the specified property name and the value is determined partly from the setter argument type and partly from the value specified in the call to this method .


private boolean isUnequivocallyInstantiable(Class<?> clazz) {
    if (clazz.isInterface()) {
      return false;
    }
    // checking for constructors would be more elegant, but in
    // classes without any declared constructors, Class.getConstructor()
    // returns null.
    Object o;
    try {
      o = clazz.getDeclaredConstructor().newInstance();
      if (o != null) {
        return true;
      } else {
        return false;
      }
    } catch (InstantiationException e) {
      return false;
    } catch (IllegalAccessException e) {
      return false;
    } catch (NoSuchMethodException e) {
      return false;
    } catch (InvocationTargetException e) {
      return false;
    }
  }

Can the given clazz instantiable with certainty?

@param clazz
The class to test for instantiability
@return true if clazz can be instantiated, and false otherwise.


@Override
  protected HashMap<String, String> childValue(
      HashMap<String, String> parentValue) {
    if (parentValue == null) {
      return null;
    } else {
      return new HashMap<String, String>(parentValue);
    }
  }

@ Override protected HashMap < String , String > childValue ( HashMap < String , String > parentValue ) { if ( parentValue == null ) { return null ; } else { return new HashMap < String , String > ( parentValue ) ; } }

Child threads should get a copy of the parent's hashmap.

Child threads should get a copy of the parent s hashmap .


@Override
  protected void processInclude(InterpretationContext ic, URL url) throws JoranException {

    InputStream in = openURL(url);

    try {
      if (in != null) {
        // add URL to watch list in case the "scan" flag is true, in
        // which case this URL is periodically checked for changes
        ConfigurationWatchListUtil.addToWatchList(getContext(), url);

        // parse the include
        SaxEventRecorder recorder = createRecorder(in, url);
        recorder.setContext(getContext());
        recorder.recordEvents(in);

        // remove the leading/trailing tags (<included> or <configuration>)
        trimHeadAndTail(recorder);

        ic.getJoranInterpreter().getEventPlayer().addEventsDynamically(recorder.getSaxEventList(), this.eventOffset);
      }
    } catch (JoranException e) {
      optionalWarning("Failed processing [" + url.toString() + "]", e);
    } finally {
      close(in);
    }
  }

Processes an include
@param ic context
@param url URL to file/resource being included


private InputStream openURL(URL url) {
    try {
      return url.openStream();
    } catch (IOException e) {
      optionalWarning("Failed to open [" + url.toString() + "]", e);
      return null;
    }
  }

private
InputStream
openURL
(
URL
url
)
{
try
{
return
url
.
openStream
(
)
;
}
catch
(
IOException
e
)
{
optionalWarning
(
"Failed to open ["
+
url
.
toString
(
)
+
"]"
,
e
)
;
return
;
}
}

Opens the given URL, logging any exceptions
@param url URL of file/resource to open
@return an input stream to the URL; or {@code null} if the URL could not be opened

Opens the given URL logging any exceptions


private void trimHeadAndTail(SaxEventRecorder recorder) {
    List<SaxEvent> saxEventList = recorder.getSaxEventList();
    if (saxEventList.size() == 0) {
      return;
    }

    boolean includedTagFound = false;
    boolean configTagFound = false;

    // find opening element
    SaxEvent first = saxEventList.get(0);
    if (first != null) {
      String elemName = getEventName(first);
      includedTagFound = INCLUDED_TAG.equalsIgnoreCase(elemName);
      configTagFound = CONFIG_TAG.equalsIgnoreCase(elemName);
    }

    // if opening element found, remove it, and then remove the closing element
    if (includedTagFound || configTagFound) {
      saxEventList.remove(0);

      final int listSize = saxEventList.size();
      if (listSize == 0) {
        return;
      }

      final int lastIndex = listSize - 1;
      SaxEvent last = saxEventList.get(lastIndex);

      if (last != null) {
        String elemName = getEventName(last);
        if ((includedTagFound && INCLUDED_TAG.equalsIgnoreCase(elemName)) ||
          (configTagFound && CONFIG_TAG.equalsIgnoreCase(elemName))) {

          saxEventList.remove(lastIndex);
        }
      }
    }
  }

Removes the head tag and tail tag if they are named either
"included" or "configuration"
@param recorder the SAX Event recorder containing the tags

Removes the head tag and tail tag if they are named either included or configuration


protected boolean shouldStart() {
    ServerSocket serverSocket = null;
    try {
      serverSocket = getServerSocketFactory().createServerSocket(
          getPort(), getBacklog(), getInetAddress());

      ServerListener<RemoteAppenderClient> listener =
          createServerListener(serverSocket);

      runner = createServerRunner(listener, getContext().getScheduledExecutorService());
      runner.setContext(getContext());
      return true;
    }
    catch (Exception ex) {
      addError("server startup error: " + ex, ex);
      CloseUtil.closeQuietly(serverSocket);
      return false;
    }
  }

protected
boolean
shouldStart
(
)
{
ServerSocket
serverSocket
=
;
try
{
serverSocket
=
getServerSocketFactory
(
)
.
createServerSocket
(
getPort
(
)
,
getBacklog
(
)
,
getInetAddress
(
)
)
;
ServerListener
<
RemoteAppenderClient
>
listener
=
createServerListener
(
serverSocket
)
;
runner
=
createServerRunner
(
listener
,
getContext
(
)
.
getScheduledExecutorService
(
)
)
;
runner
.
setContext
(
getContext
(
)
)
;
return
true
;
}
catch
(
Exception
ex
)
{
addError
(
"server startup error: "
+
ex
,
ex
)
;
CloseUtil
.
closeQuietly
(
serverSocket
)
;
return
false
;
}
}


public boolean isTransient() {
        Throwable cause = getCause();
        if (cause == null) {
            return isServerError(statusCode);
        } else if (cause instanceof AlgoliaException) {
            return ((AlgoliaException)cause).isTransient();
        } else if (cause instanceof IOException) {
            return true;
        } else {
            return false;
        }
    }

public boolean isTransient ( ) { Throwable cause = getCause ( ) ; if ( cause == null ) { return isServerError ( statusCode ) ; } else if ( cause instanceof AlgoliaException ) { return ( ( AlgoliaException ) cause ) . isTransient ( ) ; } else if ( cause instanceof IOException ) { return true ; } else { return false ; } }

Test whether this error is transient.

@return true if transient, false if fatal.


private void setDefaultHosts() {
        List<String> fallbackHosts = Arrays.asList(
                "places-1.algolianet.com",
                "places-2.algolianet.com",
                "places-3.algolianet.com"
        );
        Collections.shuffle(fallbackHosts);

        List<String> hosts = new ArrayList<>(fallbackHosts.size() + 1);
        hosts.add("places-dsn.algolia.net");
        hosts.addAll(fallbackHosts);
        String[] hostsArray = hosts.toArray(new String[hosts.size()]);

        setReadHosts(hostsArray);
        setWriteHosts(hostsArray);
    }

private void setDefaultHosts ( ) { List < String > fallbackHosts = Arrays . asList ( "places-1.algolianet.com" , "places-2.algolianet.com" , "places-3.algolianet.com" ) ; Collections . shuffle ( fallbackHosts ) ; List < String > hosts = new ArrayList <> ( fallbackHosts . size ( ) + 1 ) ; hosts . add ( "places-dsn.algolia.net" ) ; hosts . addAll ( fallbackHosts ) ; String [ ] hostsArray = hosts . toArray ( new String [ hosts . size ( ) ] ) ; setReadHosts ( hostsArray ) ; setWriteHosts ( hostsArray ) ; }

Set the default hosts for Algolia Places.

Set the default hosts for Algolia Places .


private synchronized void ensureLocalIndex()
    {
        if (localIndex == null) {
            localIndex = new LocalIndex(getClient().getRootDataDir().getAbsolutePath(), getClient().getApplicationID(), getRawIndexName());
        }
    }

private synchronized void ensureLocalIndex ( ) { if ( localIndex == null ) { localIndex = new LocalIndex ( getClient ( ) . getRootDataDir ( ) . getAbsolutePath ( ) , getClient ( ) . getApplicationID ( ) , getRawIndexName ( ) ) ; } }


public void sync()
    {
        if (getDataSelectionQueries().length == 0) {
            throw new IllegalStateException("Cannot sync with empty data selection queries");
        }
        synchronized (this) {
            if (syncing)
                return;
            syncing = true;
        }
        getClient().localBuildExecutorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
                _sync();
            }
        });
    }

Launch a sync.
If a sync is already running, this call is ignored. Otherwise, the sync is enqueued and runs in the background.

NOTE: All index syncs are sequential: no two syncs can run at the same time.

@throws IllegalStateException If no data selection queries were set.

Launch a sync . If a sync is already running this call is ignored . Otherwise the sync is enqueued and runs in the background .


public void syncIfNeeded()
    {
        long currentDate = System.currentTimeMillis();
        if (currentDate - mirrorSettings.getLastSyncDate().getTime() > delayBetweenSyncs || mirrorSettings.getQueriesModificationDate().compareTo(mirrorSettings.getLastSyncDate()) > 0) {
            sync();
        }
    }

public void syncIfNeeded ( ) { long currentDate = System . currentTimeMillis ( ) ; if ( currentDate - mirrorSettings . getLastSyncDate ( ) . getTime ( ) > delayBetweenSyncs || mirrorSettings . getQueriesModificationDate ( ) . compareTo ( mirrorSettings . getLastSyncDate ( ) ) > 0 ) { sync ( ) ; } }

Launch a sync only if the data is obsolete.
The data is obsolete if the last successful sync is older than the delay between syncs, or if the data selection
queries have been changed in the meantime.

@throws IllegalStateException If no data selection queries were set.

Launch a sync only if the data is obsolete . The data is obsolete if the last successful sync is older than the delay between syncs or if the data selection queries have been changed in the meantime .


public JSONObject waitTask(String taskID, long timeToWait) throws AlgoliaException {
        try {
            while (true) {
                JSONObject obj = client.getRequest("/1/indexes/" + encodedIndexName + "/task/" + URLEncoder.encode(taskID, "UTF-8"), /* urlParameters: */ null, false, /* requestOptions: */ null);
                if (obj.getString("status").equals("published")) {
                    return obj;
                }
                try {
                    Thread.sleep(timeToWait >= MAX_TIME_MS_TO_WAIT ? MAX_TIME_MS_TO_WAIT : timeToWait);
                } catch (InterruptedException e) {
                    continue;
                }

                final long newTimeout = timeToWait * 2;
                timeToWait = (newTimeout <= 0 || newTimeout >= MAX_TIME_MS_TO_WAIT) ? MAX_TIME_MS_TO_WAIT : newTimeout;
            }
        } catch (JSONException e) {
            throw new AlgoliaException(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

public
JSONObject
waitTask
(
String
taskID
,
long
timeToWait
)
throws
AlgoliaException
{
try
{
while
(
true
)
{
JSONObject
obj
=
client
.
getRequest
(
"/1/indexes/"
+
encodedIndexName
+
"/task/"
+
URLEncoder
.
encode
(
taskID
,
"UTF-8"
)
,
/* urlParameters: */
,
false
,
/* requestOptions: */
)
;
if
(
obj
.
getString
(
"status"
)
.
equals
(
"published"
)
)
{
return
obj
;
}
try
{
Thread
.
sleep
(
timeToWait
>=
MAX_TIME_MS_TO_WAIT
MAX_TIME_MS_TO_WAIT
:
timeToWait
)
;
}
catch
(
InterruptedException
e
)
{
continue
;
}
final
long
newTimeout
=
timeToWait
*
2
;
timeToWait
=
(
newTimeout
<=
0
||
newTimeout
>=
MAX_TIME_MS_TO_WAIT
)
MAX_TIME_MS_TO_WAIT
:
newTimeout
;
}
}
catch
(
JSONException
e
)
{
throw
new
AlgoliaException
(
e
.
getMessage
(
)
)
;
}
catch
(
UnsupportedEncodingException
e
)
{
throw
new
RuntimeException
(
e
)
;
}
}

Wait the publication of a task on the server.
All server task are asynchronous and you can check with this method that the task is published.

@param taskID     the id of the task returned by server
@param timeToWait time to sleep seed
@throws AlgoliaException

Wait the publication of a task on the server . All server task are asynchronous and you can check with this method that the task is published .


private JSONObject listIndexesOfflineSync() throws AlgoliaException {
        try {
            final String rootDataPath = getRootDataDir().getAbsolutePath();
            final File appDir = getAppDir();
            final File[] directories = appDir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    return pathname.isDirectory();
                }
            });
            JSONObject response = new JSONObject();
            JSONArray items = new JSONArray();
            if (directories != null) {
                for (File directory : directories) {
                    final String name = directory.getName();
                    if (hasOfflineData(name)) {
                        items.put(new JSONObject()
                            .put("name", name)
                        );
                        // TODO: Do we need other data as in the online API?
                    }
                }
            }
            response.put("items", items);
            return response;
        } catch (JSONException e) {
            throw new RuntimeException(e); // should never happen
        }
    }

List existing offline indices.

**Note:** This applies both to {@link MirroredIndex} and {@link OfflineIndex} instances. Only indices that
*actually exist* on disk are listed. If an instance was created but never synced or written to, it will not
appear in the list.

@return A JSON object with an `items` attribute containing the indices details as JSON objects.


private static String _toCharArray(InputStream stream) throws IOException {
        InputStreamReader is = new InputStreamReader(stream, "UTF-8");
        StringBuilder builder = new StringBuilder();
        char[] buf = new char[1000];
        int l = 0;
        while (l >= 0) {
            builder.append(buf, 0, l);
            l = is.read(buf);
        }
        is.close();
        return builder.toString();
    }

private static String _toCharArray ( InputStream stream ) throws IOException { InputStreamReader is = new InputStreamReader ( stream , "UTF-8" ) ; StringBuilder builder = new StringBuilder ( ) ; char [ ] buf = new char [ 1000 ] ; int l = 0 ; while ( l >= 0 ) { builder . append ( buf , 0 , l ) ; l = is . read ( buf ) ; } is . close ( ) ; return builder . toString ( ) ; }

Reads the InputStream as UTF-8

@param stream the InputStream to read
@return the stream's content as a String
@throws IOException if the stream can't be read, decoded as UTF-8 or closed


private static byte[] _toByteArray(InputStream stream) throws AlgoliaException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int read;
        byte[] buffer = new byte[1024];

        try {
            while ((read = stream.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, read);
            }

            out.flush();
            return out.toByteArray();
        } catch (IOException e) {
            throw new AlgoliaException("Error while reading stream: " + e.getMessage());
        }
    }

private
static
byte
[
]
_toByteArray
(
InputStream
stream
)
throws
AlgoliaException
{
ByteArrayOutputStream
out
=
new
ByteArrayOutputStream
(
)
;
int
read
;
byte
[
]
buffer
=
new
byte
[
1024
]
;
try
{
while
(
(
read
=
stream
.
read
(
buffer
,
0
,
buffer
.
length
)
)
!=
1
)
{
out
.
write
(
buffer
,
0
,
read
)
;
}
out
.
flush
(
)
;
return
out
.
toByteArray
(
)
;
}
catch
(
IOException
e
)
{
throw
new
AlgoliaException
(
"Error while reading stream: "
+
e
.
getMessage
(
)
)
;
}
}

Reads the InputStream into a byte array

@param stream the InputStream to read
@return the stream's content as a byte[]
@throws AlgoliaException if the stream can't be read or flushed


private static void consumeQuietly(final HttpURLConnection connection) {
        try {
            int read = 0;
            while (read != -1) {
                read = connection.getInputStream().read();
            }
            connection.getInputStream().close();
            read = 0;
            while (read != -1) {
                read = connection.getErrorStream().read();
            }
            connection.getErrorStream().close();
            connection.disconnect();
        } catch (IOException e) {
            // no inputStream to close
        }
    }

private
static
void
consumeQuietly
(
final
HttpURLConnection
connection
)
{
try
{
int
read
=
0
;
while
(
read
!=
1
)
{
read
=
connection
.
getInputStream
(
)
.
read
(
)
;
}
connection
.
getInputStream
(
)
.
close
(
)
;
read
=
0
;
while
(
read
!=
1
)
{
read
=
connection
.
getErrorStream
(
)
.
read
(
)
;
}
connection
.
getErrorStream
(
)
.
close
(
)
;
connection
.
disconnect
(
)
;
}
catch
(
IOException
e
)
{
// no inputStream to close
}
}

Ensures that the entity content is fully consumed and the content stream, if exists,
is closed.

Ensures that the entity content is fully consumed and the content stream if exists is closed .


private List<String> hostsThatAreUp(List<String> hosts) {
        List<String> upHosts = new ArrayList<>();
        for (String host : hosts) {
            if (isUpOrCouldBeRetried(host)) {
                upHosts.add(host);
            }
        }
        return upHosts.isEmpty() ? hosts : upHosts;
    }

private List < String > hostsThatAreUp ( List < String > hosts ) { List < String > upHosts = new ArrayList <> ( ) ; for ( String host : hosts ) { if ( isUpOrCouldBeRetried ( host ) ) { upHosts . add ( host ) ; } } return upHosts . isEmpty ( ) ? hosts : upHosts ; }

Get the hosts that are not considered down in a given list.

@param hosts a list of hosts whose {@link HostStatus} will be checked.
@return the hosts considered up, or all hosts if none is known to be reachable.

Get the hosts that are not considered down in a given list .


public @NonNull PlacesQuery setType(Type type) {
        if (type == null) {
            set(KEY_TYPE, null);
        } else {
            switch (type) {
                case CITY:
                    set(KEY_TYPE, "city");
                    break;
                case COUNTRY:
                    set(KEY_TYPE, "country");
                    break;
                case ADDRESS:
                    set(KEY_TYPE, "address");
                    break;
                case BUS_STOP:
                    set(KEY_TYPE, "busStop");
                    break;
                case TRAIN_STATION:
                    set(KEY_TYPE, "trainStation");
                    break;
                case TOWN_HALL:
                    set(KEY_TYPE, "townhall");
                    break;
                case AIRPORT:
                    set(KEY_TYPE, "airport");
                    break;
            }
        }
        return this;
    }

public @ NonNull PlacesQuery setType ( Type type ) { if ( type == null ) { set ( KEY_TYPE , null ) ; } else { switch ( type ) { case CITY : set ( KEY_TYPE , "city" ) ; break ; case COUNTRY : set ( KEY_TYPE , "country" ) ; break ; case ADDRESS : set ( KEY_TYPE , "address" ) ; break ; case BUS_STOP : set ( KEY_TYPE , "busStop" ) ; break ; case TRAIN_STATION : set ( KEY_TYPE , "trainStation" ) ; break ; case TOWN_HALL : set ( KEY_TYPE , "townhall" ) ; break ; case AIRPORT : set ( KEY_TYPE , "airport" ) ; break ; } } return this ; }

Set the type of place to search for.

@param type Type of place to search for.


public void start() {
        if (started) {
            throw new IllegalStateException();
        }
        started = true;
        request = index.browseAsync(query, requestOptions, completionHandler);
    }

public void start ( ) { if ( started ) { throw new IllegalStateException ( ) ; } started = true ; request = index . browseAsync ( query , requestOptions , completionHandler ) ; }


public V put(K key, V value) {
        V previous = null;

        synchronized (this) {
            long timeout = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(expirationTimeout, expirationTimeUnit);
            final Pair<V, Long> previousPair = lruCache.put(key, new Pair<>(value, timeout));
            if (previousPair != null) {
                previous = previousPair.first;
            }
        }
        return previous;
    }

public V put ( K key , V value ) { V previous = null ; synchronized ( this ) { long timeout = System . currentTimeMillis ( ) + TimeUnit . MILLISECONDS . convert ( expirationTimeout , expirationTimeUnit ) ; final Pair < V , Long > previousPair = lruCache . put ( key , new Pair <> ( value , timeout ) ) ; if ( previousPair != null ) { previous = previousPair . first ; } } return previous ; }

Puts a value in the cache, computing an expiration time

@return the previous value for this key, if any

Puts a value in the cache computing an expiration time


synchronized public V get(K key) {
        final Pair<V, Long> cachePair = lruCache.get(key);
        if (cachePair != null && cachePair.first != null) {
            if (cachePair.second > System.currentTimeMillis()) {
                return cachePair.first;
            } else {
                lruCache.remove(key);
            }
        }
        return null;
    }

synchronized public V get ( K key ) { final Pair < V , Long > cachePair = lruCache . get ( key ) ; if ( cachePair != null && cachePair . first != null ) { if ( cachePair . second > System . currentTimeMillis ( ) ) { return cachePair . first ; } else { lruCache . remove ( key ) ; } } return null ; }

Get a value from the cache

@return the cached value if it is still valid, else null.


public void awaitCompletion() {
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                throw rethrow(e);
            }
        }
        if (caughtException != null) {
            throw rethrow(caughtException);
        }
    }

public void awaitCompletion ( ) { for ( Thread thread : threads ) { try { thread . join ( ) ; } catch ( InterruptedException e ) { throw rethrow ( e ) ; } } if ( caughtException != null ) { throw rethrow ( caughtException ) ; } }

Waits for all threads to finish.

If {@link #throwException} is true this method will throw the first occurred exception of a thread.


public static int versionCompare(String firstVersionString, String secondVersionString) {
        String[] firstVersion = parseVersionString(firstVersionString);
        String[] secondVersion = parseVersionString(secondVersionString);

        int i = 0;
        // set index to first non-equal ordinal or length of shortest version string
        while (i < firstVersion.length && i < secondVersion.length && firstVersion[i].equals(secondVersion[i])) {
            i++;
        }
        if (i < firstVersion.length && i < secondVersion.length) {
            // compare first non-equal ordinal number
            int diff = Integer.valueOf(firstVersion[i]).compareTo(Integer.valueOf(secondVersion[i]));
            return Integer.signum(diff);
        } else {
            // the strings are equal or one string is a substring of the other
            // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4"
            return Integer.signum(firstVersion.length - secondVersion.length);
        }
    }

Compares two version strings.

Use this instead of String.compareTo() for a non-lexicographical comparison that works for version strings,
e.g. versionCompare("1.10", "1.6").

Warning:
- It does not work if "1.10" is supposed to be equal to "1.10.0".
- Everything after a "-" is ignored.

@param firstVersionString  a string of ordinal numbers separated by decimal points.
@param secondVersionString a string of ordinal numbers separated by decimal points.
@return The result is a negative integer if firstVersionString is _numerically_ less than secondVersionString.
The result is a positive integer if firstVersionString is _numerically_ greater than secondVersionString.
The result is zero if the strings are _numerically_ equal.


public static void report(String testId, Throwable cause) {
        if (cause == null) {
            LOGGER.fatal("Can't call report with a null exception");
            return;
        }

        long exceptionCount = FAILURE_ID.incrementAndGet();

        if (exceptionCount > MAX_EXCEPTION_COUNT) {
            LOGGER.warn("Exception #" + exceptionCount + " detected. The maximum number of exceptions has been exceeded, so it"
                    + " won't be reported to the Agent.", cause);
            return;
        }

        LOGGER.warn("Exception #" + exceptionCount + " detected", cause);

        String targetFileName = exceptionCount + ".exception";

        File dir = getUserDir();
        File tmpFile = new File(dir, targetFileName + ".tmp");
        try {
            if (!tmpFile.createNewFile()) {
                throw new IOException("Could not create tmp file: " + tmpFile.getAbsolutePath());
            }
        } catch (IOException e) {
            LOGGER.fatal("Could not report exception; this means that this exception is not visible to the coordinator", e);
            return;
        }

        writeText(testId + NEW_LINE + throwableToString(cause), tmpFile);

        File file = new File(dir, targetFileName);
        LOGGER.info(file.getAbsolutePath());
        rename(tmpFile, file);
    }

Writes the cause to file.

@param testId the id of the test that caused the exception. Is allowed to be <tt>null</tt> if it is not known which test
caused the problem.
@param cause  the Throwable that should be reported.


public static void copyDirectory(File src, File target) {
        checkNotNull(src, "src can't be null");
        checkNotNull(target, "target can't be null");

        File[] files = src.listFiles();
        if (files == null) {
            return;
        }

        for (File srcFile : files) {
            if (srcFile.isDirectory()) {
                File targetChild = new File(target, srcFile.getName());
                ensureExistingDirectory(targetChild);
                copyDirectory(srcFile, targetChild);
            } else {
                copyFileToDirectory(srcFile, target);
            }
        }
    }

public
static
void
copyDirectory
(
File
src
,
File
target
)
{
checkNotNull
(
src
,
"src can't be null"
)
;
checkNotNull
(
target
,
"target can't be null"
)
;
File
[
]
files
=
src
.
listFiles
(
)
;
if
(
files
==
)
{
return
;
}
for
(
File
srcFile
:
files
)
{
if
(
srcFile
.
isDirectory
(
)
)
{
File
targetChild
=
new
File
(
target
,
srcFile
.
getName
(
)
)
;
ensureExistingDirectory
(
targetChild
)
;
copyDirectory
(
srcFile
,
targetChild
)
;
}
else
{
copyFileToDirectory
(
srcFile
,
target
)
;
}
}
}

Copies a directory recursively.

@param src    the src directory
@param target the target directory


public SimulatorProperties init(File file) {
        if (file == null) {
            // if no file is explicitly given, we look in the working directory
            file = new File(getUserDir(), PROPERTIES_FILE_NAME);
            if (!file.exists()) {
                LOGGER.info(format("Found no %s in working directory, relying on default properties", PROPERTIES_FILE_NAME));
                return null;
            }
        }

        LOGGER.info(format("Loading additional %s: %s", PROPERTIES_FILE_NAME, file.getAbsolutePath()));
        check(file);
        load(file, false);
        return this;
    }

Initializes the SimulatorProperties with additional properties.

@param file the file to load the properties from. If {@code null}, the {@value #PROPERTIES_FILE_NAME} file in the working
directory is tried.
@return this
@throws CommandLineExitException if the given file does not exist. If file is {@code null} no exception will be thrown,
even if the {@value #PROPERTIES_FILE_NAME} file in the working directory cannot be found.

Initializes the SimulatorProperties with additional properties .


public static <E> E getStaticFieldValue(Class clazz, String fieldName, Class fieldType) {
        Field field = getField(clazz, fieldName, fieldType);
        if (field == null) {
            throw new ReflectionException(format("Field %s.%s is not found", clazz.getName(), fieldName));
        }

        field.setAccessible(true);
        return getFieldValue0(null, field, clazz.getName(), fieldName);
    }

public
static
<
E
>
E
getStaticFieldValue
(
Class
clazz
,
String
fieldName
,
Class
fieldType
)
{
Field
field
=
getField
(
clazz
,
fieldName
,
fieldType
)
;
if
(
field
==
)
{
throw
new
ReflectionException
(
format
(
"Field %s.%s is not found"
,
clazz
.
getName
(
)
,
fieldName
)
)
;
}
field
.
setAccessible
(
true
)
;
return
getFieldValue0
(
,
field
,
clazz
.
getName
(
)
,
fieldName
)
;
}

Gets the value for a static field.

@param clazz     class which contains the field
@param fieldName name of the field
@param fieldType type of the field
@param <E>       type of the field
@return the value of the static field


public static Method getMethodByName(Class clazz, String methodName) {
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.getName().equals(methodName)) {
                return method;
            }
        }
        return null;
    }

public static Method getMethodByName ( Class clazz , String methodName ) { for ( Method method : clazz . getDeclaredMethods ( ) ) { if ( method . getName ( ) . equals ( methodName ) ) { return method ; } } return null ; }

Searches a method by name.

@param clazz      Class to scan
@param methodName Name of the method
@return the found method or <tt>null</tt> if no method was found


public static String formatPercentage(long value, long baseValue) {
        double percentage = (baseValue > 0 ? (ONE_HUNDRED * value) / baseValue : 0);
        return formatDouble(percentage, PERCENTAGE_FORMAT_LENGTH);
    }

public static String formatPercentage ( long value , long baseValue ) { double percentage = ( baseValue > 0 ? ( ONE_HUNDRED * value ) / baseValue : 0 ) ; return formatDouble ( percentage , PERCENTAGE_FORMAT_LENGTH ) ; }

Formats a percentage of two numbers and adds padding to the left.

@param value     the value of the percentage
@param baseValue the base value of the percentage
@return the formatted percentage

Formats a percentage of two numbers and adds padding to the left .


public static String formatDouble(double number, int length) {
        return padLeft(format(Locale.US, "%,.2f", number), length);
    }

public static String formatDouble ( double number , int length ) { return padLeft ( format ( Locale . US , "%,.2f" , number ) , length ) ; }

Formats a double number and adds padding to the left.

Very inefficient implementation, but a lot easier than to deal with the formatting API.

@param number number to format
@param length width of padding
@return formatted number

Formats a double number and adds padding to the left .


public static String formatLong(long number, int length) {
        return padLeft(format(Locale.US, "%,d", number), length);
    }

public static String formatLong ( long number , int length ) { return padLeft ( format ( Locale . US , "%,d" , number ) , length ) ; }

Formats a long number and adds padding to the left.

Very inefficient implementation, but a lot easier than to deal with the formatting API.

@param number number to format
@param length width of padding
@return formatted number

Formats a long number and adds padding to the left .


protected void readJsonSyntaxChar(byte[] b) throws IOException {
        byte ch = reader.read();
        if (ch != b[0]) {
            throw new ProtocolException("Unexpected character:" + (char) ch);
        }
    }

protected
void
readJsonSyntaxChar
(
byte
[
]
b
)
throws
IOException
{
byte
ch
=
reader
.
read
(
)
;
if
(
ch
!=
b
[
0
]
)
{
throw
new
ProtocolException
(
"Unexpected character:"
+
(
char
)
ch
)
;
}
}


private static byte hexVal(byte ch) throws IOException {
        if ((ch >= '0') && (ch <= '9')) {
            return (byte) ((char) ch - '0');
        } else if ((ch >= 'a') && (ch <= 'f')) {
            return (byte) ((char) ch - 'a' + 10);
        } else {
            throw new ProtocolException("Expected hex character");
        }
    }

private
static
byte
hexVal
(
byte
ch
)
throws
IOException
{
if
(
(
ch
>=
'
'
)
&&
(
ch
<=
'
'
)
)
{
return
(
byte
)
(
(
char
)
ch
'
'
)
;
}
else
if
(
(
ch
>=
'
'
)
&&
(
ch
<=
'
'
)
)
{
return
(
byte
)
(
(
char
)
ch
'
'
+
10
)
;
}
else
{
throw
new
ProtocolException
(
"Expected hex character"
)
;
}
}


private void writeJsonString(byte[] b) throws IOException {
        context.write();
        transport.write(QUOTE);
        int len = b.length;
        for (int i = 0; i < len; i++) {
            if ((b[i] & 0x00FF) >= 0x30) {
                if (b[i] == BACKSLASH[0]) {
                    transport.write(BACKSLASH);
                    transport.write(BACKSLASH);
                } else {
                    transport.write(b, i, 1);
                }
            } else {
                tmpbuf[0] = JSON_CHAR_TABLE[b[i]];
                if (tmpbuf[0] == 1) {
                    transport.write(b, i, 1);
                } else if (tmpbuf[0] > 1) {
                    transport.write(BACKSLASH);
                    transport.write(tmpbuf, 0, 1);
                } else {
                    transport.write(ESCSEQ);
                    tmpbuf[0] = hexChar((byte) (b[i] >> 4));
                    tmpbuf[1] = hexChar(b[i]);
                    transport.write(tmpbuf, 0, 2);
                }
            }
        }
        transport.write(QUOTE);
    }

private void writeJsonString ( byte [ ] b ) throws IOException { context . write ( ) ; transport . write ( QUOTE ) ; int len = b . length ; for ( int i = 0 ; i < len ; i ++ ) { if ( ( b [ i ] & 0x00FF ) >= 0x30 ) { if ( b [ i ] == BACKSLASH [ 0 ] ) { transport . write ( BACKSLASH ) ; transport . write ( BACKSLASH ) ; } else { transport . write ( b , i , 1 ) ; } } else { tmpbuf [ 0 ] = JSON_CHAR_TABLE [ b [ i ] ] ; if ( tmpbuf [ 0 ] == 1 ) { transport . write ( b , i , 1 ) ; } else if ( tmpbuf [ 0 ] > 1 ) { transport . write ( BACKSLASH ) ; transport . write ( tmpbuf , 0 , 1 ) ; } else { transport . write ( ESCSEQ ) ; tmpbuf [ 0 ] = hexChar ( ( byte ) ( b [ i ] >> 4 ) ) ; tmpbuf [ 1 ] = hexChar ( b [ i ] ) ; transport . write ( tmpbuf , 0 , 2 ) ; } } } transport . write ( QUOTE ) ; }

Write the bytes in array buf as a Json characters, escaping as needed

Write the bytes in array buf as a Json characters escaping as needed


private void writeJsonInteger(long num) throws IOException {
        context.write();
        String str = Long.toString(num);
        boolean escapeNum = context.escapeNum();
        if (escapeNum) {
            transport.write(QUOTE);
        }
        try {
            byte[] buf = str.getBytes("UTF-8");
            transport.write(buf);
        } catch (UnsupportedEncodingException e) {
            throw new AssertionError(e);
        }
        if (escapeNum) {
            transport.write(QUOTE);
        }
    }

private void writeJsonInteger ( long num ) throws IOException { context . write ( ) ; String str = Long . toString ( num ) ; boolean escapeNum = context . escapeNum ( ) ; if ( escapeNum ) { transport . write ( QUOTE ) ; } try { byte [ ] buf = str . getBytes ( "UTF-8" ) ; transport . write ( buf ) ; } catch ( UnsupportedEncodingException e ) { throw new AssertionError ( e ) ; } if ( escapeNum ) { transport . write ( QUOTE ) ; } }

wrapped in quotes to output as a Json string.

wrapped in quotes to output as a Json string .


private void writeJsonDouble(double num) throws IOException {
        context.write();
        String str = Double.toString(num);
        boolean special = false;
        switch (str.charAt(0)) {
            case 'N': // NaN
            case 'I': // Infinity
                special = true;
                break;
            case '-':
                if (str.charAt(1) == 'I') { // -Infinity
                    special = true;
                }
                break;
            default:
                break;
        }

        boolean escapeNum = special || context.escapeNum();
        if (escapeNum) {
            transport.write(QUOTE);
        }
        try {
            byte[] b = str.getBytes("UTF-8");
            transport.write(b, 0, b.length);
        } catch (UnsupportedEncodingException e) {
            throw new AssertionError(e);
        }
        if (escapeNum) {
            transport.write(QUOTE);
        }
    }

private
void
writeJsonDouble
(
double
num
)
throws
IOException
{
context
.
write
(
)
;
String
str
=
Double
.
toString
(
num
)
;
boolean
special
=
false
;
switch
(
str
.
charAt
(
0
)
)
{
case
'
'
:
// NaN
case
'
'
:
// Infinity
special
=
true
;
break
;
case
'
'
:
if
(
str
.
charAt
(
1
)
==
'
'
)
{
// -Infinity
special
=
true
;
}
break
;
default
:
break
;
}
boolean
escapeNum
=
special
||
context
.
escapeNum
(
)
;
if
(
escapeNum
)
{
transport
.
write
(
QUOTE
)
;
}
try
{
byte
[
]
b
=
str
.
getBytes
(
"UTF-8"
)
;
transport
.
write
(
b
,
0
,
b
.
length
)
;
}
catch
(
UnsupportedEncodingException
e
)
{
throw
new
AssertionError
(
e
)
;
}
if
(
escapeNum
)
{
transport
.
write
(
QUOTE
)
;
}
}

context dictates escaping, write out as Json string.

context dictates escaping write out as Json string .


private ByteString readJsonString(boolean skipContext)
            throws IOException {
        Buffer buffer = new Buffer();
        ArrayList<Character> codeunits = new ArrayList<>();
        if (!skipContext) {
            context.read();
        }
        readJsonSyntaxChar(QUOTE);
        while (true) {
            byte ch = reader.read();
            if (ch == QUOTE[0]) {
                break;
            }
            if (ch == ESCSEQ[0]) {
                ch = reader.read();
                if (ch == ESCSEQ[1]) {
                    transport.read(tmpbuf, 0, 4);
                    short cu = (short) (
                            ((short) hexVal(tmpbuf[0]) << 12)
                                    + ((short) hexVal(tmpbuf[1]) << 8)
                                    + ((short) hexVal(tmpbuf[2]) << 4)
                                    + (short) hexVal(tmpbuf[3]));
                    try {
                        if (Character.isHighSurrogate((char) cu)) {
                            if (codeunits.size() > 0) {
                                throw new ProtocolException("Expected low surrogate char");
                            }
                            codeunits.add((char) cu);
                        } else if (Character.isLowSurrogate((char) cu)) {
                            if (codeunits.size() == 0) {
                                throw new ProtocolException("Expected high surrogate char");
                            }

                            codeunits.add((char) cu);
                            buffer.write(new String(new int[]{codeunits.get(0), codeunits.get(1)}, 0, 2)
                                    .getBytes("UTF-8"));
                            codeunits.clear();
                        } else {
                            buffer.write(new String(new int[]{cu}, 0, 1).getBytes("UTF-8"));
                        }
                        continue;
                    } catch (UnsupportedEncodingException e) {
                        throw new AssertionError(e);
                    } catch (IOException ex) {
                        throw new ProtocolException("Invalid unicode sequence");
                    }
                } else {
                    int off = ESCAPE_CHARS.indexOf(ch);
                    if (off == -1) {
                        throw new ProtocolException("Expected control char");
                    }
                    ch = ESCAPE_CHAR_VALS[off];
                }
            }
            buffer.write(new byte[]{ch});
        }
        return buffer.readByteString();
    }

private
ByteString
readJsonString
(
boolean
skipContext
)
throws
IOException
{
Buffer
buffer
=
new
Buffer
(
)
;
ArrayList
<
Character
>
codeunits
=
new
ArrayList
<>
(
)
;
if
(
!
skipContext
)
{
context
.
read
(
)
;
}
readJsonSyntaxChar
(
QUOTE
)
;
while
(
true
)
{
byte
ch
=
reader
.
read
(
)
;
if
(
ch
==
QUOTE
[
0
]
)
{
break
;
}
if
(
ch
==
ESCSEQ
[
0
]
)
{
ch
=
reader
.
read
(
)
;
if
(
ch
==
ESCSEQ
[
1
]
)
{
transport
.
read
(
tmpbuf
,
0
,
4
)
;
short
cu
=
(
short
)
(
(
(
short
)
hexVal
(
tmpbuf
[
0
]
)
<<
12
)
+
(
(
short
)
hexVal
(
tmpbuf
[
1
]
)
<<
8
)
+
(
(
short
)
hexVal
(
tmpbuf
[
2
]
)
<<
4
)
+
(
short
)
hexVal
(
tmpbuf
[
3
]
)
)
;
try
{
if
(
Character
.
isHighSurrogate
(
(
char
)
cu
)
)
{
if
(
codeunits
.
size
(
)
>
0
)
{
throw
new
ProtocolException
(
"Expected low surrogate char"
)
;
}
codeunits
.
add
(
(
char
)
cu
)
;
}
else
if
(
Character
.
isLowSurrogate
(
(
char
)
cu
)
)
{
if
(
codeunits
.
size
(
)
==
0
)
{
throw
new
ProtocolException
(
"Expected high surrogate char"
)
;
}
codeunits
.
add
(
(
char
)
cu
)
;
buffer
.
write
(
new
String
(
new
int
[
]
{
codeunits
.
get
(
0
)
,
codeunits
.
get
(
1
)
}
,
0
,
2
)
.
getBytes
(
"UTF-8"
)
)
;
codeunits
.
clear
(
)
;
}
else
{
buffer
.
write
(
new
String
(
new
int
[
]
{
cu
}
,
0
,
1
)
.
getBytes
(
"UTF-8"
)
)
;
}
continue
;
}
catch
(
UnsupportedEncodingException
e
)
{
throw
new
AssertionError
(
e
)
;
}
catch
(
IOException
ex
)
{
throw
new
ProtocolException
(
"Invalid unicode sequence"
)
;
}
}
else
{
int
off
=
ESCAPE_CHARS
.
indexOf
(
ch
)
;
if
(
off
==
1
)
{
throw
new
ProtocolException
(
"Expected control char"
)
;
}
ch
=
ESCAPE_CHAR_VALS
[
off
]
;
}
}
buffer
.
write
(
new
byte
[
]
{
ch
}
)
;
}
return
buffer
.
readByteString
(
)
;
}


private String readJsonNumericChars() throws IOException {
        StringBuilder strbld = new StringBuilder();
        while (true) {
            byte ch = reader.peek();
            if (!isJsonNumeric(ch)) {
                break;
            }
            strbld.append((char) reader.read());
        }
        return strbld.toString();
    }

private String readJsonNumericChars ( ) throws IOException { StringBuilder strbld = new StringBuilder ( ) ; while ( true ) { byte ch = reader . peek ( ) ; if ( ! isJsonNumeric ( ch ) ) { break ; } strbld . append ( ( char ) reader . read ( ) ) ; } return strbld . toString ( ) ; }

not do a complete regex check to validate that this is actually a number.

not do a complete regex check to validate that this is actually a number .


private long readJsonInteger() throws IOException {
        context.read();
        if (context.escapeNum()) {
            readJsonSyntaxChar(QUOTE);
        }
        String str = readJsonNumericChars();
        if (context.escapeNum()) {
            readJsonSyntaxChar(QUOTE);
        }
        try {
            return Long.valueOf(str);
        } catch (NumberFormatException ex) {
            throw new ProtocolException("Bad data encountered in numeric data");
        }
    }

private
long
readJsonInteger
(
)
throws
IOException
{
context
.
read
(
)
;
if
(
context
.
escapeNum
(
)
)
{
readJsonSyntaxChar
(
QUOTE
)
;
}
String
str
=
readJsonNumericChars
(
)
;
if
(
context
.
escapeNum
(
)
)
{
readJsonSyntaxChar
(
QUOTE
)
;
}
try
{
return
Long
.
valueOf
(
str
)
;
}
catch
(
NumberFormatException
ex
)
{
throw
new
ProtocolException
(
"Bad data encountered in numeric data"
)
;
}
}

Read in a Json number. If the context dictates, read in enclosing quotes.

Read in a Json number . If the context dictates read in enclosing quotes .


private double readJsonDouble() throws IOException {
        context.read();
        if (reader.peek() == QUOTE[0]) {
            ByteString str = readJsonString(true);
            double dub = Double.valueOf(str.utf8());
            if (!context.escapeNum() && !Double.isNaN(dub)
                    && !Double.isInfinite(dub)) {
                // Throw exception -- we should not be in a string in this case
                throw new ProtocolException("Numeric data unexpectedly quoted");
            }
            return dub;
        } else {
            if (context.escapeNum()) {
                // This will throw - we should have had a quote if escapeNum == true
                readJsonSyntaxChar(QUOTE);
            }
            try {
                return Double.valueOf(readJsonNumericChars());
            } catch (NumberFormatException ex) {
                throw new ProtocolException("Bad data encountered in numeric data");
            }
        }
    }

when expected or if wrapped in quotes when not expected.

when expected or if wrapped in quotes when not expected .


private ByteString readJsonBase64() throws IOException {
        ByteString str = readJsonString(false);
        return ByteString.decodeBase64(str.utf8());
    }

private ByteString readJsonBase64 ( ) throws IOException { ByteString str = readJsonString ( false ) ; return ByteString . decodeBase64 ( str . utf8 ( ) ) ; }

Read in a Json string containing base-64 encoded data and decode it.

Read in a Json string containing base - 64 encoded data and decode it .


protected final Object execute(MethodCall<?> methodCall) throws Exception {
        if (!running.get()) {
            throw new IllegalStateException("Cannot write to a closed service client");
        }

        try {
            return invokeRequest(methodCall);
        } catch (ServerException e) {
            throw e.thriftException;
        }
    }

When invoked by a derived instance, sends the given call to the server.

@param methodCall the remote method call to be invoked
@return the result of the method call

When invoked by a derived instance sends the given call to the server .


final Object invokeRequest(MethodCall<?> call) throws Exception {
        boolean isOneWay = call.callTypeId == TMessageType.ONEWAY;
        int sid = seqId.incrementAndGet();

        protocol.writeMessageBegin(call.name, call.callTypeId, sid);
        call.send(protocol);
        protocol.writeMessageEnd();
        protocol.flush();

        if (isOneWay) {
            // No response will be received
            return null;
        }

        MessageMetadata metadata = protocol.readMessageBegin();

        if (metadata.seqId != sid) {
            throw new ThriftException(
                    ThriftException.Kind.BAD_SEQUENCE_ID,
                    "Unrecognized sequence ID");
        }

        if (metadata.type == TMessageType.EXCEPTION) {
            ThriftException e = ThriftException.read(protocol);
            protocol.readMessageEnd();
            throw new ServerException(e);
        } else if (metadata.type != TMessageType.REPLY) {
            throw new ThriftException(
                    ThriftException.Kind.INVALID_MESSAGE_TYPE,
                    "Invalid message type: " + metadata.type);
        }

        if (metadata.seqId != seqId.get()) {
            throw new ThriftException(
                    ThriftException.Kind.BAD_SEQUENCE_ID,
                    "Out-of-order response");
        }

        if (!metadata.name.equals(call.name)) {
            throw new ThriftException(
                    ThriftException.Kind.WRONG_METHOD_NAME,
                    "Unexpected method name in reply; expected " + call.name
                            + " but received " + metadata.name);
        }

        try {
            Object result = call.receive(protocol, metadata);
            protocol.readMessageEnd();
            return result;
        } catch (Exception e) {
            if (e instanceof Struct) {
                // Business as usual
                protocol.readMessageEnd();
            }
            throw e;
        }
    }

Send the given call to the server.

@param call the remote method call to be invoked
@return the result of the method call
@throws ServerException wrapper around {@link ThriftException}. Callers should catch and unwrap this.
@throws IOException from the protocol
@throws Exception exception received from server implements {@link com.microsoft.thrifty.Struct}


protected void enqueue(MethodCall<?> methodCall) {
        if (!running.get()) {
            throw new IllegalStateException("Cannot write to a closed service client");
        }

        if (!pendingCalls.offer(methodCall)) {
            // This should never happen with an unbounded queue
            throw new IllegalStateException("Call queue is full");
        }
    }

When invoked by a derived instance, places the given call in a queue to
be sent to the server.

@param methodCall the remote method call to be invoked

When invoked by a derived instance places the given call in a queue to be sent to the server .


public static IFile getResourceFromFSPath(String location) {
        return Activator.getDefault().getWorkspace().
                getRoot().getFileForLocation(new Path(location));
    }

public static IFile getResourceFromFSPath ( String location ) { return Activator . getDefault ( ) . getWorkspace ( ) . getRoot ( ) . getFileForLocation ( new Path ( location ) ) ; }

Resolves a file system location to an Eclipse workspace resource.
@param location The file system location
@return The Eclipse IFile, null if not found

Resolves a file system location to an Eclipse workspace resource .


public static void updateDecoration() {
        final IWorkbench workbench = Activator.getDefault().getWorkbench();
        workbench.getDisplay().syncExec(new Runnable() {
            public void run() {
                IDecoratorManager manager = workbench.getDecoratorManager();
                manager.update(GuvnorDecorator.DECORATOR_ID);
            }
        });
    }

public static void updateDecoration ( ) { final IWorkbench workbench = Activator . getDefault ( ) . getWorkbench ( ) ; workbench . getDisplay ( ) . syncExec ( new Runnable ( ) { public void run ( ) { IDecoratorManager manager = workbench . getDecoratorManager ( ) ; manager . update ( GuvnorDecorator . DECORATOR_ID ) ; } } ) ; }

Causes the platform to update Guvnor decoration notions.

Causes the platform to update Guvnor decoration notions .


public static void refreshRepositoryView() {
        IWorkbenchWindow activeWindow = Activator.getDefault().
                                            getWorkbench().getActiveWorkbenchWindow();
        // If there is no active workbench window, then there can be no Repository view
        if (activeWindow == null) {
            return;
        }
        // If there is no active workbench page, then there can be no Repository view
        IWorkbenchPage page = activeWindow.getActivePage();
        if (page == null) {
            return;
        }
        RepositoryView view = (RepositoryView)page.findView(IGuvnorConstants.REPVIEW_ID);
        if (view != null) {
            view.refresh();
        }
    }

Causes the Repository view to refresh, if it is open.

Causes the Repository view to refresh if it is open .


public static ResourceHistoryView getResourceHistoryView() throws Exception {
        IWorkbenchWindow activeWindow = Activator.getDefault().
                                            getWorkbench().getActiveWorkbenchWindow();
        // If there is no active workbench window, then there can be no Repository History view
        if (activeWindow == null) {
            return null;
        }
        // If there is no active workbench page, then there can be no Repository History view
        IWorkbenchPage page = activeWindow.getActivePage();
        if (page == null) {
            return null;
        }
        return (ResourceHistoryView)page.showView(IGuvnorConstants.RESHISTORYVIEW_ID);
    }

Tries to find the Resource History view, attempting to open it if necessary.

Tries to find the Resource History view attempting to open it if necessary .


public static void openEditor(String contents, String name) {
        IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
        IStorage storage = new StringStorage(contents, name);
        IStorageEditorInput input = new StringInput(storage);
        IWorkbenchPage page = window.getActivePage();
        IEditorDescriptor desc = PlatformUI.getWorkbench().
                                    getEditorRegistry().getDefaultEditor(name);
        // If there is no editor associated with the given file name, we'll just
        // use the eclipse text editor as a default
        String editorId = desc != null?desc.getId():"org.eclipse.ui.DefaultTextEditor"; //$NON-NLS-1$
        try {
        if (page != null) {
            page.openEditor(input, editorId);
        }
        } catch (Exception e) {
            Activator.getDefault().displayError(IStatus.ERROR, e.getMessage(), e, true);
        }
    }

Opens a read-only, in-memory editor.
@param contents The contents for the editor
@param name The name of the file. Will be used to determine
eclipse editor association, defaulting to text editor
if no association is found

Opens a read - only in - memory editor .


public static void reportAuthenticationFailure() {
        Display display = PlatformUI.getWorkbench().getDisplay();
        display.asyncExec(new Runnable() {
            public void run() {
                Display display = Display.getCurrent();
                Shell shell = display.getActiveShell();
                MessageDialog.openError(shell, Messages.getString("login.failure.dialog.caption"),  //$NON-NLS-1$
                                       Messages.getString("login.failure.dialog.message")); //$NON-NLS-1$
            }
        });
    }

public static void reportAuthenticationFailure ( ) { Display display = PlatformUI . getWorkbench ( ) . getDisplay ( ) ; display . asyncExec ( new Runnable ( ) { public void run ( ) { Display display = Display . getCurrent ( ) ; Shell shell = display . getActiveShell ( ) ; MessageDialog . openError ( shell , Messages . getString ( "login.failure.dialog.caption" ) , //$NON-NLS-1$ Messages . getString ( "login.failure.dialog.message" ) ) ; //$NON-NLS-1$ } } ) ; }

Convenience method for reporting log in failure


public AuthPromptResults promptForAuthentication(final String server) {

        Display display = PlatformUI.getWorkbench().getDisplay();
        AuthPromptRunnable op = new AuthPromptRunnable(server);
        display.syncExec(op);
        return op.getResults();
    }

public AuthPromptResults promptForAuthentication ( final String server ) { Display display = PlatformUI . getWorkbench ( ) . getDisplay ( ) ; AuthPromptRunnable op = new AuthPromptRunnable ( server ) ; display . syncExec ( op ) ; return op . getResults ( ) ; }

Prompts for user name and password for a given Guvnor repository.
@param server The repository for log in
@return The dialog results. Includes whether the user decided to save
the user name and password in the platform's key ring.
Null if the user cancels the dialog.

Prompts for user name and password for a given Guvnor repository .


private Control createDefaultPage(FormToolkit kit) {
		Form form = kit.createForm(book);
		Composite body = form.getBody();
		GridLayout layout = new GridLayout(2, false);
		body.setLayout(layout);

		Link hlink = new Link(body, SWT.NONE);
		hlink.setText("Use the Servers View to create a new server...");
		hlink.setBackground(book.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND));
		GridData gd = new GridData(SWT.LEFT, SWT.FILL, true, false);
		hlink.setLayoutData(gd);
		hlink.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				// show Servers View
				ViewUtils.showServersView();
			}
		});

		// Create the context menu for the default page
		final CommonViewer commonViewer = this.getCommonViewer();
		if (commonViewer != null) {
			ICommonViewerSite commonViewerSite = CommonViewerSiteFactory.createCommonViewerSite(this.getViewSite());

			if (commonViewerSite != null) {
				// Note: actionService cannot be null
				final NavigatorActionService actionService = new NavigatorActionService(commonViewerSite, commonViewer,
						commonViewer.getNavigatorContentService());

				MenuManager menuManager = new MenuManager("#PopupMenu");
				menuManager.addMenuListener(new IMenuListener() {
					public void menuAboutToShow(IMenuManager mgr) {
						ISelection selection = commonViewer.getSelection();
						actionService.setContext(new ActionContext(selection));
						actionService.fillContextMenu(mgr);
					}
				});
				Menu menu = menuManager.createContextMenu(body);

				// It is necessary to set the menu in two places:
				// 1. The white space in the server view
				// 2. The text and link in the server view. If this menu is not
				// set, if the
				// user right clicks on the text or uses shortcut keys to open
				// the context menu,
				// the context menu will not come up
				body.setMenu(menu);
				hlink.setMenu(menu);
			} else {
				// if (Trace.FINEST) {
				// Trace.trace(Trace.STRING_FINEST,
				// "The commonViewerSite is null");
				// }
			}
		} else {
			// if (Trace.FINEST) {
			// Trace.trace(Trace.STRING_FINEST, "The commonViewer is null");
			// }
		}

		return form;
	}

Creates a page displayed when there are no servers defined.

@param kit
@return Control

Creates a page displayed when there are no servers defined .


protected void startThread() {
		if (animationActive)
			return;

		stopAnimation = false;

		final Display display = treeViewer == null ? Display.getDefault() : treeViewer.getControl().getDisplay();
		final int SLEEP = 200;
		final Runnable[] animator = new Runnable[1];
		animator[0] = new Runnable() {
			public void run() {
				if (!stopAnimation) {
					try {
						int size = 0;
						String[] servers;
						synchronized (starting) {
							size = starting.size();
							servers = new String[size];
							starting.toArray(servers);

						}

						for (int i = 0; i < size; i++) {
							IServer server = ServerCore.findServer(servers[i]);
							if (server != null) {
								// ServerDecorator.animate();
								treeViewer.update(server, new String[] { "ICON" });
							}
						}
					} catch (Exception e) {
						// if (Trace.FINEST) {
						// Trace.trace(Trace.STRING_FINEST,
						// "Error in Servers view animation", e);
						// }
					}
					display.timerExec(SLEEP, animator[0]);
				}
			}
		};
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				display.timerExec(SLEEP, animator[0]);
			}
		});
	}


public void setIsKeepAllAlive(boolean isKeepAllAlive) {
        Element child = getFirstChild(root, childNames);
        boolean isAlreadyKeepAllAlive = false;
        if (isDAVElement(child, "keepalive")) //$NON-NLS-1$
            isAlreadyKeepAllAlive = "*".equals(getFirstText(child)); //$NON-NLS-1$
        if (isKeepAllAlive) {
            if (!isAlreadyKeepAllAlive) {
                if (child != null)
                    root.removeChild(child);
                appendChild(root, "keepalive", "*"); //$NON-NLS-1$ //$NON-NLS-2$
            }
        } else if (isAlreadyKeepAllAlive)
            root.removeChild(child);
    }

public
void
setIsKeepAllAlive
(
boolean
isKeepAllAlive
)
{
Element
child
=
getFirstChild
(
root
,
childNames
)
;
boolean
isAlreadyKeepAllAlive
=
false
;
if
(
isDAVElement
(
child
,
"keepalive"
)
)
//$NON-NLS-1$
isAlreadyKeepAllAlive
=
"*"
.
equals
(
getFirstText
(
child
)
)
;
//$NON-NLS-1$
if
(
isKeepAllAlive
)
{
if
(
!
isAlreadyKeepAllAlive
)
{
if
(
child
!=
)
root
.
removeChild
(
child
)
;
appendChild
(
root
,
"keepalive"
,
"*"
)
;
//$NON-NLS-1$ //$NON-NLS-2$
}
}
else
if
(
isAlreadyKeepAllAlive
)
root
.
removeChild
(
child
)
;
}

Sets whether this propertybehavior is in the "keep all alive" form or
not.

@param isKeepAllAlive a boolean indicating whether this
propertybehavior will be in the "keep all
alive" form

Sets whether this propertybehavior is in the keep all alive form or not .


public void setIsOmit(boolean isOmit) {
        Element child = getFirstChild(root, childNames);
        boolean isAlreadyOmit = isDAVElement(child, "omit"); //$NON-NLS-1$
        if (isOmit) {
            if (!isAlreadyOmit) {
                if (child != null)
                    root.removeChild(child);
                appendChild(root, "omit"); //$NON-NLS-1$
            }
        } else if (isAlreadyOmit)
            root.removeChild(child);
    }

public void setIsOmit ( boolean isOmit ) { Element child = getFirstChild ( root , childNames ) ; boolean isAlreadyOmit = isDAVElement ( child , "omit" ) ; //$NON-NLS-1$ if ( isOmit ) { if ( ! isAlreadyOmit ) { if ( child != null ) root . removeChild ( child ) ; appendChild ( root , "omit" ) ; //$NON-NLS-1$ } } else if ( isAlreadyOmit ) root . removeChild ( child ) ; }

Sets whether this propertybehavior is in the "omit" form or not.

@param isOmit a boolean indicating whether this propertybehavior will
be in the "omit" form

Sets whether this propertybehavior is in the omit form or not .


public Owner setOwner() {
        Element owner = setChild(root, "owner", childNames, false); //$NON-NLS-1$
        Owner result = null;
        try {
            result = new Owner(owner);
        } catch (MalformedElementException e) {
            Assert.isTrue(false, Policy.bind("assert.internalError")); //$NON-NLS-1$
        }
        return result;
    }

public Owner setOwner ( ) { Element owner = setChild ( root , "owner" , childNames , false ) ; //$NON-NLS-1$ Owner result = null ; try { result = new Owner ( owner ) ; } catch ( MalformedElementException e ) { Assert . isTrue ( false , Policy . bind ( "assert.internalError" ) ) ; //$NON-NLS-1$ } return result ; }

Creates and sets an owner element on this activelock and returns an
editor on it.

@return an editor on an owner element

Creates and sets an owner element on this activelock and returns an editor on it .


public void addConditionFactor(ConditionFactor factor) throws WebDAVException {
        if (conditionFactors.contains(factor))
            throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseDuplicateEntry")); //$NON-NLS-1$
        conditionFactors.addElement(factor);
    }

public void addConditionFactor ( ConditionFactor factor ) throws WebDAVException { if ( conditionFactors . contains ( factor ) ) throw new WebDAVException ( IResponse . SC_BAD_REQUEST , Policy . bind ( "error.parseDuplicateEntry" ) ) ; //$NON-NLS-1$ conditionFactors . addElement ( factor ) ; }

Add a ConditionFactor to a ConditionTerm.

@param factor the factor to add
@exception WebDAVException thrown if the term already contains the factor

Add a ConditionFactor to a ConditionTerm .


public static ConditionTerm create(StreamTokenizer tokenizer) throws WebDAVException {
        ConditionTerm term = new ConditionTerm();
        try {
            int token = tokenizer.ttype;
            if (token == '(')
                token = tokenizer.nextToken();
            else
                throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseMissing", String.valueOf(token), "(")); //$NON-NLS-1$ //$NON-NLS-2$

            while (token == StreamTokenizer.TT_WORD || token == '<' || token == '[') {
                term.addConditionFactor(ConditionFactor.create(tokenizer));
                token = tokenizer.ttype;
            }
            if (token == ')')
                token = tokenizer.nextToken();
            else
                throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseMissing", String.valueOf(token), ")")); //$NON-NLS-1$ //$NON-NLS-2$
        } catch (IOException exc) {
            // ignore or log?
        }
        if (!term.getConditionFactors().hasMoreElements())
            throw new WebDAVException(IResponse.SC_BAD_REQUEST, Policy.bind("error.parseMissingStateOrEntity")); //$NON-NLS-1$
        return term;
    }

public
static
ConditionTerm
create
(
StreamTokenizer
tokenizer
)
throws
WebDAVException
{
ConditionTerm
term
=
new
ConditionTerm
(
)
;
try
{
int
token
=
tokenizer
.
ttype
;
if
(
token
==
'
'
)
token
=
tokenizer
.
nextToken
(
)
;
else
throw
new
WebDAVException
(
IResponse
.
SC_BAD_REQUEST
,
Policy
.
bind
(
"error.parseMissing"
,
String
.
valueOf
(
token
)
,
"("
)
)
;
//$NON-NLS-1$ //$NON-NLS-2$
while
(
token
==
StreamTokenizer
.
TT_WORD
||
token
==
'
'
||
token
==
'
'
)
{
term
.
addConditionFactor
(
ConditionFactor
.
create
(
tokenizer
)
)
;
token
=
tokenizer
.
ttype
;
}
if
(
token
==
'
'
)
token
=
tokenizer
.
nextToken
(
)
;
else
throw
new
WebDAVException
(
IResponse
.
SC_BAD_REQUEST
,
Policy
.
bind
(
"error.parseMissing"
,
String
.
valueOf
(
token
)
,
")"
)
)
;
//$NON-NLS-1$ //$NON-NLS-2$
}
catch
(
IOException
exc
)
{
// ignore or log?
}
if
(
!
term
.
getConditionFactors
(
)
.
hasMoreElements
(
)
)
throw
new
WebDAVException
(
IResponse
.
SC_BAD_REQUEST
,
Policy
.
bind
(
"error.parseMissingStateOrEntity"
)
)
;
//$NON-NLS-1$
return
term
;
}

Create a ConditionTerm by parsing the given If header as defined by
section 9.4 in the WebDAV spec.

@param tokenizer a StreamTokenizer on the contents of a WebDAV If header
@return the parsed ConditionTerm
@exception WebDAVException thrown if there is a syntax error in the If header

Create a ConditionTerm by parsing the given If header as defined by section 9 . 4 in the WebDAV spec .


public boolean matches(ConditionTerm conditionTerm) {
        int numberOfItemsToMatch = 0;
        boolean match = true;
        Enumeration factors = getConditionFactors();
        while (match && factors.hasMoreElements()) {
            ConditionFactor factor = (ConditionFactor) factors.nextElement();
            if (factor.not()) {
                match = !conditionTerm.contains(factor);
            } else {
                match = conditionTerm.contains(factor);
                numberOfItemsToMatch++;
            }
        }
        match = match && numberOfItemsToMatch == conditionTerm.numberOfFactors();
        return match;
    }

public boolean matches ( ConditionTerm conditionTerm ) { int numberOfItemsToMatch = 0 ; boolean match = true ; Enumeration factors = getConditionFactors ( ) ; while ( match && factors . hasMoreElements ( ) ) { ConditionFactor factor = ( ConditionFactor ) factors . nextElement ( ) ; if ( factor . not ( ) ) { match = ! conditionTerm . contains ( factor ) ; } else { match = conditionTerm . contains ( factor ) ; numberOfItemsToMatch ++ ; } } match = match && numberOfItemsToMatch == conditionTerm . numberOfFactors ( ) ; return match ; }

See if this ConditionTerm matches the given ConditionTerm. This is an
AND operation. All the factors in the ConditionTerm must match.

@param conditionTerm the term to match
@return true if all the factors in the term match those in this term

See if this ConditionTerm matches the given ConditionTerm . This is an AND operation . All the factors in the ConditionTerm must match .


public static Reader getDSLContent(String ruleSource, IResource input) throws CoreException {
        String dslFileName = findDSLConfigName( ruleSource, input );
        if (dslFileName == null) {
            return null;
        }
        IResource res = findDSLResource( input, dslFileName );
        if (res instanceof IFile) {
            IFile dslConf = (IFile) res;
            if (dslConf.exists()) {
                return new InputStreamReader(dslConf.getContents());
            }
        }
        return null;
    }

public static Reader getDSLContent ( String ruleSource , IResource input ) throws CoreException { String dslFileName = findDSLConfigName ( ruleSource , input ) ; if ( dslFileName == null ) { return null ; } IResource res = findDSLResource ( input , dslFileName ) ; if ( res instanceof IFile ) { IFile dslConf = ( IFile ) res ; if ( dslConf . exists ( ) ) { return new InputStreamReader ( dslConf . getContents ( ) ) ; } } return null ; }