Input: Convert the string passed as argument to a Level . If the conversion fails then this method returns the value of <code > defaultLevel< / code > . [CODESPLIT] public static Level toLevel ( final String sArg , Level defaultLevel ) { if ( sArg == null ) { return defaultLevel ; } final String in = sArg . trim ( ) ; if ( in . equalsIgnoreCase ( "ALL" ) ) { return Level . ALL ; } if ( in . equalsIgnoreCase ( "TRACE" ) ) { return Level . TRACE ; } if ( in . equalsIgnoreCase ( "DEBUG" ) ) { return Level . DEBUG ; } if ( in . equalsIgnoreCase ( "INFO" ) ) { return Level . INFO ; } if ( in . equalsIgnoreCase ( "WARN" ) ) { return Level . WARN ; } if ( in . equalsIgnoreCase ( "ERROR" ) ) { return Level . ERROR ; } if ( in . equalsIgnoreCase ( "OFF" ) ) { return Level . OFF ; } return defaultLevel ; }


Input: Convert one of the integer values defined in { @link LocationAwareLogger } interface to an instance of this class i . e . a Level . [CODESPLIT] public static Level fromLocationAwareLoggerInteger ( int levelInt ) { Level level ; switch ( levelInt ) { case LocationAwareLogger . TRACE_INT : level = TRACE ; break ; case LocationAwareLogger . DEBUG_INT : level = DEBUG ; break ; case LocationAwareLogger . INFO_INT : level = INFO ; break ; case LocationAwareLogger . WARN_INT : level = WARN ; break ; case LocationAwareLogger . ERROR_INT : level = ERROR ; break ; default : throw new IllegalArgumentException ( levelInt + " not a valid level value" ) ; } return level ; }


Input: Convert this level instance to an integer value defined in the { @link LocationAwareLogger } interface . [CODESPLIT] public static int toLocationAwareLoggerInteger ( Level level ) { if ( level == null ) throw new IllegalArgumentException ( "null level parameter is not admitted" ) ; switch ( level . toInt ( ) ) { case Level . TRACE_INT : return LocationAwareLogger . TRACE_INT ; case Level . DEBUG_INT : return LocationAwareLogger . DEBUG_INT ; case Level . INFO_INT : return LocationAwareLogger . INFO_INT ; case Level . WARN_INT : return LocationAwareLogger . WARN_INT ; case Level . ERROR_INT : return LocationAwareLogger . ERROR_INT ; default : throw new IllegalArgumentException ( level + " not a valid level value" ) ; } }


Input: Returns true if the class of the object o passed as parameter is * not * marked with the NoAutoStart annotation . Return true otherwise . [CODESPLIT] static public boolean notMarkedWithNoAutoStart ( Object o ) { if ( o == null ) { return false ; } Class < ? > clazz = o . getClass ( ) ; NoAutoStart a = clazz . getAnnotation ( NoAutoStart . class ) ; return a == null ; }


Input: Creates a new { [CODESPLIT] public KeyStore createKeyStore ( ) throws NoSuchProviderException , NoSuchAlgorithmException , KeyStoreException { if ( getLocation ( ) == null ) { throw new IllegalArgumentException ( "location is required" ) ; } InputStream inputStream = null ; try { URL url = LocationUtil . urlForResource ( getLocation ( ) ) ; inputStream = url . openStream ( ) ; KeyStore keyStore = newKeyStore ( ) ; keyStore . load ( inputStream , getPassword ( ) . toCharArray ( ) ) ; return keyStore ; } catch ( NoSuchProviderException ex ) { throw new NoSuchProviderException ( "no such keystore provider: " + getProvider ( ) ) ; } catch ( NoSuchAlgorithmException ex ) { throw new NoSuchAlgorithmException ( "no such keystore type: " + getType ( ) ) ; } catch ( FileNotFoundException ex ) { throw new KeyStoreException ( getLocation ( ) + ": file not found" ) ; } catch ( Exception ex ) { throw new KeyStoreException ( getLocation ( ) + ": " + ex . getMessage ( ) , ex ) ; } finally { try { if ( inputStream != null ) { inputStream . close ( ) ; } } catch ( IOException ex ) { ex . printStackTrace ( System . err ) ; } } }


Input: Invokes the appropriate JCE factory method to obtain a new { [CODESPLIT] private KeyStore newKeyStore ( ) throws NoSuchAlgorithmException , NoSuchProviderException , KeyStoreException { return getProvider ( ) != null ? KeyStore . getInstance ( getType ( ) , getProvider ( ) ) : KeyStore . getInstance ( getType ( ) ) ; }


Input: Compute the number of occurrences a resource can be found by a class loader . [CODESPLIT] public static Set < URL > getResourceOccurrenceCount ( String resource , ClassLoader classLoader ) throws IOException { // See LBCLASSIC-159 Set < URL > urlSet = new HashSet < URL > ( ) ; Enumeration < URL > urlEnum = classLoader . getResources ( resource ) ; while ( urlEnum . hasMoreElements ( ) ) { URL url = urlEnum . nextElement ( ) ; urlSet . add ( url ) ; } return urlSet ; }


Input: Search for a resource using the classloader passed as parameter . [CODESPLIT] public static URL getResource ( String resource , ClassLoader classLoader ) { try { return classLoader . getResource ( resource ) ; } catch ( Throwable t ) { return null ; } }


Input: Get the class loader of the object passed as argument . Return the system class loader if appropriate . [CODESPLIT] public static ClassLoader getClassLoaderOfObject ( Object o ) { if ( o == null ) { throw new NullPointerException ( "Argument cannot be null" ) ; } return getClassLoaderOfClass ( o . getClass ( ) ) ; }


Input: Returns the class loader of clazz in an access privileged section . [CODESPLIT] public static ClassLoader getClassLoaderAsPrivileged ( final Class < ? > clazz ) { if ( ! HAS_GET_CLASS_LOADER_PERMISSION ) return null ; else return AccessController . doPrivileged ( new PrivilegedAction < ClassLoader > ( ) { public ClassLoader run ( ) { return clazz . getClassLoader ( ) ; } } ) ; }


Input: Return the class loader which loaded the class passed as argument . Return the system class loader if appropriate . [CODESPLIT] public static ClassLoader getClassLoaderOfClass ( final Class < ? > clazz ) { ClassLoader cl = clazz . getClassLoader ( ) ; if ( cl == null ) { return ClassLoader . getSystemClassLoader ( ) ; } else { return cl ; } }


Input: If running under JDK 1 . 2 load the specified class using the <code > Thread< / code > <code > contextClassLoader< / code > if that fails try Class . forname . Under JDK 1 . 1 only Class . forName is used . [CODESPLIT] public static Class < ? > loadClass ( String clazz ) throws ClassNotFoundException { // Just call Class.forName(clazz) if we are running under JDK 1.1 // or if we are instructed to ignore the TCL. if ( ignoreTCL ) { return Class . forName ( clazz ) ; } else { try { return getTCL ( ) . loadClass ( clazz ) ; } catch ( Throwable e ) { // we reached here because tcl was null or because of a // security exception, or because clazz could not be loaded... // In any case we now try one more time return Class . forName ( clazz ) ; } } }


Input: Checks that required parameters are set and if everything is in order activates this appender . [CODESPLIT] @ Override public void start ( ) { if ( ( this . encoder == null ) || ( this . encoder . getLayout ( ) == null ) ) { addError ( "No layout set for the appender named [" + name + "]." ) ; return ; } // tag encoder is optional but needs a layout if ( this . tagEncoder != null ) { final Layout < ? > layout = this . tagEncoder . getLayout ( ) ; if ( layout == null ) { addError ( "No tag layout set for the appender named [" + name + "]." ) ; return ; } // prevent stack traces from showing up in the tag // (which could lead to very confusing error messages) if ( layout instanceof PatternLayout ) { String pattern = this . tagEncoder . getPattern ( ) ; if ( ! pattern . contains ( "%nopex" ) ) { this . tagEncoder . stop ( ) ; this . tagEncoder . setPattern ( pattern + "%nopex" ) ; this . tagEncoder . start ( ) ; } PatternLayout tagLayout = ( PatternLayout ) layout ; tagLayout . setPostCompileProcessor ( null ) ; } } super . start ( ) ; }


Input: Writes an event to Android s logging mechanism ( logcat ) [CODESPLIT] public void append ( ILoggingEvent event ) { if ( ! isStarted ( ) ) { return ; } String tag = getTag ( event ) ; switch ( event . getLevel ( ) . levelInt ) { case Level . ALL_INT : case Level . TRACE_INT : if ( ! checkLoggable || Log . isLoggable ( tag , Log . VERBOSE ) ) { Log . v ( tag , this . encoder . getLayout ( ) . doLayout ( event ) ) ; } break ; case Level . DEBUG_INT : if ( ! checkLoggable || Log . isLoggable ( tag , Log . DEBUG ) ) { Log . d ( tag , this . encoder . getLayout ( ) . doLayout ( event ) ) ; } break ; case Level . INFO_INT : if ( ! checkLoggable || Log . isLoggable ( tag , Log . INFO ) ) { Log . i ( tag , this . encoder . getLayout ( ) . doLayout ( event ) ) ; } break ; case Level . WARN_INT : if ( ! checkLoggable || Log . isLoggable ( tag , Log . WARN ) ) { Log . w ( tag , this . encoder . getLayout ( ) . doLayout ( event ) ) ; } break ; case Level . ERROR_INT : if ( ! checkLoggable || Log . isLoggable ( tag , Log . ERROR ) ) { Log . e ( tag , this . encoder . getLayout ( ) . doLayout ( event ) ) ; } break ; case Level . OFF_INT : default : break ; } }


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


Input: { [CODESPLIT] public void setLoggerContext ( LoggerContext lc ) { this . lc = lc ; this . logger = lc . getLogger ( getClass ( ) . getPackage ( ) . getName ( ) ) ; }


Input: { [CODESPLIT] public void run ( ) { logger . info ( this + ": connected" ) ; HardenedObjectInputStream ois = null ; try { ois = createObjectInputStream ( ) ; while ( true ) { // read an event from the wire ILoggingEvent event = ( ILoggingEvent ) ois . readObject ( ) ; // get a logger from the hierarchy. The name of the logger is taken to // be the name contained in the event. Logger remoteLogger = lc . getLogger ( event . getLoggerName ( ) ) ; // apply the logger-level filter if ( remoteLogger . isEnabledFor ( event . getLevel ( ) ) ) { // finally log the event as if was generated locally remoteLogger . callAppenders ( event ) ; } } } catch ( EOFException ex ) { // this is normal and expected assert true ; } catch ( IOException ex ) { logger . info ( this + ": " + ex ) ; } catch ( ClassNotFoundException ex ) { logger . error ( this + ": unknown event class" ) ; } catch ( RuntimeException ex ) { logger . error ( this + ": " + ex ) ; } finally { if ( ois != null ) { CloseUtil . closeQuietly ( ois ) ; } close ( ) ; logger . info ( this + ": connection closed" ) ; } }


Input: Set a new property for the execution context by name value pair or adds all the properties found in the given file . [CODESPLIT] public void begin ( InterpretationContext ec , String localName , Attributes attributes ) { if ( "substitutionProperty" . equals ( localName ) ) { addWarn ( "[substitutionProperty] element has been deprecated. Please use the [property] element instead." ) ; } String name = attributes . getValue ( NAME_ATTRIBUTE ) ; String value = attributes . getValue ( VALUE_ATTRIBUTE ) ; String scopeStr = attributes . getValue ( SCOPE_ATTRIBUTE ) ; Scope scope = ActionUtil . stringToScope ( scopeStr ) ; if ( checkFileAttributeSanity ( attributes ) ) { String file = attributes . getValue ( FILE_ATTRIBUTE ) ; file = ec . subst ( file ) ; try { FileInputStream istream = new FileInputStream ( file ) ; loadAndSetProperties ( ec , istream , scope ) ; } catch ( FileNotFoundException e ) { addError ( "Could not find properties file [" + file + "]." ) ; } catch ( IOException e1 ) { addError ( "Could not read properties file [" + file + "]." , e1 ) ; } } else if ( checkResourceAttributeSanity ( attributes ) ) { String resource = attributes . getValue ( RESOURCE_ATTRIBUTE ) ; resource = ec . subst ( resource ) ; URL resourceURL = Loader . getResourceBySelfClassLoader ( resource ) ; if ( resourceURL == null ) { addError ( "Could not find resource [" + resource + "]." ) ; } else { try { InputStream istream = resourceURL . openStream ( ) ; loadAndSetProperties ( ec , istream , scope ) ; } catch ( IOException e ) { addError ( "Could not read resource file [" + resource + "]." , e ) ; } } } else if ( checkValueNameAttributesSanity ( attributes ) ) { value = RegularEscapeUtil . basicEscape ( value ) ; // now remove both leading and trailing spaces value = value . trim ( ) ; value = ec . subst ( value ) ; ActionUtil . setProperty ( ec , name , value , scope ) ; } else { addError ( INVALID_ATTRIBUTES ) ; } }


Input: Get the position of the separator character if any starting at position fromIndex . [CODESPLIT] public static int getSeparatorIndexOf ( String name , int fromIndex ) { int dotIndex = name . indexOf ( CoreConstants . DOT , fromIndex ) ; int dollarIndex = name . indexOf ( CoreConstants . DOLLAR , fromIndex ) ; if ( dotIndex == - 1 && dollarIndex == - 1 ) return - 1 ; if ( dotIndex == - 1 ) return dollarIndex ; if ( dollarIndex == - 1 ) return dotIndex ; return dotIndex < dollarIndex ? dotIndex : dollarIndex ; }


Input: Return true if event passed as parameter contains one of the specified user - markers . [CODESPLIT] public boolean evaluate ( ILoggingEvent event ) throws NullPointerException , EvaluationException { Marker eventsMarker = event . getMarker ( ) ; if ( eventsMarker == null ) { return false ; } for ( String markerStr : markerList ) { if ( eventsMarker . contains ( markerStr ) ) { return true ; } } return false ; }


Input: Creates a { [CODESPLIT] public TrustManagerFactory createTrustManagerFactory ( ) throws NoSuchProviderException , NoSuchAlgorithmException { return getProvider ( ) != null ? TrustManagerFactory . getInstance ( getAlgorithm ( ) , getProvider ( ) ) : TrustManagerFactory . getInstance ( getAlgorithm ( ) ) ; }


Input: Returns a name to identify each client thread . [CODESPLIT] protected String getClientThreadName ( Socket socket ) { return String . format ( Locale . US , "Logback SocketNode (client: %s)" , socket . getRemoteSocketAddress ( ) ) ; }


Input: This method assumes that both files a and b exists . [CODESPLIT] static public boolean areOnSameFileStore ( File a , File b ) throws RolloverFailure { if ( ! a . exists ( ) ) { throw new IllegalArgumentException ( "File [" + a + "] does not exist." ) ; } if ( ! b . exists ( ) ) { throw new IllegalArgumentException ( "File [" + b + "] does not exist." ) ; } // Implements the following by reflection //    Path pathA = a.toPath(); //    Path pathB = b.toPath(); // //    FileStore fileStoreA = Files.getFileStore(pathA); //    FileStore fileStoreB = Files.getFileStore(pathB); // //    return fileStoreA.equals(fileStoreB); try { Class < ? > pathClass = Class . forName ( PATH_CLASS_STR ) ; Class < ? > filesClass = Class . forName ( FILES_CLASS_STR ) ; Method toPath = File . class . getMethod ( "toPath" ) ; Method getFileStoreMethod = filesClass . getMethod ( "getFileStore" , pathClass ) ; Object pathA = toPath . invoke ( a ) ; Object pathB = toPath . invoke ( b ) ; Object fileStoreA = getFileStoreMethod . invoke ( null , pathA ) ; Object fileStoreB = getFileStoreMethod . invoke ( null , pathB ) ; return fileStoreA . equals ( fileStoreB ) ; } catch ( Exception e ) { throw new RolloverFailure ( "Failed to check file store equality for [" + a + "] and [" + b + "]" , e ) ; } }


Input: Start the appender [CODESPLIT] public void start ( ) { if ( cbTracker == null ) { cbTracker = new CyclicBufferTracker < E > ( ) ; } session = buildSessionFromProperties ( ) ; if ( session == null ) { addError ( "Failed to obtain javax.mail.Session. Cannot start." ) ; return ; } subjectLayout = makeSubjectLayout ( subjectStr ) ; started = true ; }


Input: Perform SMTPAppender specific appending actions delegating some of them to a subclass and checking if the event triggers an e - mail to be sent . [CODESPLIT] protected void append ( E eventObject ) { if ( ! checkEntryConditions ( ) ) { return ; } String key = discriminator . getDiscriminatingValue ( eventObject ) ; long now = System . currentTimeMillis ( ) ; final CyclicBuffer < E > cb = cbTracker . getOrCreate ( key , now ) ; subAppend ( cb , eventObject ) ; try { if ( eventEvaluator . evaluate ( eventObject ) ) { // clone the CyclicBuffer before sending out asynchronously CyclicBuffer < E > cbClone = new CyclicBuffer < E > ( cb ) ; // see http://jira.qos.ch/browse/LBCLASSIC-221 cb . clear ( ) ; if ( asynchronousSending ) { // perform actual sending asynchronously SenderRunnable senderRunnable = new SenderRunnable ( cbClone , eventObject ) ; context . getScheduledExecutorService ( ) . execute ( senderRunnable ) ; } else { // synchronous sending sendBuffer ( cbClone , eventObject ) ; } } } catch ( EvaluationException ex ) { errorCount ++ ; if ( errorCount < CoreConstants . MAX_ERROR_COUNT ) { addError ( "SMTPAppender's EventEvaluator threw an Exception-" , ex ) ; } } // immediately remove the buffer if asked by the user if ( eventMarksEndOfLife ( eventObject ) ) { cbTracker . endOfLife ( key ) ; } cbTracker . removeStaleComponents ( now ) ; if ( lastTrackerStatusPrint + delayBetweenStatusMessages < now ) { addInfo ( "SMTPAppender [" + name + "] is tracking [" + cbTracker . getComponentCount ( ) + "] buffers" ) ; lastTrackerStatusPrint = now ; // quadruple 'delay' assuming less than max delay if ( delayBetweenStatusMessages < MAX_DELAY_BETWEEN_STATUS_MESSAGES ) { delayBetweenStatusMessages *= 4 ; } } }


Input: This method determines if there is a sense in attempting to append . <p > It checks whether there is a set output target and also if there is a set layout . If these checks fail then the boolean value <code > false< / code > is returned . [CODESPLIT] public boolean checkEntryConditions ( ) { if ( ! this . started ) { addError ( "Attempting to append to a non-started appender: " + this . getName ( ) ) ; return false ; } if ( this . eventEvaluator == null ) { addError ( "No EventEvaluator is set for appender [" + name + "]." ) ; return false ; } if ( this . layout == null ) { addError ( "No layout set for appender named [" + name + "]. For more information, please visit http://logback.qos.ch/codes.html#smtp_no_layout" ) ; return false ; } return true ; }


Input: Send the contents of the cyclic buffer as an e - mail message . [CODESPLIT] protected void sendBuffer ( CyclicBuffer < E > cb , E lastEventObject ) { // Note: this code already owns the monitor for this // appender. This frees us from needing to synchronize on 'cb'. try { MimeBodyPart part = new MimeBodyPart ( ) ; StringBuffer sbuf = new StringBuffer ( ) ; String header = layout . getFileHeader ( ) ; if ( header != null ) { sbuf . append ( header ) ; } String presentationHeader = layout . getPresentationHeader ( ) ; if ( presentationHeader != null ) { sbuf . append ( presentationHeader ) ; } fillBuffer ( cb , sbuf ) ; String presentationFooter = layout . getPresentationFooter ( ) ; if ( presentationFooter != null ) { sbuf . append ( presentationFooter ) ; } String footer = layout . getFileFooter ( ) ; if ( footer != null ) { sbuf . append ( footer ) ; } String subjectStr = "Undefined subject" ; if ( subjectLayout != null ) { subjectStr = subjectLayout . doLayout ( lastEventObject ) ; // The subject must not contain new-line characters, which cause // an SMTP error (LOGBACK-865). Truncate the string at the first // new-line character. int newLinePos = ( subjectStr != null ) ? subjectStr . indexOf ( ' ' ) : - 1 ; if ( newLinePos > - 1 ) { subjectStr = subjectStr . substring ( 0 , newLinePos ) ; } } MimeMessage mimeMsg = new MimeMessage ( session ) ; if ( from != null ) { mimeMsg . setFrom ( getAddress ( from ) ) ; } else { mimeMsg . setFrom ( ) ; } mimeMsg . setSubject ( subjectStr , charsetEncoding ) ; List < InternetAddress > destinationAddresses = parseAddress ( lastEventObject ) ; if ( destinationAddresses . isEmpty ( ) ) { addInfo ( "Empty destination address. Aborting email transmission" ) ; return ; } InternetAddress [ ] toAddressArray = destinationAddresses . toArray ( EMPTY_IA_ARRAY ) ; mimeMsg . setRecipients ( Message . RecipientType . TO , toAddressArray ) ; String contentType = layout . getContentType ( ) ; if ( ContentTypeUtil . isTextual ( contentType ) ) { part . setText ( sbuf . toString ( ) , charsetEncoding , ContentTypeUtil . getSubType ( contentType ) ) ; } else { part . setContent ( sbuf . toString ( ) , layout . getContentType ( ) ) ; } Multipart mp = new MimeMultipart ( ) ; mp . addBodyPart ( part ) ; mimeMsg . setContent ( mp ) ; updateMimeMsg ( mimeMsg , cb , lastEventObject ) ; mimeMsg . setSentDate ( new Date ( ) ) ; addInfo ( "About to send out SMTP message \"" + subjectStr + "\" to " + Arrays . toString ( toAddressArray ) ) ; Transport . send ( mimeMsg ) ; } catch ( Exception e ) { addError ( "Error occurred while sending e-mail notification." , e ) ; } }


Input: } [CODESPLIT] public void run ( ) { try { hardenedLoggingEventInputStream = new HardenedLoggingEventInputStream ( new BufferedInputStream ( socket . getInputStream ( ) ) ) ; } catch ( Exception e ) { logger . error ( "Could not open ObjectInputStream to " + socket , e ) ; closed = true ; } ILoggingEvent event ; Logger remoteLogger ; try { while ( ! closed ) { // read an event from the wire event = ( ILoggingEvent ) hardenedLoggingEventInputStream . readObject ( ) ; // get a logger from the hierarchy. The name of the logger is taken to // be the name contained in the event. remoteLogger = context . getLogger ( event . getLoggerName ( ) ) ; // apply the logger-level filter if ( remoteLogger . isEnabledFor ( event . getLevel ( ) ) ) { // finally log the event as if was generated locally remoteLogger . callAppenders ( event ) ; } } } catch ( java . io . EOFException e ) { logger . info ( "Caught java.io.EOFException closing connection." ) ; } catch ( java . net . SocketException e ) { logger . info ( "Caught java.net.SocketException closing connection." ) ; } catch ( IOException e ) { logger . info ( "Caught java.io.IOException: " + e ) ; logger . info ( "Closing connection." ) ; } catch ( Exception e ) { logger . error ( "Unexpected exception. Closing connection." , e ) ; } socketServer . socketNodeClosing ( this ) ; close ( ) ; }


Input: Add a new MDCValuePair [CODESPLIT] public void addMDCValueLevelPair ( MDCValueLevelPair mdcValueLevelPair ) { if ( valueLevelMap . containsKey ( mdcValueLevelPair . getValue ( ) ) ) { addError ( mdcValueLevelPair . getValue ( ) + " has been already set" ) ; } else { valueLevelMap . put ( mdcValueLevelPair . getValue ( ) , mdcValueLevelPair . getLevel ( ) ) ; } }


Input: This method first finds the MDC value for key . It then finds the level threshold associated with this MDC value from the list of MDCValueLevelPair passed to this filter . This value is stored in a variable called levelAssociatedWithMDCValue . If it null then it is set to the { @link #defaultThreshold } value . [CODESPLIT] @ Override public FilterReply decide ( Marker marker , Logger logger , Level level , String s , Object [ ] objects , Throwable throwable ) { String mdcValue = MDC . get ( this . key ) ; if ( ! isStarted ( ) ) { return FilterReply . NEUTRAL ; } Level levelAssociatedWithMDCValue = null ; if ( mdcValue != null ) { levelAssociatedWithMDCValue = valueLevelMap . get ( mdcValue ) ; } if ( levelAssociatedWithMDCValue == null ) { levelAssociatedWithMDCValue = defaultThreshold ; } if ( level . isGreaterOrEqual ( levelAssociatedWithMDCValue ) ) { return onHigherOrEqual ; } else { return onLower ; } }


Input: Attempt to create a converter using the information found in converterMap . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) DynamicConverter < E > createConverter ( SimpleKeywordNode kn ) { String keyword = ( String ) kn . getValue ( ) ; String converterClassStr = ( String ) converterMap . get ( keyword ) ; if ( converterClassStr != null ) { try { return ( DynamicConverter < E > ) OptionHelper . instantiateByClassName ( converterClassStr , DynamicConverter . class , context ) ; } catch ( Exception e ) { addError ( "Failed to instantiate converter class [" + converterClassStr + "] for keyword [" + keyword + "]" , e ) ; return null ; } } else { addError ( "There is no conversion class registered for conversion word [" + keyword + "]" ) ; return null ; } }


Input: Attempt to create a converter using the information found in compositeConverterMap . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) CompositeConverter < E > createCompositeConverter ( CompositeNode cn ) { String keyword = ( String ) cn . getValue ( ) ; String converterClassStr = ( String ) converterMap . get ( keyword ) ; if ( converterClassStr != null ) { try { return ( CompositeConverter < E > ) OptionHelper . instantiateByClassName ( converterClassStr , CompositeConverter . class , context ) ; } catch ( Exception e ) { addError ( "Failed to instantiate converter class [" + converterClassStr + "] as a composite converter for keyword [" + keyword + "]" , e ) ; return null ; } } else { addError ( "There is no conversion class registered for composite conversion word [" + keyword + "]" ) ; return null ; } }


Input: Given the FileNamePattern string this method determines the compression mode depending on last letters of the fileNamePatternStr . Patterns ending with . gz imply GZIP compression endings with . zip imply ZIP compression . Otherwise and by default there is no compression . [CODESPLIT] protected void determineCompressionMode ( ) { if ( fileNamePatternStr . endsWith ( ".gz" ) ) { addInfo ( "Will use gz compression" ) ; compressionMode = CompressionMode . GZ ; } else if ( fileNamePatternStr . endsWith ( ".zip" ) ) { addInfo ( "Will use zip compression" ) ; compressionMode = CompressionMode . ZIP ; } else { addInfo ( "No compression will be used" ) ; compressionMode = CompressionMode . NONE ; } }


Input: Configures logback with the configuration XML read from a file located at the given URL [CODESPLIT] public final void doConfigure ( URL url ) throws JoranException { InputStream in = null ; try { informContextOfURLUsedForConfiguration ( getContext ( ) , url ) ; URLConnection urlConnection = url . openConnection ( ) ; // per http://jira.qos.ch/browse/LBCORE-105 // per http://jira.qos.ch/browse/LBCORE-127 urlConnection . setUseCaches ( false ) ; // this closes the stream for us in = urlConnection . getInputStream ( ) ; doConfigure ( in , url . toExternalForm ( ) ) ; } catch ( IOException ioe ) { String errMsg = "Could not open URL [" + url + "]." ; addError ( errMsg , ioe ) ; throw new JoranException ( errMsg , ioe ) ; } finally { CloseUtil . closeQuietly ( in ) ; } }


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


Input: Configures logback with the configuraiton XML read from an input stream and then closes the stream [CODESPLIT] public final void doConfigure ( InputStream inputStream ) throws JoranException { try { doConfigure ( new InputSource ( inputStream ) ) ; } finally { try { inputStream . close ( ) ; } catch ( IOException ioe ) { String errMsg = "Could not close the stream" ; addError ( errMsg , ioe ) ; throw new JoranException ( errMsg , ioe ) ; } } }


Input: Builds a generic configuration - XML interpreter [CODESPLIT] protected void buildInterpreter ( ) { RuleStore rs = new SimpleRuleStore ( context ) ; addInstanceRules ( rs ) ; this . interpreter = new Interpreter ( context , rs , initialElementPath ( ) ) ; InterpretationContext interpretationContext = interpreter . getInterpretationContext ( ) ; interpretationContext . setContext ( context ) ; addImplicitRules ( interpreter ) ; addDefaultNestedComponentRegistryRules ( interpretationContext . getDefaultNestedComponentRegistry ( ) ) ; }


Input: Configures logback with the configuration XML read from an input source . [CODESPLIT] private final void doConfigure ( final InputSource inputSource ) throws JoranException { long threshold = System . currentTimeMillis ( ) ; //    if (!ConfigurationWatchListUtil.wasConfigurationWatchListReset(context)) { //      informContextOfURLUsedForConfiguration(getContext(), null); //    } SaxEventRecorder recorder = new SaxEventRecorder ( context ) ; recorder . recordEvents ( inputSource ) ; doConfigure ( recorder . getSaxEventList ( ) ) ; // no exceptions a this level StatusUtil statusUtil = new StatusUtil ( context ) ; if ( statusUtil . noXMLParsingErrorsOccurred ( threshold ) ) { addInfo ( "Registering current configuration as safe fallback point" ) ; registerSafeConfiguration ( recorder . getSaxEventList ( ) ) ; } }


Input: Configures logback with SAX events of configuration XML [CODESPLIT] public void doConfigure ( final List < SaxEvent > eventList ) throws JoranException { buildInterpreter ( ) ; // disallow simultaneous configurations of the same context synchronized ( context . getConfigurationLock ( ) ) { interpreter . getEventPlayer ( ) . play ( eventList ) ; } }


Input: Given a key return the corresponding property value . If invoked with the special key CONTEXT_NAME the name of the context is returned . [CODESPLIT] public String getProperty ( String key ) { if ( CONTEXT_NAME_KEY . equals ( key ) ) return getName ( ) ; return ( String ) this . propertyMap . get ( key ) ; }


Input: The context name can be set only if it is not already set or if the current name is the default context name namely default or if the current name and the old name are the same . [CODESPLIT] public void setName ( String name ) throws IllegalStateException { if ( name != null && name . equals ( this . name ) ) { return ; // idempotent naming } if ( this . name == null || CoreConstants . DEFAULT_CONTEXT_NAME . equals ( this . name ) ) { this . name = name ; } else { throw new IllegalStateException ( "Context has been already given a name" ) ; } }


Input: Returns true if the StatusManager associated with the context passed as parameter has one or more StatusListener instances registered . Returns false otherwise . [CODESPLIT] static public boolean contextHasStatusListener ( Context context ) { StatusManager sm = context . getStatusManager ( ) ; if ( sm == null ) return false ; List < StatusListener > listeners = sm . getCopyOfStatusListenerList ( ) ; if ( listeners == null || listeners . size ( ) == 0 ) return false ; else return true ; }


Input: Return the time of last reset . - 1 if last reset time could not be found [CODESPLIT] 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 ; }


Input: Add an <code > event< / code > as the last event in the buffer . [CODESPLIT] public void add ( E event ) { ea [ last ] = event ; if ( ++ last == maxSize ) last = 0 ; if ( numElems < maxSize ) numElems ++ ; else if ( ++ first == maxSize ) first = 0 ; }


Input: Get the <i > i< / i > th oldest event currently in the buffer . If <em > i< / em > is outside the range 0 to the number of elements currently in the buffer then <code > null< / code > is returned . [CODESPLIT] public E get ( int i ) { if ( i < 0 || i >= numElems ) return null ; return ea [ ( first + i ) % maxSize ] ; }


Input: Get the oldest ( first ) element in the buffer . The oldest element is removed from the buffer . [CODESPLIT] public E get ( ) { E r = null ; if ( numElems > 0 ) { numElems -- ; r = ea [ first ] ; ea [ first ] = null ; if ( ++ first == maxSize ) first = 0 ; } return r ; }


Input: Resize the cyclic buffer to <code > newSize< / code > . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public void resize ( int newSize ) { if ( newSize < 0 ) { throw new IllegalArgumentException ( "Negative array size [" + newSize + "] not allowed." ) ; } if ( newSize == numElems ) return ; // nothing to do // E [ ] temp = ( E [ ] ) new Object [ newSize ] ; int loopLen = newSize < numElems ? newSize : numElems ; for ( int i = 0 ; i < loopLen ; i ++ ) { temp [ i ] = ea [ first ] ; ea [ first ] = null ; if ( ++ first == numElems ) first = 0 ; } ea = temp ; first = 0 ; numElems = loopLen ; maxSize = newSize ; if ( loopLen == newSize ) { last = 0 ; } else { last = loopLen ; } }


Input: { [CODESPLIT] @ Override protected RemoteReceiverClient createClient ( String id , Socket socket ) throws IOException { return new RemoteReceiverStreamClient ( id , socket ) ; }


Input: { [CODESPLIT] @ Override public Socket createSocket ( InetAddress address , int port , InetAddress localAddress , int localPort ) throws IOException { SSLSocket socket = ( SSLSocket ) delegate . createSocket ( address , port , localAddress , localPort ) ; parameters . configure ( new SSLConfigurableSocket ( socket ) ) ; return socket ; }


Input: { [CODESPLIT] @ Override public Socket createSocket ( InetAddress host , int port ) throws IOException { SSLSocket socket = ( SSLSocket ) delegate . createSocket ( host , port ) ; parameters . configure ( new SSLConfigurableSocket ( socket ) ) ; return socket ; }


Input: } [CODESPLIT] public static ConfigurationWatchList getConfigurationWatchList ( Context context ) { if ( context == null ) return null ; return ( ConfigurationWatchList ) context . getObject ( CoreConstants . CONFIGURATION_WATCH_LIST ) ; }


Input: Parses the pattern and creates the Converter linked list . [CODESPLIT] @ 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 ; } }


Input: Returns a map where the default converter map is merged with the map contained in the context . [CODESPLIT] 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 ; }


Input: Returns appropriate HTML headers . [CODESPLIT] @ 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 ( ) ; }


Input: Returns the appropriate HTML footers . [CODESPLIT] @ Override public String getFileFooter ( ) { StringBuilder sbuf = new StringBuilder ( ) ; sbuf . append ( LINE_SEPARATOR ) ; sbuf . append ( "" ) ; return sbuf . toString ( ) ; }


Input: Instantiates an appender of the given class and sets its name . [CODESPLIT] @ 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 ) ; } }


Input: Once the children elements are also parsed now is the time to activate the appender options . [CODESPLIT] 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 ( ) ; } }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override final public boolean isTooSoon ( long currentTime ) { boolean maskMatch = ( ( invocationCounter ++ ) & mask ) == mask ; if ( maskMatch ) { if ( currentTime < this . lowerLimitForMaskMatch ) { increaseMask ( ) ; } updateLimits ( currentTime ) ; } else { if ( currentTime > this . upperLimitForNoMaskMatch ) { decreaseMask ( ) ; updateLimits ( currentTime ) ; return false ; } } return ! maskMatch ; }


Input: { [CODESPLIT] public void stop ( ) throws IOException { listener . close ( ) ; accept ( new ClientVisitor < T > ( ) { public void visit ( T client ) { client . close ( ) ; } } ) ; }


Input: { [CODESPLIT] public void accept ( ClientVisitor < T > visitor ) { Collection < T > clients = copyClients ( ) ; for ( T client : clients ) { try { visitor . visit ( client ) ; } catch ( RuntimeException ex ) { addError ( client + ": " + ex ) ; } } }


Input: Creates a copy of the collection of all clients that are presently being tracked by the server . [CODESPLIT] private Collection < T > copyClients ( ) { clientsLock . lock ( ) ; try { Collection < T > copy = new ArrayList < T > ( clients ) ; return copy ; } finally { clientsLock . unlock ( ) ; } }


Input: { [CODESPLIT] public void run ( ) { setRunning ( true ) ; try { addInfo ( "listening on " + listener ) ; while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { T client = listener . acceptClient ( ) ; if ( ! configureClient ( client ) ) { addError ( client + ": connection dropped" ) ; client . close ( ) ; continue ; } try { executor . execute ( new ClientWrapper ( client ) ) ; } catch ( RejectedExecutionException ex ) { addError ( client + ": connection dropped" ) ; client . close ( ) ; } } } catch ( InterruptedException ex ) { assert true ; // ok... we'll shut down } catch ( Exception ex ) { addError ( "listener: " + ex ) ; } setRunning ( false ) ; addInfo ( "shutting down" ) ; listener . close ( ) ; }


Input: Adds a client to the collection of those being tracked by the server . [CODESPLIT] private void addClient ( T client ) { clientsLock . lock ( ) ; try { clients . add ( client ) ; } finally { clientsLock . unlock ( ) ; } }


Input: Removes a client from the collection of those being tracked by the server . [CODESPLIT] private void removeClient ( T client ) { clientsLock . lock ( ) ; try { clients . remove ( client ) ; } finally { clientsLock . unlock ( ) ; } }


Input: Put a context value ( the <code > val< / code > parameter ) as identified with the <code > key< / code > parameter into the current thread s context map . Note that contrary to log4j the <code > val< / code > parameter can be null . <p > If the current thread does not have a context map it is created as a side effect of this call . [CODESPLIT] public void put ( String key , String val ) throws IllegalArgumentException { if ( key == null ) { throw new IllegalArgumentException ( "key cannot be null" ) ; } Map < String , String > oldMap = copyOnThreadLocal . get ( ) ; Integer lastOp = getAndSetLastOperation ( WRITE_OPERATION ) ; if ( wasLastOpReadOrNull ( lastOp ) || oldMap == null ) { Map < String , String > newMap = duplicateAndInsertNewMap ( oldMap ) ; newMap . put ( key , val ) ; } else { oldMap . put ( key , val ) ; } }


Input: Remove the the context identified by the <code > key< / code > parameter . [CODESPLIT] public void remove ( String key ) { if ( key == null ) { return ; } Map < String , String > oldMap = copyOnThreadLocal . get ( ) ; if ( oldMap == null ) return ; Integer lastOp = getAndSetLastOperation ( WRITE_OPERATION ) ; if ( wasLastOpReadOrNull ( lastOp ) ) { Map < String , String > newMap = duplicateAndInsertNewMap ( oldMap ) ; newMap . remove ( key ) ; } else { oldMap . remove ( key ) ; } }


Input: Get the context identified by the <code > key< / code > parameter . [CODESPLIT] public String get ( String key ) { final Map < String , String > map = copyOnThreadLocal . get ( ) ; if ( ( map != null ) && ( key != null ) ) { return map . get ( key ) ; } else { return null ; } }


Input: Returns the keys in the MDC as a { [CODESPLIT] public Set < String > getKeys ( ) { Map < String , String > map = getPropertyMap ( ) ; if ( map != null ) { return map . keySet ( ) ; } else { return null ; } }


Input: Return a copy of the current thread s context map . Returned value may be null . [CODESPLIT] public Map < String , String > getCopyOfContextMap ( ) { Map < String , String > hashMap = copyOnThreadLocal . get ( ) ; if ( hashMap == null ) { return null ; } else { return new HashMap < String , String > ( hashMap ) ; } }


Input: Convert <code > val< / code > a String parameter to an object of a given type . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public static Object convertArg ( ContextAware ca , String val , Class < ? > type ) { if ( val == null ) { return null ; } String v = val . trim ( ) ; if ( String . class . isAssignableFrom ( type ) ) { return v ; } else if ( Integer . TYPE . isAssignableFrom ( type ) ) { return Integer . valueOf ( v ) ; } else if ( Long . TYPE . isAssignableFrom ( type ) ) { return Long . valueOf ( v ) ; } else if ( Float . TYPE . isAssignableFrom ( type ) ) { return Float . valueOf ( v ) ; } else if ( Double . TYPE . isAssignableFrom ( type ) ) { return Double . valueOf ( v ) ; } else if ( Boolean . TYPE . isAssignableFrom ( type ) ) { if ( "true" . equalsIgnoreCase ( v ) ) { return Boolean . TRUE ; } else if ( "false" . equalsIgnoreCase ( v ) ) { return Boolean . FALSE ; } } else if ( type . isEnum ( ) ) { return convertToEnum ( ca , v , ( Class < ? extends Enum < ? > > ) type ) ; } else if ( StringToObjectConverter . followsTheValueOfConvention ( type ) ) { return convertByValueOfMethod ( ca , type , v ) ; } else if ( isOfTypeCharset ( type ) ) { return convertToCharset ( ca , val ) ; } return null ; }


Input: returned value may be null and in most cases it is null . [CODESPLIT] 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 ; } }


Input: 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 . [CODESPLIT] 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 ; }


Input: { [CODESPLIT] @ Override protected RemoteAppenderClient createClient ( String id , Socket socket ) throws IOException { return new RemoteAppenderStreamClient ( id , socket ) ; }


Input: Add a new rule i . e . a pattern action pair to the rule store . <p > Note that the added action s LoggerRepository will be set in the process . [CODESPLIT] public void addRule ( ElementSelector elementSelector , Action action ) { action . setContext ( context ) ; List < Action > a4p = rules . get ( elementSelector ) ; if ( a4p == null ) { a4p = new ArrayList < Action > ( ) ; rules . put ( elementSelector , a4p ) ; } a4p . add ( action ) ; }


Input: match for x / y / * has higher priority than matches for x / * [CODESPLIT] public List < Action > matchActions ( ElementPath elementPath ) { List < Action > actionList ; if ( ( actionList = fullPathMatch ( elementPath ) ) != null ) { return actionList ; } else if ( ( actionList = suffixMatch ( elementPath ) ) != null ) { return actionList ; } else if ( ( actionList = prefixMatch ( elementPath ) ) != null ) { return actionList ; } else if ( ( actionList = middleMatch ( elementPath ) ) != null ) { return actionList ; } else { return null ; } }


Input: Suffix matches are matches of type * / x / y [CODESPLIT] List < Action > suffixMatch ( ElementPath elementPath ) { int max = 0 ; ElementSelector longestMatchingElementSelector = null ; for ( ElementSelector selector : rules . keySet ( ) ) { if ( isSuffixPattern ( selector ) ) { int r = selector . getTailMatchLength ( elementPath ) ; if ( r > max ) { max = r ; longestMatchingElementSelector = selector ; } } } if ( longestMatchingElementSelector != null ) { return rules . get ( longestMatchingElementSelector ) ; } else { return null ; } }


Input: Heuristically determines whether the current OS is Android [CODESPLIT] 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" ) ; }


Input: Package access for testing purposes . [CODESPLIT] 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 ) ; } }


Input: Return the set of files matching the stemRegex as found in directory . A stemRegex does not contain any slash characters or any folder separators . [CODESPLIT] 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 ) ; } } ) ; }


Input: { [CODESPLIT] public final void start ( ) { if ( isStarted ( ) ) return ; if ( getContext ( ) == null ) { throw new IllegalStateException ( "context not set" ) ; } if ( shouldStart ( ) ) { getContext ( ) . getScheduledExecutorService ( ) . execute ( getRunnableTask ( ) ) ; started = true ; } }


Input: { [CODESPLIT] public final void stop ( ) { if ( ! isStarted ( ) ) return ; try { onStop ( ) ; } catch ( RuntimeException ex ) { addError ( "on stop: " + ex , ex ) ; } started = false ; }


Input: { [CODESPLIT] @ Override public void start ( ) { try { SSLContext sslContext = getSsl ( ) . createContext ( this ) ; SSLParametersConfiguration parameters = getSsl ( ) . getParameters ( ) ; parameters . setContext ( getContext ( ) ) ; socketFactory = new ConfigurableSSLServerSocketFactory ( parameters , sslContext . getServerSocketFactory ( ) ) ; super . start ( ) ; } catch ( Exception ex ) { addError ( ex . getMessage ( ) , ex ) ; } }


Input: Print status messages retrospectively [CODESPLIT] 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 ) ; } } }


Input: Returns the integer value corresponding to the named syslog facility . [CODESPLIT] 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" ) ; } }


Input: The <b > Facility< / b > option must be set one of the strings KERN USER MAIL DAEMON AUTH SYSLOG LPR NEWS UUCP CRON AUTHPRIV FTP NTP AUDIT ALERT CLOCK LOCAL0 LOCAL1 LOCAL2 LOCAL3 LOCAL4 LOCAL5 LOCAL6 LOCAL7 . Case is not important . [CODESPLIT] public void setFacility ( String facilityStr ) { if ( facilityStr != null ) { facilityStr = facilityStr . trim ( ) ; } this . facilityStr = facilityStr ; }


Input: Determine if a node has already been visited already by checking the cycleDetectionStack for it s existence . This method is used -- rather than Stack . contains () -- because we want to ignore the Node s next attribute when comparing for equality . [CODESPLIT] private boolean haveVisitedNodeAlready ( Node node , Stack < Node > cycleDetectionStack ) { for ( Node cycleNode : cycleDetectionStack ) { if ( equalNodes ( node , cycleNode ) ) { return true ; } } return false ; }


Input: Gets a file object from a file path to a SQLite database [CODESPLIT] 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 ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void start ( ) { this . started = false ; File dbfile = getDatabaseFile ( this . filename ) ; if ( dbfile == null ) { addError ( "Cannot determine database filename" ) ; return ; } boolean dbOpened = false ; try { dbfile . getParentFile ( ) . mkdirs ( ) ; addInfo ( "db path: " + dbfile . getAbsolutePath ( ) ) ; this . db = SQLiteDatabase . openOrCreateDatabase ( dbfile . getPath ( ) , null ) ; dbOpened = true ; } catch ( SQLiteException e ) { addError ( "Cannot open database" , e ) ; } if ( dbOpened ) { if ( dbNameResolver == null ) { dbNameResolver = new DefaultDBNameResolver ( ) ; } insertExceptionSQL = SQLBuilder . buildInsertExceptionSQL ( dbNameResolver ) ; insertPropertiesSQL = SQLBuilder . buildInsertPropertiesSQL ( dbNameResolver ) ; insertSQL = SQLBuilder . buildInsertSQL ( dbNameResolver ) ; try { this . db . execSQL ( SQLBuilder . buildCreateLoggingEventTableSQL ( dbNameResolver ) ) ; this . db . execSQL ( SQLBuilder . buildCreatePropertyTableSQL ( dbNameResolver ) ) ; this . db . execSQL ( SQLBuilder . buildCreateExceptionTableSQL ( dbNameResolver ) ) ; clearExpiredLogs ( this . db ) ; super . start ( ) ; this . started = true ; } catch ( SQLiteException e ) { addError ( "Cannot create database tables" , e ) ; } } }


Input: Removes expired logs from the database [CODESPLIT] private void clearExpiredLogs ( SQLiteDatabase db ) { if ( lastCheckExpired ( this . maxHistory , this . lastCleanupTime ) ) { this . lastCleanupTime = this . clock . currentTimeMillis ( ) ; this . getLogCleaner ( ) . performLogCleanup ( db , this . maxHistory ) ; } }


Input: Determines whether it s time to clear expired logs [CODESPLIT] 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 ; }


Input: Gets the { [CODESPLIT] public SQLiteLogCleaner getLogCleaner ( ) { if ( this . logCleaner == null ) { final Clock thisClock = this . clock ; this . logCleaner = new SQLiteLogCleaner ( ) { public void performLogCleanup ( SQLiteDatabase db , Duration expiry ) { final long expiryMs = thisClock . currentTimeMillis ( ) - expiry . getMilliseconds ( ) ; final String deleteExpiredLogsSQL = SQLBuilder . buildDeleteExpiredLogsSQL ( dbNameResolver , expiryMs ) ; db . execSQL ( deleteExpiredLogsSQL ) ; } } ; } return this . logCleaner ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void append ( ILoggingEvent eventObject ) { if ( isStarted ( ) ) { try { clearExpiredLogs ( db ) ; SQLiteStatement stmt = db . compileStatement ( insertSQL ) ; try { db . beginTransaction ( ) ; long eventId = subAppend ( eventObject , stmt ) ; if ( eventId != - 1 ) { secondarySubAppend ( eventObject , eventId ) ; db . setTransactionSuccessful ( ) ; } } finally { if ( db . inTransaction ( ) ) { db . endTransaction ( ) ; } stmt . close ( ) ; } } catch ( Throwable e ) { addError ( "Cannot append event" , e ) ; } } }


Input: Inserts the main details of a log event into the database [CODESPLIT] 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 ; }


Input: Updates an existing row of an event with the secondary details of the event . This includes MDC properties and any exception information . [CODESPLIT] 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 ) ; } }


Input: Binds the main details of a log event to a SQLite statement s parameters [CODESPLIT] 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 ) ) ; }


Input: Binds a logging event s arguments ( e . g . <code > logger . debug ( x = {} y = {} arg1 arg2 ) < / code > ) to a SQLite statement s parameters [CODESPLIT] private void bindLoggingEventArguments ( SQLiteStatement stmt , Object [ ] argArray ) throws SQLException { int arrayLen = argArray != null ? argArray . length : 0 ; for ( int i = 0 ; i < arrayLen && i < 4 ; i ++ ) { stmt . bindString ( ARG0_INDEX + i , asStringTruncatedTo254 ( argArray [ i ] ) ) ; } // //    // set remaining columns to "" //    for (int i = arrayLen; i < 4; i++) { //      stmt.bindString(ARG0_INDEX+i, ""); //    } }


Input: Gets the first 254 characters of an object s string representation . This is used to truncate a logging event s argument binding if necessary . [CODESPLIT] 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 ; }


Input: Computes the reference mask for a logging event including flags to indicate whether MDC properties or exception info is available for the event . [CODESPLIT] 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 ; }


Input: 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 . [CODESPLIT] 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 ; }


Input: Updates an existing row with property details ( context properties and event s properties ) . [CODESPLIT] private void insertProperties ( Map < String , String > mergedMap , long eventId ) throws SQLException { if ( mergedMap . size ( ) > 0 ) { SQLiteStatement stmt = db . compileStatement ( insertPropertiesSQL ) ; try { for ( Entry < String , String > entry : mergedMap . entrySet ( ) ) { stmt . bindLong ( 1 , eventId ) ; stmt . bindString ( 2 , entry . getKey ( ) ) ; stmt . bindString ( 3 , entry . getValue ( ) ) ; stmt . executeInsert ( ) ; } } finally { stmt . close ( ) ; } } }


Input: Binds the calling function s details ( filename line etc . ) to a SQLite statement s arguments [CODESPLIT] private void bindCallerData ( SQLiteStatement stmt , StackTraceElement [ ] callerDataArray ) throws SQLException { if ( callerDataArray != null && callerDataArray . length > 0 ) { StackTraceElement callerData = callerDataArray [ 0 ] ; if ( callerData != null ) { bindString ( stmt , CALLER_FILENAME_INDEX , callerData . getFileName ( ) ) ; bindString ( stmt , CALLER_CLASS_INDEX , callerData . getClassName ( ) ) ; bindString ( stmt , CALLER_METHOD_INDEX , callerData . getMethodName ( ) ) ; bindString ( stmt , CALLER_LINE_INDEX , Integer . toString ( callerData . getLineNumber ( ) ) ) ; } } }


Input: Inserts an exception into the logging_exceptions table [CODESPLIT] 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 ( ) ; }


Input: 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 . [CODESPLIT] 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 ; }


Input: different status objects lying on the same cycle [CODESPLIT] 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 ; }


Input: Uses JavaBeans { [CODESPLIT] protected void introspect ( ) { try { propertyDescriptors = Introspector . getPropertyDescriptors ( this . objClass ) ; methodDescriptors = Introspector . getMethodDescriptors ( this . objClass ) ; } catch ( IntrospectionException ex ) { addError ( "Failed to introspect " + obj + ": " + ex . getMessage ( ) ) ; propertyDescriptors = new PropertyDescriptor [ 0 ] ; methodDescriptors = new MethodDescriptor [ 0 ] ; } }


Input: 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 . [CODESPLIT] 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 ) ; } } }


Input: Set the named property given a { @link PropertyDescriptor } . [CODESPLIT] public void setProperty ( PropertyDescriptor prop , String name , String value ) throws PropertySetterException { Method setter = prop . getWriteMethod ( ) ; if ( setter == null ) { throw new PropertySetterException ( "No setter for property [" + name + "]." ) ; } Class < ? > [ ] paramTypes = setter . getParameterTypes ( ) ; if ( paramTypes . length != 1 ) { throw new PropertySetterException ( "#params for setter != 1" ) ; } Object arg ; try { arg = StringToObjectConverter . convertArg ( this , value , paramTypes [ 0 ] ) ; } catch ( Throwable t ) { throw new PropertySetterException ( "Conversion to type [" + paramTypes [ 0 ] + "] failed. " , t ) ; } if ( arg == null ) { throw new PropertySetterException ( "Conversion to type [" + paramTypes [ 0 ] + "] failed." ) ; } try { setter . invoke ( obj , arg ) ; } catch ( Exception ex ) { throw new PropertySetterException ( ex ) ; } }


Input: Can the given clazz instantiable with certainty? [CODESPLIT] 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 ; } }


Input: Returns the string true if the { @link #setResource ( String ) resource } specified by the user is available on the class path false otherwise . [CODESPLIT] public String getPropertyValue ( ) { if ( OptionHelper . isEmpty ( resourceStr ) ) { addError ( "The \"resource\" property must be set." ) ; return null ; } URL resourceURL = Loader . getResourceBySelfClassLoader ( resourceStr ) ; return booleanAsStr ( resourceURL != null ) ; }


Input: Child threads should get a copy of the parent s hashmap . [CODESPLIT] @ Override protected HashMap < String , String > childValue ( HashMap < String , String > parentValue ) { if ( parentValue == null ) { return null ; } else { return new HashMap < String , String > ( parentValue ) ; } }


Input: Eopt = E|~ [CODESPLIT] private Node Eopt ( ) throws ScanException { Token next = peekAtCurentToken ( ) ; if ( next == null ) { return null ; } else { return E ( ) ; } }


Input: T = LITERAL | $ { V } [CODESPLIT] private Node T ( ) throws ScanException { Token t = peekAtCurentToken ( ) ; switch ( t . type ) { case LITERAL : advanceTokenPointer ( ) ; return makeNewLiteralNode ( t . payload ) ; case CURLY_LEFT : advanceTokenPointer ( ) ; Node innerNode = C ( ) ; Token right = peekAtCurentToken ( ) ; expectCurlyRight ( right ) ; advanceTokenPointer ( ) ; Node curlyLeft = makeNewLiteralNode ( CoreConstants . LEFT_ACCOLADE ) ; curlyLeft . append ( innerNode ) ; curlyLeft . append ( makeNewLiteralNode ( CoreConstants . RIGHT_ACCOLADE ) ) ; return curlyLeft ; case START : advanceTokenPointer ( ) ; Node v = V ( ) ; Token w = peekAtCurentToken ( ) ; expectCurlyRight ( w ) ; advanceTokenPointer ( ) ; return v ; default : return null ; } }


Input: V = E ( : = E|~ ) [CODESPLIT] private Node V ( ) throws ScanException { Node e = E ( ) ; Node variable = new Node ( Node . Type . VARIABLE , e ) ; Token t = peekAtCurentToken ( ) ; if ( isDefaultToken ( t ) ) { advanceTokenPointer ( ) ; Node def = E ( ) ; variable . defaultPart = def ; } return variable ; }


Input: C = E ( : = E|~ ) [CODESPLIT] private Node C ( ) throws ScanException { Node e0 = E ( ) ; Token t = peekAtCurentToken ( ) ; if ( isDefaultToken ( t ) ) { advanceTokenPointer ( ) ; Node literal = makeNewLiteralNode ( CoreConstants . DEFAULT_VALUE_SEPARATOR ) ; e0 . append ( literal ) ; Node e1 = E ( ) ; e0 . append ( e1 ) ; } return e0 ; }


Input: Processes an include [CODESPLIT] @ 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 ) ; } }


Input: Opens the given URL logging any exceptions [CODESPLIT] private InputStream openURL ( URL url ) { try { return url . openStream ( ) ; } catch ( IOException e ) { optionalWarning ( "Failed to open [" + url . toString ( ) + "]" , e ) ; return null ; } }


Input: Removes the head tag and tail tag if they are named either included or configuration [CODESPLIT] 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 ) ; } } } }


Input: Gets the event name of a { [CODESPLIT] private String getEventName ( SaxEvent event ) { return event . qName . length ( ) > 0 ? event . qName : event . localName ; }


Input: Starts the server . [CODESPLIT] 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 ; } }


Input: { [CODESPLIT] protected void onStop ( ) { try { if ( runner == null ) return ; runner . stop ( ) ; } catch ( IOException ex ) { addError ( "server shutdown error: " + ex , ex ) ; } }


Input: Test whether this error is transient . [CODESPLIT] 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 ; } }


Input: Set the default hosts for Algolia Places . [CODESPLIT] 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 ) ; }


Input: Search for places . [CODESPLIT] public Request searchAsync ( @ NonNull PlacesQuery params , @ NonNull CompletionHandler completionHandler ) { final PlacesQuery paramsCopy = new PlacesQuery ( params ) ; return new AsyncTaskRequest ( completionHandler ) { @ Override protected @ NonNull JSONObject run ( ) throws AlgoliaException { return search ( paramsCopy ) ; } } . start ( ) ; }


Input: Search for places . [CODESPLIT] protected JSONObject search ( @ NonNull PlacesQuery params ) throws AlgoliaException { try { JSONObject body = new JSONObject ( ) . put ( "params" , params . build ( ) ) ; return postRequest ( "/1/places/query" , /* urlParameters: */ null , body . toString ( ) , true /* readOperation */ , /* requestOptions: */ null ) ; } catch ( JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } }


Input: Get a place by its objectID . [CODESPLIT] public JSONObject getByObjectID ( @ NonNull String objectID ) throws AlgoliaException { return getRequest ( "/1/places/" + objectID , /* urlParameters: */ null , false , /* requestOptions: */ null ) ; }


Input: Add a data selection query to this index . NOTE : All queries are implicitly browse queries ( and not search queries ) . [CODESPLIT] public void addDataSelectionQuery ( @ NonNull DataSelectionQuery query ) { mirrorSettings . addQuery ( query ) ; mirrorSettings . setQueriesModificationDate ( new Date ( ) ) ; saveMirrorSettings ( ) ; }


Input: Replace all data selection queries associated to this index . [CODESPLIT] public void setDataSelectionQueries ( @ NonNull DataSelectionQuery ... queries ) { DataSelectionQuery [ ] oldQueries = mirrorSettings . getQueries ( ) ; if ( ! Arrays . equals ( oldQueries , queries ) ) { mirrorSettings . setQueries ( queries ) ; mirrorSettings . setQueriesModificationDate ( new Date ( ) ) ; saveMirrorSettings ( ) ; } }


Input: Set the delay after which data is considered to be obsolete . [CODESPLIT] public void setDelayBetweenSyncs ( long duration , @ NonNull TimeUnit unit ) { this . setDelayBetweenSyncs ( TimeUnit . MILLISECONDS . convert ( duration , unit ) ) ; }


Input: Lazy instantiate the local index . [CODESPLIT] private synchronized void ensureLocalIndex ( ) { if ( localIndex == null ) { localIndex = new LocalIndex ( getClient ( ) . getRootDataDir ( ) . getAbsolutePath ( ) , getClient ( ) . getApplicationID ( ) , getRawIndexName ( ) ) ; } }


Input: ---------------------------------------------------------------------- [CODESPLIT] private void saveMirrorSettings ( ) { File dataDir = getDataDir ( ) ; if ( ! dataDir . exists ( ) ) { dataDir . mkdirs ( ) ; } mirrorSettings . save ( getSettingsFile ( ) ) ; }


Input: Launch a sync . If a sync is already running this call is ignored . Otherwise the sync is enqueued and runs in the background . [CODESPLIT] 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 ( ) ; } } ) ; }


Input: 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 . [CODESPLIT] public void syncIfNeeded ( ) { long currentDate = System . currentTimeMillis ( ) ; if ( currentDate - mirrorSettings . getLastSyncDate ( ) . getTime ( ) > delayBetweenSyncs || mirrorSettings . getQueriesModificationDate ( ) . compareTo ( mirrorSettings . getLastSyncDate ( ) ) > 0 ) { sync ( ) ; } }


Input: Refresh the local mirror . WARNING : Should be called from a background thread . [CODESPLIT] private void _sync ( ) { if ( ! mirrored ) throw new IllegalArgumentException ( "Mirroring not activated on this index" ) ; // Reset statistics. stats = new SyncStats ( ) ; long startTime = System . currentTimeMillis ( ) ; // Notify listeners. getClient ( ) . completionExecutor . execute ( new Runnable ( ) { @ Override public void run ( ) { fireSyncDidStart ( ) ; } } ) ; try { // Create temporary directory. tmpDir = new File ( getClient ( ) . getTempDir ( ) , UUID . randomUUID ( ) . toString ( ) ) ; tmpDir . mkdirs ( ) ; // NOTE: We are doing everything sequentially, because this is a background job: we care more about // resource consumption than about how long it will take. // Fetch settings. { JSONObject settingsJSON = this . getSettings ( 1 , /* requestOptions: */ null ) ; settingsFile = new File ( tmpDir , "settings.json" ) ; String data = settingsJSON . toString ( ) ; Writer writer = new OutputStreamWriter ( new FileOutputStream ( settingsFile ) , "UTF-8" ) ; writer . write ( data ) ; writer . close ( ) ; } // Perform data selection queries. objectFiles = new ArrayList <> ( ) ; final DataSelectionQuery [ ] queries = mirrorSettings . getQueries ( ) ; for ( DataSelectionQuery query : queries ) { String cursor = null ; int retrievedObjects = 0 ; do { // Make next request. JSONObject objectsJSON = cursor == null ? this . browse ( query . query , /* requestOptions: */ null ) : this . browseFrom ( cursor , /* requestOptions: */ null ) ; // Write result to file. int objectFileNo = objectFiles . size ( ) ; File file = new File ( tmpDir , String . format ( "%d.json" , objectFileNo ) ) ; objectFiles . add ( file ) ; String data = objectsJSON . toString ( ) ; Writer writer = new OutputStreamWriter ( new FileOutputStream ( file ) , "UTF-8" ) ; writer . write ( data ) ; writer . close ( ) ; cursor = objectsJSON . optString ( "cursor" , null ) ; JSONArray hits = objectsJSON . optJSONArray ( "hits" ) ; if ( hits == null ) { // Something went wrong: // Report the error, and just abort this batch and proceed with the next query. Log . e ( this . getClass ( ) . getName ( ) , "No hits in result for query: " + query . query ) ; break ; } retrievedObjects += hits . length ( ) ; } while ( retrievedObjects < query . maxObjects && cursor != null ) ; stats . objectCount += retrievedObjects ; } // Update statistics. long afterFetchTime = System . currentTimeMillis ( ) ; stats . fetchTime = afterFetchTime - startTime ; stats . fileCount = objectFiles . size ( ) ; // Build the index. _buildOffline ( settingsFile , objectFiles . toArray ( new File [ objectFiles . size ( ) ] ) ) ; // Update statistics. long afterBuildTime = System . currentTimeMillis ( ) ; stats . buildTime = afterBuildTime - afterFetchTime ; stats . totalTime = afterBuildTime - startTime ; // Remember the last sync date. mirrorSettings . setLastSyncDate ( new Date ( ) ) ; saveMirrorSettings ( ) ; // Log statistics. Log . d ( this . getClass ( ) . getName ( ) , "Sync stats: " + stats ) ; } catch ( Exception e ) { Log . e ( this . getClass ( ) . getName ( ) , "Sync failed" , e ) ; error = e ; } finally { // Clean up. if ( tmpDir != null ) { FileUtils . deleteRecursive ( tmpDir ) ; tmpDir = null ; } settingsFile = null ; objectFiles = null ; // Mark sync as finished. synchronized ( this ) { syncing = false ; } // Notify listeners. getClient ( ) . completionExecutor . execute ( new Runnable ( ) { @ Override public void run ( ) { fireSyncDidFinish ( ) ; } } ) ; } }


Input: Search the online API falling back to the local mirror if enabled in case of error . [CODESPLIT] @ Override public Request searchAsync ( @ NonNull Query query , @ Nullable RequestOptions requestOptions , @ NonNull CompletionHandler completionHandler ) { // A non-mirrored index behaves exactly as an online index. if ( ! mirrored ) { return super . searchAsync ( query , requestOptions , completionHandler ) ; } // A mirrored index launches a mixed offline/online request. else { final Query queryCopy = new Query ( query ) ; return new OnlineOfflineSearchRequest ( queryCopy , requestOptions , completionHandler ) . start ( ) ; } }


Input: Search the online API . [CODESPLIT] public Request searchOnlineAsync ( @ NonNull Query query , @ NonNull final CompletionHandler completionHandler ) { return searchOnlineAsync ( query , /* requestOptions: */ null , completionHandler ) ; }


Input: Search the online API . [CODESPLIT] public Request searchOnlineAsync ( @ NonNull Query query , @ Nullable final RequestOptions requestOptions , @ NonNull final CompletionHandler completionHandler ) { final Query queryCopy = new Query ( query ) ; return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return searchOnline ( queryCopy , requestOptions ) ; } } . start ( ) ; }


Input: ---------------------------------------------------------------------- [CODESPLIT] @ Override public Request multipleQueriesAsync ( @ NonNull Collection < Query > queries , final Client . MultipleQueriesStrategy strategy , @ Nullable RequestOptions requestOptions , @ NonNull CompletionHandler completionHandler ) { // A non-mirrored index behaves exactly as an online index. if ( ! mirrored ) { return super . multipleQueriesAsync ( queries , strategy , completionHandler ) ; } // A mirrored index launches a mixed offline/online request. else { final List < Query > queriesCopy = new ArrayList <> ( queries . size ( ) ) ; for ( Query query : queries ) { queriesCopy . add ( new Query ( query ) ) ; } return new OnlineOfflineMultipleQueriesRequest ( queriesCopy , strategy , requestOptions , completionHandler ) . start ( ) ; } }


Input: Run multiple queries on this index explicitly targeting the online API . [CODESPLIT] public Request multipleQueriesOnlineAsync ( @ NonNull List < Query > queries , final Client . MultipleQueriesStrategy strategy , final @ NonNull CompletionHandler completionHandler ) { return multipleQueriesAsync ( queries , /* requestOptions: */ null , completionHandler ) ; }


Input: Run multiple queries on this index explicitly targeting the online API . [CODESPLIT] public Request multipleQueriesOnlineAsync ( @ NonNull List < Query > queries , final Client . MultipleQueriesStrategy strategy , @ Nullable final RequestOptions requestOptions , final @ NonNull CompletionHandler completionHandler ) { final List < Query > queriesCopy = new ArrayList <> ( queries . size ( ) ) ; for ( Query query : queries ) { queriesCopy . add ( new Query ( query ) ) ; } return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return multipleQueriesOnline ( queriesCopy , strategy == null ? null : strategy . toString ( ) , requestOptions ) ; } } . start ( ) ; }


Input: Run multiple queries on this index explicitly targeting the offline mirror . [CODESPLIT] public Request multipleQueriesOfflineAsync ( final @ NonNull List < Query > queries , final Client . MultipleQueriesStrategy strategy , @ NonNull CompletionHandler completionHandler ) { if ( ! mirrored ) { throw new IllegalStateException ( "Offline requests are only available when the index is mirrored" ) ; } final List < Query > queriesCopy = new ArrayList <> ( queries . size ( ) ) ; for ( Query query : queries ) { queriesCopy . add ( new Query ( query ) ) ; } return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . localSearchExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return _multipleQueriesOffline ( queriesCopy , strategy == null ? null : strategy . toString ( ) ) ; } } . start ( ) ; }


Input: Run multiple queries on this index explicitly targeting the online API . [CODESPLIT] private JSONObject multipleQueriesOnline ( @ NonNull List < Query > queries , String strategy , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { JSONObject content = super . multipleQueries ( queries , strategy , requestOptions ) ; content . put ( JSON_KEY_ORIGIN , JSON_VALUE_ORIGIN_REMOTE ) ; return content ; } catch ( JSONException e ) { throw new AlgoliaException ( "Failed to patch JSON result" ) ; } }


Input: Run multiple queries on this index explicitly targeting the offline mirror . [CODESPLIT] private JSONObject _multipleQueriesOffline ( @ NonNull List < Query > queries , String strategy ) throws AlgoliaException { if ( ! mirrored ) { throw new IllegalStateException ( "Cannot run offline search on a non-mirrored index" ) ; } return new MultipleQueryEmulator ( this . getRawIndexName ( ) ) { @ Override protected JSONObject singleQuery ( @ NonNull Query query ) throws AlgoliaException { return _searchOffline ( query ) ; } } . multipleQueries ( queries , strategy ) ; }


Input: Browse the local mirror ( initial call ) . Same semantics as { @link Index#browseAsync } . [CODESPLIT] public Request browseMirrorAsync ( @ NonNull Query query , @ NonNull CompletionHandler completionHandler ) { if ( ! mirrored ) { throw new IllegalStateException ( "Mirroring not activated on this index" ) ; } final Query queryCopy = new Query ( query ) ; return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . localSearchExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return _browseMirror ( queryCopy ) ; } } . start ( ) ; }


Input: Browse the local mirror ( subsequent calls ) . Same semantics as { @link Index#browseFromAsync } . [CODESPLIT] public Request browseMirrorFromAsync ( @ NonNull String cursor , @ NonNull CompletionHandler completionHandler ) { if ( ! mirrored ) { throw new IllegalStateException ( "Mirroring not activated on this index" ) ; } final Query query = new Query ( ) . set ( "cursor" , cursor ) ; return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . localSearchExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return _browseMirror ( query ) ; } } . start ( ) ; }


Input: Get an individual object from the online API falling back to the local mirror in case of error ( when enabled ) . [CODESPLIT] @ Override public Request getObjectAsync ( final @ NonNull String objectID , final @ Nullable Collection < String > attributesToRetrieve , @ Nullable RequestOptions requestOptions , @ NonNull CompletionHandler completionHandler ) { if ( ! mirrored ) { return super . getObjectAsync ( objectID , attributesToRetrieve , requestOptions , completionHandler ) ; } else { return new OnlineOfflineGetObjectRequest ( objectID , new ArrayList ( attributesToRetrieve ) , requestOptions , completionHandler ) . start ( ) ; } }


Input: Get an individual object explicitly targeting the online API not the offline mirror . [CODESPLIT] public Request getObjectOnlineAsync ( @ NonNull final String objectID , final @ Nullable List < String > attributesToRetrieve , @ NonNull final CompletionHandler completionHandler ) { return getObjectOnlineAsync ( objectID , attributesToRetrieve , /* requestOptions: */ null , completionHandler ) ; }


Input: Get an individual object explicitly targeting the online API not the offline mirror . [CODESPLIT] public Request getObjectOnlineAsync ( @ NonNull final String objectID , final @ Nullable List < String > attributesToRetrieve , @ Nullable RequestOptions requestOptions , @ NonNull final CompletionHandler completionHandler ) { // TODO: Cannot perform origin tagging because it could conflict with the object's attributes return super . getObjectAsync ( objectID , attributesToRetrieve , requestOptions , completionHandler ) ; }


Input: Get an individual object explicitly targeting the online API not the offline mirror . [CODESPLIT] public Request getObjectOnlineAsync ( @ NonNull final String objectID , @ NonNull final CompletionHandler completionHandler ) { return getObjectOnlineAsync ( objectID , /* attributesToRetrieve: */ null , /* requestOptions: */ null , completionHandler ) ; }


Input: Get an individual object explicitly targeting the offline mirror not the online API . [CODESPLIT] public Request getObjectOfflineAsync ( @ NonNull final String objectID , final @ Nullable List < String > attributesToRetrieve , @ NonNull CompletionHandler completionHandler ) { if ( ! mirrored ) { throw new IllegalStateException ( "Mirroring not activated on this index" ) ; } return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . localSearchExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return _getObjectOffline ( objectID , attributesToRetrieve ) ; } } . start ( ) ; }


Input: Get an individual object explicitly targeting the offline mirror not the online API . [CODESPLIT] public Request getObjectOfflineAsync ( @ NonNull final String objectID , @ NonNull final CompletionHandler completionHandler ) { return getObjectOfflineAsync ( objectID , null , completionHandler ) ; }


Input: Get individual objects from the online API falling back to the local mirror in case of error ( when enabled ) . [CODESPLIT] @ Override public Request getObjectsAsync ( final @ NonNull Collection < String > objectIDs , final @ Nullable Collection < String > attributesToRetrieve , @ Nullable RequestOptions requestOptions , @ NonNull CompletionHandler completionHandler ) { if ( ! mirrored ) { return super . getObjectsAsync ( objectIDs , attributesToRetrieve , requestOptions , completionHandler ) ; } else { return new OnlineOfflineGetObjectsRequest ( new ArrayList ( objectIDs ) , new ArrayList ( attributesToRetrieve ) , requestOptions , completionHandler ) . start ( ) ; } }


Input: Get individual objects explicitly targeting the online API not the offline mirror . [CODESPLIT] public Request getObjectsOnlineAsync ( @ NonNull final List < String > objectIDs , final @ Nullable List < String > attributesToRetrieve , @ NonNull final CompletionHandler completionHandler ) { return getObjectsOnlineAsync ( objectIDs , attributesToRetrieve , /* requestOptions: */ null , completionHandler ) ; }


Input: Get individual objects explicitly targeting the online API not the offline mirror . [CODESPLIT] public Request getObjectsOnlineAsync ( @ NonNull final List < String > objectIDs , final @ Nullable List < String > attributesToRetrieve , @ Nullable final RequestOptions requestOptions , @ NonNull final CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return getObjectsOnline ( objectIDs , attributesToRetrieve , requestOptions ) ; } } . start ( ) ; }


Input: Get individual objects explicitly targeting the online API not the offline mirror . [CODESPLIT] public Request getObjectsOnlineAsync ( @ NonNull final List < String > objectIDs , @ NonNull final CompletionHandler completionHandler ) { return getObjectsOnlineAsync ( objectIDs , /* attributesToRetrieve: */ null , /* requestOptions: */ null , completionHandler ) ; }


Input: Get individual objects explicitly targeting the offline mirror not the online API . [CODESPLIT] public Request getObjectsOfflineAsync ( @ NonNull final List < String > objectIDs , final @ Nullable List < String > attributesToRetrieve , @ NonNull CompletionHandler completionHandler ) { if ( ! mirrored ) { throw new IllegalStateException ( "Mirroring not activated on this index" ) ; } return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . localSearchExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return _getObjectsOffline ( objectIDs , attributesToRetrieve ) ; } } . start ( ) ; }


Input: Get individual objects explicitly targeting the offline mirror not the online API . [CODESPLIT] public Request getObjectsOfflineAsync ( @ NonNull final List < String > objectIDs , @ NonNull final CompletionHandler completionHandler ) { return getObjectsOfflineAsync ( objectIDs , null , completionHandler ) ; }


Input: ---------------------------------------------------------------------- [CODESPLIT] @ Override public Request searchForFacetValuesAsync ( @ NonNull String facetName , @ NonNull String text , @ Nullable Query query , @ Nullable RequestOptions requestOptions , @ NonNull final CompletionHandler completionHandler ) { // A non-mirrored index behaves exactly as an online index. if ( ! mirrored ) { return super . searchForFacetValuesAsync ( facetName , text , query , requestOptions , completionHandler ) ; } // A mirrored index launches a mixed offline/online request. else { final Query queryCopy = query != null ? new Query ( query ) : null ; return new MixedFacetSearchRequest ( facetName , text , queryCopy , requestOptions , completionHandler ) . start ( ) ; } }


Input: Search for facet values explicitly targeting the online API not the offline mirror . Same parameters as { [CODESPLIT] public Request searchForFacetValuesOnline ( @ NonNull String facetName , @ NonNull String text , @ Nullable Query query , @ NonNull final CompletionHandler completionHandler ) { return searchForFacetValuesOnline ( facetName , text , query , /* requestOptions: */ null , completionHandler ) ; }


Input: Search for facet values explicitly targeting the online API not the offline mirror . Same parameters as { [CODESPLIT] public Request searchForFacetValuesOnline ( @ NonNull String facetName , @ NonNull String text , @ Nullable Query query , @ Nullable RequestOptions requestOptions , @ NonNull final CompletionHandler completionHandler ) { return super . searchForFacetValuesAsync ( facetName , text , query , requestOptions , new CompletionHandler ( ) { @ Override public void requestCompleted ( JSONObject content , AlgoliaException error ) { try { if ( content != null ) content . put ( JSON_KEY_ORIGIN , JSON_VALUE_ORIGIN_REMOTE ) ; } catch ( JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } completionHandler . requestCompleted ( content , error ) ; } } ) ; }


Input: Search for facet values explicitly targeting the offline mirror not the online API . [CODESPLIT] public Request searchForFacetValuesOffline ( final @ NonNull String facetName , final @ NonNull String text , @ Nullable Query query , @ NonNull final CompletionHandler completionHandler ) { if ( ! mirrored ) { throw new IllegalStateException ( "Offline requests are only available when the index is mirrored" ) ; } final Query queryCopy = query != null ? new Query ( query ) : null ; return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . localSearchExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return _searchForFacetValuesOffline ( facetName , text , queryCopy ) ; } } . start ( ) ; }


Input: Searches inside this index ( asynchronously ) . [CODESPLIT] public Request searchAsync ( @ Nullable Query query , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { final Query queryCopy = query != null ? new Query ( query ) : new Query ( ) ; return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return search ( queryCopy , requestOptions ) ; } } . start ( ) ; }


Input: Searches inside this index ( synchronously ) . [CODESPLIT] public JSONObject searchSync ( @ Nullable Query query , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { return search ( query , requestOptions ) ; }


Input: Run multiple queries on this index with one API call . A variant of { @link Client#multipleQueriesAsync ( List Client . MultipleQueriesStrategy CompletionHandler ) } where the targeted index is always the receiver . [CODESPLIT] public Request multipleQueriesAsync ( final @ NonNull Collection < Query > queries , final Client . MultipleQueriesStrategy strategy , @ Nullable CompletionHandler completionHandler ) { return multipleQueriesAsync ( queries , strategy , /* requestOptions: */ null , completionHandler ) ; }


Input: Searches inside this index synchronously . [CODESPLIT] protected byte [ ] searchSyncRaw ( @ NonNull Query query , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { return searchRaw ( query , requestOptions ) ; }


Input: Perform a search with disjunctive facets generating as many queries as number of disjunctive facets ( helper ) . [CODESPLIT] @ Override public Request searchDisjunctiveFacetingAsync ( @ NonNull Query query , @ NonNull final Collection < String > disjunctiveFacets , @ NonNull final Map < String , ? extends Collection < String > > refinements , @ Nullable final RequestOptions requestOptions , @ NonNull final CompletionHandler completionHandler ) { return new DisjunctiveFaceting ( ) { @ Override protected Request multipleQueriesAsync ( @ NonNull Collection < Query > queries , @ Nullable CompletionHandler completionHandler ) { return Index . this . multipleQueriesAsync ( queries , null , requestOptions , completionHandler ) ; } } . searchDisjunctiveFacetingAsync ( query , disjunctiveFacets , refinements , completionHandler ) ; }


Input: Perform a search with disjunctive facets generating as many queries as number of disjunctive facets ( helper ) . [CODESPLIT] public Request searchDisjunctiveFacetingAsync ( @ NonNull Query query , @ NonNull final Collection < String > disjunctiveFacets , @ NonNull final Map < String , ? extends Collection < String > > refinements , @ NonNull final CompletionHandler completionHandler ) { return searchDisjunctiveFacetingAsync ( query , disjunctiveFacets , refinements , /* requestOptions: */ null , completionHandler ) ; }