idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
5,700
private int getHeaderViewType ( int position ) { if ( headerContent != null ) { if ( headerContent . getData ( ) == getItem ( position ) && ( position == 0 ) ) { return headerContent . getViewtype ( ) ; } } return PeasyHeaderViewHolder . VIEWTYPE_NOTHING ; }
To identify content as Header
70
5
5,701
public int getFooterViewType ( int position ) { if ( footerContent != null ) { if ( footerContent . getData ( ) == getItem ( position ) && ( position == getLastItemIndex ( ) ) ) { return footerContent . getViewtype ( ) ; } } return PeasyHeaderViewHolder . VIEWTYPE_NOTHING ; }
To identify content as Footer
79
6
5,702
public boolean onItemLongClick ( final View view , final int viewType , final int position , final T item , final PeasyViewHolder viewHolder ) { return true ; }
Indicate content is clicked with long tap
39
8
5,703
@ SuppressWarnings ( { "PMD.NcssCount" , "PMD.UseStringBufferForStringAppends" } ) public static boolean sendStaticContent ( HttpRequest request , IOSubchannel channel , Function < String , URL > resolver , MaxAgeCalculator maxAgeCalculator ) { String path = request . requestUri ( ) . getPath ( ) ; URL resourceUrl = resolver . apply ( path ) ; ResourceInfo info ; URLConnection resConn ; InputStream resIn ; try { if ( resourceUrl == null ) { throw new IOException ( ) ; } info = ResponseCreationSupport . resourceInfo ( resourceUrl ) ; if ( Boolean . TRUE . equals ( info . isDirectory ( ) ) ) { throw new IOException ( ) ; } resConn = resourceUrl . openConnection ( ) ; resIn = resConn . getInputStream ( ) ; } catch ( IOException e1 ) { try { if ( ! path . endsWith ( "/" ) ) { path += "/" ; } path += "index.html" ; resourceUrl = resolver . apply ( path ) ; if ( resourceUrl == null ) { return false ; } info = ResponseCreationSupport . resourceInfo ( resourceUrl ) ; resConn = resourceUrl . openConnection ( ) ; resIn = resConn . getInputStream ( ) ; } catch ( IOException e2 ) { return false ; } } HttpResponse response = request . response ( ) . get ( ) ; response . setField ( HttpField . LAST_MODIFIED , Optional . ofNullable ( info . getLastModifiedAt ( ) ) . orElseGet ( ( ) -> Instant . now ( ) ) ) ; // Get content type and derive max age MediaType mediaType = HttpResponse . contentType ( ResponseCreationSupport . uriFromUrl ( resourceUrl ) ) ; setMaxAge ( response , ( maxAgeCalculator == null ? DEFAULT_MAX_AGE_CALCULATOR : maxAgeCalculator ) . maxAge ( request , mediaType ) ) ; // Check if sending is really required. Optional < Instant > modifiedSince = request . findValue ( HttpField . IF_MODIFIED_SINCE , Converters . DATE_TIME ) ; if ( modifiedSince . isPresent ( ) && info . getLastModifiedAt ( ) != null && ! info . getLastModifiedAt ( ) . isAfter ( modifiedSince . get ( ) ) ) { response . setStatus ( HttpStatus . NOT_MODIFIED ) ; channel . respond ( new Response ( response ) ) ; } else { response . setContentType ( mediaType ) ; response . setStatus ( HttpStatus . OK ) ; channel . respond ( new Response ( response ) ) ; // Start sending content (Output events as resonses) ( new InputStreamPipeline ( resIn , channel ) . suppressClose ( ) ) . run ( ) ; } return true ; }
Creates and sends a response with static content . The content is looked up by invoking the resolver with the path from the request .
635
27
5,704
@ SuppressWarnings ( "PMD.EmptyCatchBlock" ) public static ResourceInfo resourceInfo ( URL resource ) { try { Path path = Paths . get ( resource . toURI ( ) ) ; return new ResourceInfo ( Files . isDirectory ( path ) , Files . getLastModifiedTime ( path ) . toInstant ( ) . with ( ChronoField . NANO_OF_SECOND , 0 ) ) ; } catch ( FileSystemNotFoundException | IOException | URISyntaxException e ) { // Fall through } if ( "jar" . equals ( resource . getProtocol ( ) ) ) { try { JarURLConnection conn = ( JarURLConnection ) resource . openConnection ( ) ; JarEntry entry = conn . getJarEntry ( ) ; return new ResourceInfo ( entry . isDirectory ( ) , entry . getLastModifiedTime ( ) . toInstant ( ) . with ( ChronoField . NANO_OF_SECOND , 0 ) ) ; } catch ( IOException e ) { // Fall through } } try { URLConnection conn = resource . openConnection ( ) ; long lastModified = conn . getLastModified ( ) ; if ( lastModified != 0 ) { return new ResourceInfo ( null , Instant . ofEpochMilli ( lastModified ) . with ( ChronoField . NANO_OF_SECOND , 0 ) ) ; } } catch ( IOException e ) { // Fall through } return new ResourceInfo ( null , null ) ; }
Attempts to lookup the additional resource information for the given URL .
325
12
5,705
public static long setMaxAge ( HttpResponse response , int maxAge ) { List < Directive > directives = new ArrayList <> ( ) ; directives . add ( new Directive ( "max-age" , maxAge ) ) ; response . setField ( HttpField . CACHE_CONTROL , directives ) ; return maxAge ; }
Sets the cache control header in the given response .
74
11
5,706
public void setSelection ( List < GraphUser > graphUsers ) { List < String > userIds = new ArrayList < String > ( ) ; for ( GraphUser graphUser : graphUsers ) { userIds . add ( graphUser . getId ( ) ) ; } setSelectionByIds ( userIds ) ; }
Sets the list of friends for pre selection . These friends will be selected by default .
71
18
5,707
private void authorize ( Activity activity , String [ ] permissions , int activityCode , SessionLoginBehavior behavior , final DialogListener listener ) { checkUserSession ( "authorize" ) ; pendingOpeningSession = new Session . Builder ( activity ) . setApplicationId ( mAppId ) . setTokenCachingStrategy ( getTokenCache ( ) ) . build ( ) ; pendingAuthorizationActivity = activity ; pendingAuthorizationPermissions = ( permissions != null ) ? permissions : new String [ 0 ] ; StatusCallback callback = new StatusCallback ( ) { @ Override public void call ( Session callbackSession , SessionState state , Exception exception ) { // Invoke user-callback. onSessionCallback ( callbackSession , state , exception , listener ) ; } } ; Session . OpenRequest openRequest = new Session . OpenRequest ( activity ) . setCallback ( callback ) . setLoginBehavior ( behavior ) . setRequestCode ( activityCode ) . setPermissions ( Arrays . asList ( pendingAuthorizationPermissions ) ) ; openSession ( pendingOpeningSession , openRequest , pendingAuthorizationPermissions . length > 0 ) ; }
Full authorize method .
236
4
5,708
private boolean validateServiceIntent ( Context context , Intent intent ) { ResolveInfo resolveInfo = context . getPackageManager ( ) . resolveService ( intent , 0 ) ; if ( resolveInfo == null ) { return false ; } return validateAppSignatureForPackage ( context , resolveInfo . serviceInfo . packageName ) ; }
Helper to validate a service intent by resolving and checking the provider s package signature .
69
16
5,709
private boolean validateAppSignatureForPackage ( Context context , String packageName ) { PackageInfo packageInfo ; try { packageInfo = context . getPackageManager ( ) . getPackageInfo ( packageName , PackageManager . GET_SIGNATURES ) ; } catch ( NameNotFoundException e ) { return false ; } for ( Signature signature : packageInfo . signatures ) { if ( signature . toCharsString ( ) . equals ( FB_APP_SIGNATURE ) ) { return true ; } } return false ; }
Query the signature for the application that would be invoked by the given intent and verify that it matches the FB application s signature .
107
25
5,710
@ SuppressWarnings ( "deprecation" ) String requestImpl ( String graphPath , Bundle params , String httpMethod ) throws FileNotFoundException , MalformedURLException , IOException { params . putString ( "format" , "json" ) ; if ( isSessionValid ( ) ) { params . putString ( TOKEN , getAccessToken ( ) ) ; } String url = ( graphPath != null ) ? GRAPH_BASE_URL + graphPath : RESTSERVER_URL ; return Util . openUrl ( url , httpMethod , params ) ; }
Internal call to avoid deprecated warnings .
127
7
5,711
@ Deprecated public void setSession ( Session session ) { if ( session == null ) { throw new IllegalArgumentException ( "session cannot be null" ) ; } synchronized ( this . lock ) { this . userSetSession = session ; } }
Allows the user to set a Session for the Facebook class to use . If a Session is set here then one should not use the authorize logout or extendAccessToken methods which alter the Session object since that may result in undefined behavior . Using those methods after setting the session here will result in exceptions being thrown .
52
62
5,712
@ Deprecated public final Session getSession ( ) { while ( true ) { String cachedToken = null ; Session oldSession = null ; synchronized ( this . lock ) { if ( userSetSession != null ) { return userSetSession ; } if ( ( session != null ) || ! sessionInvalidated ) { return session ; } cachedToken = accessToken ; oldSession = session ; } if ( cachedToken == null ) { return null ; } // At this point we do not have a valid session, but mAccessToken is // non-null. // So we can try building a session based on that. List < String > permissions ; if ( oldSession != null ) { permissions = oldSession . getPermissions ( ) ; } else if ( pendingAuthorizationPermissions != null ) { permissions = Arrays . asList ( pendingAuthorizationPermissions ) ; } else { permissions = Collections . < String > emptyList ( ) ; } Session newSession = new Session . Builder ( pendingAuthorizationActivity ) . setApplicationId ( mAppId ) . setTokenCachingStrategy ( getTokenCache ( ) ) . build ( ) ; if ( newSession . getState ( ) != SessionState . CREATED_TOKEN_LOADED ) { return null ; } Session . OpenRequest openRequest = new Session . OpenRequest ( pendingAuthorizationActivity ) . setPermissions ( permissions ) ; openSession ( newSession , openRequest , ! permissions . isEmpty ( ) ) ; Session invalidatedSession = null ; Session returnSession = null ; synchronized ( this . lock ) { if ( sessionInvalidated || ( session == null ) ) { invalidatedSession = session ; returnSession = session = newSession ; sessionInvalidated = false ; } } if ( invalidatedSession != null ) { invalidatedSession . close ( ) ; } if ( returnSession != null ) { return returnSession ; } // Else token state changed between the synchronized blocks, so // retry.. } }
Get the underlying Session object to use with 3 . 0 api .
411
13
5,713
@ Handler public void onStart ( Start event ) { synchronized ( this ) { if ( runner != null && ! runner . isInterrupted ( ) ) { return ; } runner = new Thread ( this , Components . simpleObjectName ( this ) ) ; runner . start ( ) ; } }
Starts this dispatcher . A dispatcher has an associated thread that keeps it running .
60
16
5,714
@ Handler ( priority = - 10000 ) public void onStop ( Stop event ) throws InterruptedException { synchronized ( this ) { if ( runner == null ) { return ; } // It just might happen that the wakeup() occurs between the // check for running and the select() in the thread's run loop, // but we -- obviously -- cannot put the select() in a // synchronized(this). while ( runner . isAlive ( ) ) { runner . interrupt ( ) ; // *Should* be sufficient, but... selector . wakeup ( ) ; // Make sure runner . join ( 10 ) ; } runner = null ; } }
Stops the thread that is associated with this dispatcher .
132
11
5,715
@ Handler public void onNioRegistration ( NioRegistration event ) throws IOException { SelectableChannel channel = event . ioChannel ( ) ; channel . configureBlocking ( false ) ; SelectionKey key ; synchronized ( selectorGate ) { selector . wakeup ( ) ; // make sure selector isn't blocking key = channel . register ( selector , event . ops ( ) , event . handler ( ) ) ; } event . setResult ( new Registration ( key ) ) ; }
Handle the NIO registration .
98
6
5,716
private DataContainer innerJoin ( DataContainer left , DataContainer right , Optional < BooleanExpression > joinCondition ) { return crossJoin ( left , right , joinCondition , JoinType . INNER ) ; }
A naive implementation filtering cross join by condition
43
8
5,717
@ SuppressWarnings ( "PMD.DataflowAnomalyAnalysis" ) protected static String derivePattern ( String path ) { String pattern ; if ( "/" . equals ( path ) ) { pattern = "/**" ; } else { String patternBase = path ; if ( patternBase . endsWith ( "/" ) ) { patternBase = path . substring ( 0 , path . length ( ) - 1 ) ; } pattern = path + "," + path + "/**" ; } return pattern ; }
Derives the resource pattern from the path .
108
9
5,718
protected String createSessionId ( HttpResponse response ) { StringBuilder sessionIdBuilder = new StringBuilder ( ) ; byte [ ] bytes = new byte [ 16 ] ; secureRandom . nextBytes ( bytes ) ; for ( byte b : bytes ) { sessionIdBuilder . append ( Integer . toHexString ( b & 0xff ) ) ; } String sessionId = sessionIdBuilder . toString ( ) ; HttpCookie sessionCookie = new HttpCookie ( idName ( ) , sessionId ) ; sessionCookie . setPath ( path ) ; sessionCookie . setHttpOnly ( true ) ; response . computeIfAbsent ( HttpField . SET_COOKIE , CookieList :: new ) . value ( ) . add ( sessionCookie ) ; response . computeIfAbsent ( HttpField . CACHE_CONTROL , CacheControlDirectives :: new ) . value ( ) . add ( new Directive ( "no-cache" , "SetCookie, Set-Cookie2" ) ) ; return sessionId ; }
Creates a session id and adds the corresponding cookie to the response .
225
14
5,719
@ Handler ( channels = Channel . class ) public void discard ( DiscardSession event ) { removeSession ( event . session ( ) . id ( ) ) ; }
Discards the given session .
34
6
5,720
@ Handler ( priority = 1000 ) public void onProtocolSwitchAccepted ( ProtocolSwitchAccepted event , IOSubchannel channel ) { event . requestEvent ( ) . associated ( Session . class ) . ifPresent ( session -> { channel . setAssociated ( Session . class , session ) ; } ) ; }
Associates the channel with the session from the upgrade request .
65
13
5,721
@ Handler public void onOpenConnection ( OpenTcpConnection event ) { try { SocketChannel socketChannel = SocketChannel . open ( event . address ( ) ) ; channels . add ( new TcpChannelImpl ( socketChannel ) ) ; } catch ( ConnectException e ) { fire ( new ConnectError ( event , "Connection refused." , e ) ) ; } catch ( IOException e ) { fire ( new ConnectError ( event , "Failed to open TCP connection." , e ) ) ; } }
Opens a connection to the end point specified in the event .
105
13
5,722
@ Handler ( channels = Self . class ) public void onRegistered ( NioRegistration . Completed event ) throws InterruptedException , IOException { NioHandler handler = event . event ( ) . handler ( ) ; if ( ! ( handler instanceof TcpChannelImpl ) ) { return ; } if ( event . event ( ) . get ( ) == null ) { fire ( new Error ( event , "Registration failed, no NioDispatcher?" , new Throwable ( ) ) ) ; return ; } TcpChannelImpl channel = ( TcpChannelImpl ) handler ; channel . registrationComplete ( event . event ( ) ) ; channel . downPipeline ( ) . fire ( new Connected ( channel . nioChannel ( ) . getLocalAddress ( ) , channel . nioChannel ( ) . getRemoteAddress ( ) ) , channel ) ; }
Called when the new socket channel has successfully been registered with the nio dispatcher .
180
17
5,723
@ Handler @ SuppressWarnings ( "PMD.DataflowAnomalyAnalysis" ) public void onClose ( Close event ) throws IOException , InterruptedException { for ( Channel channel : event . channels ( ) ) { if ( channel instanceof TcpChannelImpl && channels . contains ( channel ) ) { ( ( TcpChannelImpl ) channel ) . close ( ) ; } } }
Shuts down the one of the connections .
83
9
5,724
@ Override public Validator newValidator ( String identifier ) { if ( identifier == null ) { return null ; } ValidatorFactory template ; synchronized ( map ) { verifyMapIntegrity ( ) ; template = map . get ( identifier ) ; } if ( template != null ) { try { return template . newValidator ( identifier ) ; } catch ( ValidatorFactoryException e ) { logger . log ( Level . WARNING , "Failed to create validator." , e ) ; return null ; } } else { return null ; } }
Obtains a new instance of a Validator with the given identifier
113
13
5,725
@ SuppressWarnings ( { "PMD.CyclomaticComplexity" , "PMD.NPathComplexity" , "PMD.CollapsibleIfStatements" , "PMD.DataflowAnomalyAnalysis" } ) public int matches ( URI resource ) { if ( protocol != null && ! protocol . equals ( "*" ) ) { if ( resource . getScheme ( ) == null ) { return - 1 ; } if ( Arrays . stream ( protocol . split ( "," ) ) . noneMatch ( proto -> proto . equals ( resource . getScheme ( ) ) ) ) { return - 1 ; } } if ( host != null && ! host . equals ( "*" ) ) { if ( resource . getHost ( ) == null || ! resource . getHost ( ) . equals ( host ) ) { return - 1 ; } } if ( port != null && ! port . equals ( "*" ) ) { if ( Integer . parseInt ( port ) != resource . getPort ( ) ) { return - 1 ; } } String [ ] reqElements = PathSpliterator . stream ( resource . getPath ( ) ) . skip ( 1 ) . toArray ( size -> new String [ size ] ) ; String [ ] reqElementsPlus = null ; // Created lazily for ( int pathIdx = 0 ; pathIdx < pathPatternElements . length ; pathIdx ++ ) { String [ ] pathPattern = pathPatternElements [ pathIdx ] ; if ( prefixSegs [ pathIdx ] == pathPattern . length - 1 && lastIsEmpty ( pathPattern ) ) { // Special case, pattern ends with vertical bar if ( reqElementsPlus == null ) { reqElementsPlus = reqElements ; if ( ! lastIsEmpty ( reqElementsPlus ) ) { reqElementsPlus = Arrays . copyOf ( reqElementsPlus , reqElementsPlus . length + 1 ) ; reqElementsPlus [ reqElementsPlus . length - 1 ] = "" ; } } if ( matchPath ( pathPattern , reqElementsPlus ) ) { return prefixSegs [ pathIdx ] ; } } else { if ( matchPath ( pathPattern , reqElements ) ) { return prefixSegs [ pathIdx ] ; } } } return - 1 ; }
Matches the given resource URI against the pattern .
498
10
5,726
public static boolean matches ( String pattern , URI resource ) throws ParseException { return ( new ResourcePattern ( pattern ) ) . matches ( resource ) >= 0 ; }
Matches the given pattern against the given resource URI .
34
11
5,727
@ RequestHandler ( dynamic = true ) public void onGet ( Request . In . Get event , IOSubchannel channel ) throws ParseException , IOException { int prefixSegs = resourcePattern . matches ( event . requestUri ( ) ) ; if ( prefixSegs < 0 ) { return ; } if ( contentDirectory == null ) { getFromUri ( event , channel , prefixSegs ) ; } else { getFromFileSystem ( event , channel , prefixSegs ) ; } }
Handles a GET request .
106
6
5,728
@ Handler @ SuppressWarnings ( "PMD.SystemPrintln" ) public void onInput ( Input < ByteBuffer > event ) { String data = Charset . defaultCharset ( ) . decode ( event . data ( ) ) . toString ( ) ; System . out . print ( data ) ; if ( data . trim ( ) . equals ( "QUIT" ) ) { fire ( new Stop ( ) ) ; } }
Handle input .
95
3
5,729
public ConfigurationUpdate removePath ( String path ) { if ( path == null || ! path . startsWith ( "/" ) ) { throw new IllegalArgumentException ( "Path must start with \"/\"." ) ; } paths . put ( path , null ) ; return this ; }
Remove a path from the configuration .
59
7
5,730
public Optional < Map < String , String > > values ( String path ) { Map < String , String > result = paths . get ( path ) ; if ( result == null ) { return Optional . empty ( ) ; } return Optional . of ( Collections . unmodifiableMap ( result ) ) ; }
Return the values for a given path if they exists .
63
11
5,731
public Optional < String > value ( String path , String key ) { return Optional . ofNullable ( paths . get ( path ) ) . flatMap ( map -> Optional . ofNullable ( map . get ( key ) ) ) ; }
Return the value with the given path and key if it exists .
50
13
5,732
public static boolean isRange ( String value ) { if ( value == null ) { return false ; } try { Set < Integer > values = parseRange ( value ) ; return values . size ( ) > 0 ; } catch ( Exception e ) { return false ; } }
Returns whether passed value is a range
56
7
5,733
public static void disableSSLValidation ( ) { try { SSLContext context = SSLContext . getInstance ( "SSL" ) ; context . init ( null , new TrustManager [ ] { new UnsafeTrustManager ( ) } , null ) ; HttpsURLConnection . setDefaultSSLSocketFactory ( context . getSocketFactory ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Disabling SSL validation is strongly discouraged . This is generally only intended for use during testing or perhaps when used in a private network with a self signed certificate .
90
31
5,734
public static void enableSSLValidation ( ) { try { SSLContext . getInstance ( "SSL" ) . init ( null , null , null ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Enable SSL Validation .
49
5
5,735
public static boolean validCertificateString ( String certificateString ) { try { byte [ ] certBytes = parseDERFromPEM ( certificateString , CERT_START , CERT_END ) ; generateCertificateFromDER ( certBytes ) ; } catch ( Exception e ) { return false ; } return true ; }
Checks the given certificate String to ensure it is a PEM formatted certificate .
67
16
5,736
public RESTClient < RS , ERS > urlParameter ( String name , Object value ) { if ( value == null ) { return this ; } List < Object > values = this . parameters . get ( name ) ; if ( values == null ) { values = new ArrayList <> ( ) ; this . parameters . put ( name , values ) ; } if ( value instanceof ZonedDateTime ) { values . add ( ( ( ZonedDateTime ) value ) . toInstant ( ) . toEpochMilli ( ) ) ; } else if ( value instanceof Collection ) { values . addAll ( ( Collection ) value ) ; } else { values . add ( value ) ; } return this ; }
Add a URL parameter as a key value pair .
149
10
5,737
@ Override protected Enumeration < URL > findResources ( String name ) { URL url = findResource ( name ) ; Vector < URL > urls = new Vector <> ( ) ; if ( url != null ) { urls . add ( url ) ; } return urls . elements ( ) ; }
Returns an enumeration of URL objects representing all the resources with th given name .
65
16
5,738
public void unsetUserConfigurations ( UserConfigurationsProvider provider ) { if ( userConfigurations . isPresent ( ) && userConfigurations . get ( ) . equals ( provider ) ) { this . userConfigurations = Optional . empty ( ) ; } }
Unset reference added automatically from setUserConfigurations annotation
54
11
5,739
public Attribute getAttribute ( final String attributeName ) { final Attribute a = attributes . get ( attributeName ) ; if ( a == null ) throw new IllegalArgumentException ( "Attribute " + attributeName + " doesn't exists" ) ; return a ; }
Returns the attribute with the given name . Throws an IllegalArgumentException if there is no such attribute .
56
22
5,740
public void addAttributeValue ( final String attributeName , final Value attributeValue , Environment in ) { if ( in == null ) in = GlobalEnvironment . INSTANCE ; Attribute attr = attributes . get ( attributeName ) ; if ( attr == null ) { attr = new Attribute ( attributeName ) ; attributes . put ( attr . getName ( ) , attr ) ; } attr . addValue ( attributeValue , in ) ; Map < String , Object > valueMap = contentMap . get ( in ) ; if ( valueMap == null ) valueMap = new HashMap <> ( ) ; valueMap . put ( attributeName , attributeValue . getRaw ( ) ) ; contentMap . put ( in , valueMap ) ; //TODO check for loops and process such situation if ( attributeValue instanceof IncludeValue ) externalConfigurations . add ( ( ( IncludeValue ) attributeValue ) . getConfigName ( ) ) ; }
Adds an attribute value . If the attribute doesn t exist it will be created .
201
16
5,741
@ Handler public void onClose ( Close event , WebAppMsgChannel appChannel ) throws InterruptedException { appChannel . handleClose ( event ) ; }
Handles a close event from downstream by closing the upstream connections .
32
13
5,742
@ Handler ( priority = Integer . MIN_VALUE ) public void onOptions ( Request . In . Options event , IOSubchannel appChannel ) { if ( event . requestUri ( ) == HttpRequest . ASTERISK_REQUEST ) { HttpResponse response = event . httpRequest ( ) . response ( ) . get ( ) ; response . setStatus ( HttpStatus . OK ) ; appChannel . respond ( new Response ( response ) ) ; event . setResult ( true ) ; event . stop ( ) ; } }
Provides a fallback handler for an OPTIONS request with asterisk . Simply responds with OK .
114
20
5,743
public Matcher matcher ( CharSequence s ) { Matcher m = new Matcher ( this ) ; m . setTarget ( s ) ; return m ; }
Returns a matcher for a specified string .
35
9
5,744
public Matcher matcher ( char [ ] data , int start , int end ) { Matcher m = new Matcher ( this ) ; m . setTarget ( data , start , end ) ; return m ; }
Returns a matcher for a specified region .
45
9
5,745
public Matcher matcher ( MatchResult res , String groupName ) { Integer id = res . pattern ( ) . groupId ( groupName ) ; if ( id == null ) throw new IllegalArgumentException ( "group not found:" + groupName ) ; int group = id ; return matcher ( res , group ) ; }
Just as above yet with symbolic group name .
69
9
5,746
public List < ColumnRelation > toList ( ) { List < ColumnRelation > ret = new ArrayList <> ( ) ; ret . add ( this ) ; if ( getNextRelation ( ) . isPresent ( ) ) { ret . addAll ( getNextRelation ( ) . get ( ) . toList ( ) ) ; } return ret ; }
Returns a chain of column relations as list
77
8
5,747
public static void addToDataSource ( DataSource parent , DataSource child ) { if ( ! parent . getLeftDataSource ( ) . isPresent ( ) ) { parent . setLeftDataSource ( child ) ; } else if ( ! parent . getRightDataSource ( ) . isPresent ( ) ) { parent . setRightDataSource ( child ) ; } else { DataSource newLeftDataSource = new DataSource ( parent . getLeftDataSource ( ) . get ( ) ) ; newLeftDataSource . setRightDataSource ( parent . getRightDataSource ( ) . get ( ) ) ; parent . setLeftDataSource ( newLeftDataSource ) ; parent . setRightDataSource ( child ) ; } }
Builds optimized data source as a tree
152
8
5,748
@ Override public String format ( LogRecord logRecord ) { StringBuilder resultBuilder = new StringBuilder ( ) ; String prefix = logRecord . getLevel ( ) . getName ( ) + "\t" ; resultBuilder . append ( prefix ) ; resultBuilder . append ( Thread . currentThread ( ) . getName ( ) ) . append ( " " ) . append ( sdf . format ( new java . util . Date ( logRecord . getMillis ( ) ) ) ) . append ( ": " ) . append ( logRecord . getSourceClassName ( ) ) . append ( ":" ) . append ( logRecord . getSourceMethodName ( ) ) . append ( ": " ) . append ( logRecord . getMessage ( ) ) ; Object [ ] params = logRecord . getParameters ( ) ; if ( params != null ) { resultBuilder . append ( "\nParameters:" ) ; if ( params . length < 1 ) { resultBuilder . append ( " (none)" ) ; } else { for ( int paramIndex = 0 ; paramIndex < params . length ; paramIndex ++ ) { Object param = params [ paramIndex ] ; if ( param != null ) { String paramString = param . toString ( ) ; resultBuilder . append ( "\nParameter " ) . append ( String . valueOf ( paramIndex ) ) . append ( " is a " ) . append ( param . getClass ( ) . getName ( ) ) . append ( ": >" ) . append ( paramString ) . append ( "<" ) ; } else { resultBuilder . append ( "\nParameter " ) . append ( String . valueOf ( paramIndex ) ) . append ( " is null." ) ; } } } } Throwable t = logRecord . getThrown ( ) ; if ( t != null ) { resultBuilder . append ( "\nThrowing:\n" ) . append ( getFullThrowableMsg ( t ) ) ; } String result = resultBuilder . toString ( ) . replaceAll ( "\n" , "\n" + prefix ) + "\n" ; return result ; }
Format a logging message
444
4
5,749
public boolean acceptsValue ( String value ) { if ( value == null ) { return false ; } else if ( hasValues ( ) ) { return getValuesList ( ) . contains ( value ) ; } else { return true ; } }
Returns true if this option accepts the specified value
49
9
5,750
private static String getUrl ( int method , String baseUrl , String endpoint , Map < String , String > params ) { if ( params != null ) { for ( Map . Entry < String , String > entry : params . entrySet ( ) ) { if ( entry . getValue ( ) == null || entry . getValue ( ) . equals ( "null" ) ) { entry . setValue ( "" ) ; } } } if ( method == Method . GET && params != null && ! params . isEmpty ( ) ) { final StringBuilder result = new StringBuilder ( baseUrl + endpoint ) ; final int startLength = result . length ( ) ; for ( String key : params . keySet ( ) ) { try { final String encodedKey = URLEncoder . encode ( key , "UTF-8" ) ; final String encodedValue = URLEncoder . encode ( params . get ( key ) , "UTF-8" ) ; if ( result . length ( ) > startLength ) { result . append ( "&" ) ; } else { result . append ( "?" ) ; } result . append ( encodedKey ) ; result . append ( "=" ) ; result . append ( encodedValue ) ; } catch ( Exception e ) { } } return result . toString ( ) ; } else { return baseUrl + endpoint ; } }
Converts a base URL endpoint and parameters into a full URL
283
12
5,751
public static boolean configure ( File configFile ) { boolean goOn = true ; if ( ! configFile . exists ( ) ) { LogHelperDebug . printError ( "File " + configFile . getAbsolutePath ( ) + " does not exist" , false ) ; goOn = false ; } DocumentBuilderFactory documentBuilderFactory = null ; DocumentBuilder documentBuilder = null ; if ( goOn ) { documentBuilderFactory = DocumentBuilderFactory . newInstance ( ) ; try { documentBuilder = documentBuilderFactory . newDocumentBuilder ( ) ; } catch ( ParserConfigurationException ex ) { LogHelperDebug . printError ( ex . getMessage ( ) , ex , false ) ; goOn = false ; } } Document configDocument = null ; if ( goOn ) { try { configDocument = documentBuilder . parse ( configFile ) ; } catch ( SAXException ex ) { LogHelperDebug . printError ( ex . getMessage ( ) , ex , false ) ; goOn = false ; } catch ( IOException ex ) { LogHelperDebug . printError ( ex . getMessage ( ) , ex , false ) ; goOn = false ; } } NodeList configNodeList = null ; if ( goOn ) { configNodeList = configDocument . getElementsByTagName ( "log-helper" ) ; if ( configNodeList == null ) { LogHelperDebug . printError ( "configNodeList is null" , false ) ; goOn = false ; } else if ( configNodeList . getLength ( ) < 1 ) { LogHelperDebug . printError ( "configNodeList is empty" , false ) ; goOn = false ; } } Node configNode = null ; if ( goOn ) { configNode = configNodeList . item ( 0 ) ; if ( configNode == null ) { LogHelperDebug . printError ( "configNode is null" , false ) ; goOn = false ; } } boolean success = false ; if ( goOn ) { success = configure ( configNode ) ; } return success ; }
Configure the log - helper library to the values in the given XML config file
431
16
5,752
private static void configureLoggerWrapper ( Node configNode ) { Node lwNameNode = configNode . getAttributes ( ) . getNamedItem ( "name" ) ; String lwName ; if ( lwNameNode != null ) { lwName = lwNameNode . getTextContent ( ) ; } else { lwName = "LoggerWrapper_" + String . valueOf ( ( new Date ( ) ) . getTime ( ) ) ; } LoggerWrapper loggerWrapper = LogHelper . getLoggerWrapper ( lwName ) ; NodeList lwSubnodes = configNode . getChildNodes ( ) ; for ( int subnodeIndex = 0 ; subnodeIndex < lwSubnodes . getLength ( ) ; subnodeIndex ++ ) { Node subnode = lwSubnodes . item ( subnodeIndex ) ; String subnodeName = subnode . getNodeName ( ) . trim ( ) . toLowerCase ( ) ; if ( subnodeName . equals ( "configurator" ) ) { configureLoggerWrapperByConfigurator ( loggerWrapper , subnode ) ; } } }
Configure a LoggerWrapper to the values of a DOM node . It MUST have an attribute named name storing the LoggerWrapper s name . It may have subnodes named configurator keeping the properties for
250
45
5,753
public PermitsPool removeListener ( AvailabilityListener listener ) { synchronized ( listeners ) { for ( Iterator < WeakReference < AvailabilityListener > > iter = listeners . iterator ( ) ; iter . hasNext ( ) ; ) { WeakReference < AvailabilityListener > item = iter . next ( ) ; if ( item . get ( ) == null || item . get ( ) == listener ) { iter . remove ( ) ; } } } return this ; }
Removes the listener .
92
5
5,754
public static String className ( Class < ? > clazz ) { if ( CoreUtils . classNames . isLoggable ( Level . FINER ) ) { return clazz . getName ( ) ; } else { return simpleClassName ( clazz ) ; } }
Returns the full name or simple name of the class depending on the log level .
58
16
5,755
public static Timer schedule ( TimeoutHandler timeoutHandler , Instant scheduledFor ) { return scheduler . schedule ( timeoutHandler , scheduledFor ) ; }
Schedules the given timeout handler for the given instance .
31
12
5,756
public static Timer schedule ( TimeoutHandler timeoutHandler , Duration scheduledFor ) { return scheduler . schedule ( timeoutHandler , Instant . now ( ) . plus ( scheduledFor ) ) ; }
Schedules the given timeout handler for the given offset from now .
40
14
5,757
@ Deprecated public static String encodePostBody ( Bundle parameters , String boundary ) { if ( parameters == null ) return "" ; StringBuilder sb = new StringBuilder ( ) ; for ( String key : parameters . keySet ( ) ) { Object parameter = parameters . get ( key ) ; if ( ! ( parameter instanceof String ) ) { continue ; } sb . append ( "Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n" + ( String ) parameter ) ; sb . append ( "\r\n" + "--" + boundary + "\r\n" ) ; } return sb . toString ( ) ; }
Generate the multi - part post body providing the parameters and boundary string
148
14
5,758
@ Deprecated public static Bundle parseUrl ( String url ) { // hack to prevent MalformedURLException url = url . replace ( "fbconnect" , "http" ) ; try { URL u = new URL ( url ) ; Bundle b = decodeUrl ( u . getQuery ( ) ) ; b . putAll ( decodeUrl ( u . getRef ( ) ) ) ; return b ; } catch ( MalformedURLException e ) { return new Bundle ( ) ; } }
Parse a URL query and fragment parameters into a key - value bundle .
104
15
5,759
public static String getAttachmentUrl ( String applicationId , UUID callId , String attachmentName ) { return String . format ( "%s%s/%s/%s" , ATTACHMENT_URL_BASE , applicationId , callId . toString ( ) , attachmentName ) ; }
Returns the name of the content provider formatted correctly for constructing URLs .
64
13
5,760
@ Deprecated public Character set ( final int index , final Character ok ) { return set ( index , ok . charValue ( ) ) ; }
Delegates to the corresponding type - specific method .
30
10
5,761
private void getElements ( final int from , final char [ ] a , final int offset , final int length ) { CharArrays . ensureOffsetLength ( a , offset , length ) ; System . arraycopy ( this . a , from , a , offset , length ) ; }
Copies element of this type - specific list into the given array using optimized system calls .
59
18
5,762
public void removeElements ( final int from , final int to ) { CharArrays . ensureFromTo ( size , from , to ) ; System . arraycopy ( a , to , a , from , size - to ) ; size -= ( to - from ) ; }
Removes elements of this type - specific list using optimized system calls .
57
14
5,763
public void addElements ( final int index , final char a [ ] , final int offset , final int length ) { ensureIndex ( index ) ; CharArrays . ensureOffsetLength ( a , offset , length ) ; grow ( size + length ) ; System . arraycopy ( this . a , index , this . a , index + length , size - index ) ; System . arraycopy ( a , offset , this . a , index , length ) ; size += length ; }
Adds elements to this type - specific list using optimized system calls .
100
13
5,764
private void ensureIndex ( final int index ) { if ( index < 0 ) throw new IndexOutOfBoundsException ( "Index (" + index + ") is negative" ) ; if ( index > size ( ) ) throw new IndexOutOfBoundsException ( "Index (" + index + ") is greater than list size (" + ( size ( ) ) + ")" ) ; }
Ensures that the given index is non - negative and not greater than the list size .
81
19
5,765
protected void ensureRestrictedIndex ( final int index ) { if ( index < 0 ) throw new IndexOutOfBoundsException ( "Index (" + index + ") is negative" ) ; if ( index >= size ( ) ) throw new IndexOutOfBoundsException ( "Index (" + index + ") is greater than or equal to list size (" + ( size ( ) ) + ")" ) ; }
Ensures that the given index is non - negative and smaller than the list size .
86
18
5,766
public boolean containsAll ( Collection < ? > c ) { int n = c . size ( ) ; final Iterator < ? > i = c . iterator ( ) ; while ( n -- != 0 ) if ( ! contains ( i . next ( ) ) ) return false ; return true ; }
Checks whether this collection contains all elements from the given collection .
61
13
5,767
public boolean addAll ( Collection < ? extends Character > c ) { boolean retVal = false ; final Iterator < ? extends Character > i = c . iterator ( ) ; int n = c . size ( ) ; while ( n -- != 0 ) if ( add ( i . next ( ) ) ) retVal = true ; return retVal ; }
Adds all elements of the given collection to this collection .
73
11
5,768
public synchronized Set < ConfigurationDetails > getConfigurationDetails ( ) { return inventory . entries ( ) . stream ( ) . map ( c -> c . getConfiguration ( ) . orElse ( null ) ) . filter ( v -> v != null ) . map ( v -> v . getDetails ( ) ) . collect ( Collectors . toSet ( ) ) ; }
Gets configuration details .
75
5
5,769
public synchronized Map < String , Object > getConfiguration ( String key ) { return Optional . ofNullable ( inventory . get ( key ) ) . flatMap ( v -> v . getConfiguration ( ) ) . map ( v -> v . getMap ( ) ) . orElse ( null ) ; }
Gets a configuration .
62
5
5,770
public synchronized Optional < String > addConfiguration ( String niceName , String description , Map < String , Object > config ) { try { if ( catalog == null ) { throw new FileNotFoundException ( ) ; } return sync ( ( ) -> { ConfigurationDetails p = new ConfigurationDetails . Builder ( inventory . nextIdentifier ( ) ) . niceName ( niceName ) . description ( description ) . build ( ) ; try { InventoryEntry ret = InventoryEntry . create ( new Configuration ( p , new HashMap <> ( config ) ) , newConfigurationFile ( ) ) ; inventory . add ( ret ) ; return Optional . of ( ret . getIdentifier ( ) ) ; } catch ( IOException e ) { logger . log ( Level . WARNING , "Failed to add configuration." , e ) ; return Optional . empty ( ) ; } } ) ; } catch ( IOException e ) { logger . log ( Level . WARNING , "Could not add configuration" , e ) ; return Optional . empty ( ) ; } }
Adds a configuration to this catalog .
213
7
5,771
public synchronized boolean removeConfiguration ( String key ) { try { if ( catalog == null ) { throw new FileNotFoundException ( ) ; } return sync ( ( ) -> inventory . remove ( key ) != null ) ; } catch ( IOException e ) { logger . log ( Level . WARNING , "Failed to remove configuration." , e ) ; return false ; } }
Removes the configuration with the specified identifier .
77
9
5,772
private boolean cleanupInventory ( ) { boolean modified = false ; modified |= removeUnreadable ( ) ; modified |= recreateMismatching ( ) ; modified |= importConfigurations ( ) ; return modified ; }
Cleans up the inventory .
45
6
5,773
private boolean removeUnreadable ( ) { List < File > unreadable = inventory . removeUnreadable ( ) ; unreadable . forEach ( v -> v . delete ( ) ) ; return ! unreadable . isEmpty ( ) ; }
Removes unreadable configurations from the file system .
49
10
5,774
private boolean recreateMismatching ( ) { List < Configuration > mismatching = inventory . removeMismatching ( ) ; mismatching . forEach ( entry -> { try { inventory . add ( InventoryEntry . create ( entry . copyWithIdentifier ( inventory . nextIdentifier ( ) ) , newConfigurationFile ( ) ) ) ; } catch ( IOException e1 ) { logger . log ( Level . WARNING , "Failed to write a configuration." , e1 ) ; } } ) ; return ! mismatching . isEmpty ( ) ; }
Recreates mismatching configurations .
114
7
5,775
private boolean importConfigurations ( ) { // Create a set of files in the inventory Set < File > files = inventory . entries ( ) . stream ( ) . map ( v -> v . getPath ( ) ) . collect ( Collectors . toSet ( ) ) ; List < File > entriesToImport = Arrays . asList ( baseDir . listFiles ( f -> f . isFile ( ) && ! f . equals ( catalog ) // Exclude the master catalog (should it have the same extension as entries) && f . getName ( ) . endsWith ( CONFIG_EXT ) && ! files . contains ( f ) ) // Exclude files already in the inventory ) ; entriesToImport . forEach ( f -> { try { inventory . add ( InventoryEntry . create ( Configuration . read ( f ) . copyWithIdentifier ( inventory . nextIdentifier ( ) ) , newConfigurationFile ( ) ) ) ; f . delete ( ) ; } catch ( IOException e ) { if ( logger . isLoggable ( Level . FINE ) ) { logger . log ( Level . FINE , "Failed to read: " + f , e ) ; } } } ) ; return ! entriesToImport . isEmpty ( ) ; }
Imports new configurations from the file system .
261
9
5,776
@ SuppressWarnings ( { "unchecked" , "PMD.ShortVariable" , "PMD.AvoidDuplicateLiterals" } ) public < C > C [ ] channels ( Class < C > type ) { return Arrays . stream ( channels ) . filter ( c -> type . isAssignableFrom ( c . getClass ( ) ) ) . toArray ( size -> ( C [ ] ) Array . newInstance ( type , size ) ) ; }
Returns the subset of channels that are assignable to the given type .
102
14
5,777
@ SuppressWarnings ( { "unchecked" , "PMD.ShortVariable" } ) public < E extends EventBase < ? > , C extends Channel > void forChannels ( Class < C > type , BiConsumer < E , C > handler ) { Arrays . stream ( channels ) . filter ( c -> type . isAssignableFrom ( c . getClass ( ) ) ) . forEach ( c -> handler . accept ( ( E ) this , ( C ) c ) ) ; }
Execute the given handler for all channels of the given type .
108
13
5,778
public Event < T > setResult ( T result ) { synchronized ( this ) { if ( results == null ) { // Make sure that we have a valid result before // calling decrementOpen results = new ArrayList < T > ( ) ; results . add ( result ) ; firstResultAssigned ( ) ; return this ; } results . add ( result ) ; return this ; } }
Sets the result of handling this event . If this method is invoked more then once the various results are collected in a list . This can happen if the event is handled by several components .
80
38
5,779
protected List < T > currentResults ( ) { return results == null ? Collections . emptyList ( ) : Collections . unmodifiableList ( results ) ; }
Allows access to the intermediate result before the completion of the event .
33
13
5,780
public static View inflateView ( LayoutInflater inflater , ViewGroup parent , int layoutId ) { return inflater . inflate ( layoutId , parent , false ) ; }
Static method to help inflate parent view with layoutId
39
11
5,781
public static < VH extends PeasyViewHolder > VH GetViewHolder ( PeasyViewHolder vh , Class < VH > cls ) { return cls . cast ( vh ) ; }
Help to cast provided PeasyViewHolder to its child class instance
47
14
5,782
< T > void bindWith ( final PeasyRecyclerView < T > binder , final int viewType ) { this . itemView . setOnClickListener ( new View . OnClickListener ( ) { @ Override public void onClick ( View v ) { int position = getLayoutPosition ( ) ; position = ( position <= binder . getLastItemIndex ( ) ) ? position : getAdapterPosition ( ) ; position = ( position <= binder . getLastItemIndex ( ) ) ? position : RecyclerView . NO_POSITION ; if ( position != RecyclerView . NO_POSITION ) { binder . onItemClick ( v , viewType , position , binder . getItem ( position ) , getInstance ( ) ) ; } } } ) ; this . itemView . setOnLongClickListener ( new View . OnLongClickListener ( ) { @ Override public boolean onLongClick ( View v ) { int position = getLayoutPosition ( ) ; position = ( position <= binder . getLastItemIndex ( ) ) ? position : getAdapterPosition ( ) ; position = ( position <= binder . getLastItemIndex ( ) ) ? position : RecyclerView . NO_POSITION ; if ( getLayoutPosition ( ) != RecyclerView . NO_POSITION ) { return binder . onItemLongClick ( v , viewType , position , binder . getItem ( position ) , getInstance ( ) ) ; } return false ; } } ) ; }
Will bind onClick and setOnLongClickListener here
321
11
5,783
@ SuppressWarnings ( "PMD.UseVarargs" ) public void fire ( Event < ? > event , Channel [ ] channels ) { eventPipeline . add ( event , channels ) ; }
Forward to the thread s event manager .
45
8
5,784
@ SuppressWarnings ( "PMD.UseVarargs" ) /* default */ void dispatch ( EventPipeline pipeline , EventBase < ? > event , Channel [ ] channels ) { HandlerList handlers = getEventHandlers ( event , channels ) ; handlers . process ( pipeline , event ) ; }
Send the event to all matching handlers .
65
8
5,785
public static String readlineFromStdIn ( ) throws IOException { StringBuilder ret = new StringBuilder ( ) ; int c ; while ( ( c = System . in . read ( ) ) != ' ' && c != - 1 ) { if ( c != ' ' ) ret . append ( ( char ) c ) ; } return ret . toString ( ) ; }
Reads a line from standard input .
78
8
5,786
protected final SessionState getSessionState ( ) { if ( sessionTracker != null ) { Session currentSession = sessionTracker . getSession ( ) ; return ( currentSession != null ) ? currentSession . getState ( ) : null ; } return null ; }
Gets the current state of the session or null if no session has been created .
53
17
5,787
protected final String getAccessToken ( ) { if ( sessionTracker != null ) { Session currentSession = sessionTracker . getOpenSession ( ) ; return ( currentSession != null ) ? currentSession . getAccessToken ( ) : null ; } return null ; }
Gets the access token associated with the current session or null if no session has been created .
54
19
5,788
protected final Date getExpirationDate ( ) { if ( sessionTracker != null ) { Session currentSession = sessionTracker . getOpenSession ( ) ; return ( currentSession != null ) ? currentSession . getExpirationDate ( ) : null ; } return null ; }
Gets the date at which the current session will expire or null if no session has been created .
56
20
5,789
protected final void closeSessionAndClearTokenInformation ( ) { if ( sessionTracker != null ) { Session currentSession = sessionTracker . getOpenSession ( ) ; if ( currentSession != null ) { currentSession . closeAndClearTokenInformation ( ) ; } } }
Closes the current session as well as clearing the token cache .
55
13
5,790
protected final List < String > getSessionPermissions ( ) { if ( sessionTracker != null ) { Session currentSession = sessionTracker . getSession ( ) ; return ( currentSession != null ) ? currentSession . getPermissions ( ) : null ; } return null ; }
Gets the permissions associated with the current session or null if no session has been created .
57
18
5,791
protected final void openSessionForRead ( String applicationId , List < String > permissions , SessionLoginBehavior behavior , int activityCode ) { openSession ( applicationId , permissions , behavior , activityCode , SessionAuthorizationType . READ ) ; }
Opens a new session with read permissions . If either applicationID or permissions is null this method will default to using the values from the associated meta - data value and an empty list respectively .
51
38
5,792
public static void fetchDeferredAppLinkData ( Context context , String applicationId , final CompletionHandler completionHandler ) { Validate . notNull ( context , "context" ) ; Validate . notNull ( completionHandler , "completionHandler" ) ; if ( applicationId == null ) { applicationId = Utility . getMetadataApplicationId ( context ) ; } Validate . notNull ( applicationId , "applicationId" ) ; final Context applicationContext = context . getApplicationContext ( ) ; final String applicationIdCopy = applicationId ; Settings . getExecutor ( ) . execute ( new Runnable ( ) { @ Override public void run ( ) { fetchDeferredAppLinkFromServer ( applicationContext , applicationIdCopy , completionHandler ) ; } } ) ; }
Asynchronously fetches app link information that might have been stored for use after installation of the app
164
20
5,793
public static AppLinkData createFromActivity ( Activity activity ) { Validate . notNull ( activity , "activity" ) ; Intent intent = activity . getIntent ( ) ; if ( intent == null ) { return null ; } AppLinkData appLinkData = createFromAlApplinkData ( intent ) ; if ( appLinkData == null ) { String appLinkArgsJsonString = intent . getStringExtra ( BUNDLE_APPLINK_ARGS_KEY ) ; appLinkData = createFromJson ( appLinkArgsJsonString ) ; } if ( appLinkData == null ) { // Try regular app linking appLinkData = createFromUri ( intent . getData ( ) ) ; } return appLinkData ; }
Parses out any app link data from the Intent of the Activity passed in .
159
17
5,794
public void setPattern ( Pattern regex ) { this . re = regex ; int memregCount , counterCount , lookaheadCount ; if ( ( memregCount = regex . memregs ) > 0 ) { MemReg [ ] memregs = new MemReg [ memregCount ] ; for ( int i = 0 ; i < memregCount ; i ++ ) { memregs [ i ] = new MemReg ( - 1 ) ; //unlikely to SearchEntry, in this case we know memreg indices by definition } this . memregs = memregs ; } if ( ( counterCount = regex . counters ) > 0 ) counters = new int [ counterCount ] ; if ( ( lookaheadCount = regex . lookaheads ) > 0 ) { LAEntry [ ] lookaheads = new LAEntry [ lookaheadCount ] ; for ( int i = 0 ; i < lookaheadCount ; i ++ ) { lookaheads [ i ] = new LAEntry ( ) ; } this . lookaheads = lookaheads ; } this . memregCount = memregCount ; this . counterCount = counterCount ; this . lookaheadCount = lookaheadCount ; first = new SearchEntry ( ) ; defaultEntry = new SearchEntry ( ) ; minQueueLength = regex . stringRepr . length ( ) / 2 ; // just evaluation!!! }
Sets the regex Pattern this tries to match . Won t do anything until the target is set as well .
286
22
5,795
public void skip ( ) { int we = wEnd ; if ( wOffset == we ) { //requires special handling //if no variants at 'wOutside',advance pointer and clear if ( top == null ) { wOffset ++ ; flush ( ) ; } //otherwise, if there exist a variant, //don't clear(), i.e. allow it to match return ; } else { if ( we < 0 ) wOffset = 0 ; else wOffset = we ; } //rflush(); //rflush() works faster on simple regexes (with a small group/branch number) flush ( ) ; }
Sets the current search position just after the end of last match .
129
14
5,796
public void flush ( ) { top = null ; defaultEntry . reset ( 0 ) ; first . reset ( minQueueLength ) ; for ( int i = memregs . length - 1 ; i > 0 ; i -- ) { MemReg mr = memregs [ i ] ; mr . in = mr . out = - 1 ; } /* for (int i = memregs.length - 1; i > 0; i--) { MemReg mr = memregs[i]; mr.in = mr.out = -1; }*/ called = false ; }
Resets the internal state .
127
6
5,797
@ Override public int start ( String name ) { Integer id = re . groupId ( name ) ; if ( id == null ) throw new IllegalArgumentException ( "<" + name + "> isn't defined" ) ; return start ( id ) ; }
Returns the start index of the subsequence captured by the given named - capturing group during the previous match operation .
55
22
5,798
private static int repeat ( char [ ] data , int off , int out , Term term ) { switch ( term . type ) { case Term . CHAR : { char c = term . c ; int i = off ; while ( i < out ) { if ( data [ i ] != c ) break ; i ++ ; } return i - off ; } case Term . ANY_CHAR : { return out - off ; } case Term . ANY_CHAR_NE : { int i = off ; char c ; while ( i < out ) { if ( ( c = data [ i ] ) == ' ' || c == ' ' ) break ; i ++ ; } return i - off ; } case Term . BITSET : { IntBitSet arr = term . bitset ; int i = off ; char c ; if ( term . inverse ) while ( i < out ) { if ( ( c = data [ i ] ) <= 255 && arr . get ( c ) ) break ; else i ++ ; } else while ( i < out ) { if ( ( c = data [ i ] ) <= 255 && arr . get ( c ) ) i ++ ; else break ; } return i - off ; } case Term . BITSET2 : { int i = off ; IntBitSet [ ] bitset2 = term . bitset2 ; char c ; if ( term . inverse ) while ( i < out ) { IntBitSet arr = bitset2 [ ( c = data [ i ] ) >> 8 ] ; if ( arr != null && arr . get ( c & 0xff ) ) break ; else i ++ ; } else while ( i < out ) { IntBitSet arr = bitset2 [ ( c = data [ i ] ) >> 8 ] ; if ( arr != null && arr . get ( c & 0xff ) ) i ++ ; else break ; } return i - off ; } } throw new Error ( "this kind of term can't be quantified:" + term . type ) ; }
repeat while matches
418
3
5,799
private static int find ( char [ ] data , int off , int out , Term term ) { if ( off >= out ) return - 1 ; switch ( term . type ) { case Term . CHAR : { char c = term . c ; int i = off ; while ( i < out ) { if ( data [ i ] == c ) break ; i ++ ; } return i - off ; } case Term . BITSET : { IntBitSet arr = term . bitset ; int i = off ; char c ; if ( ! term . inverse ) while ( i < out ) { if ( ( c = data [ i ] ) <= 255 && arr . get ( c ) ) break ; else i ++ ; } else while ( i < out ) { if ( ( c = data [ i ] ) <= 255 && arr . get ( c ) ) i ++ ; else break ; } return i - off ; } case Term . BITSET2 : { int i = off ; IntBitSet [ ] bitset2 = term . bitset2 ; char c ; if ( ! term . inverse ) while ( i < out ) { IntBitSet arr = bitset2 [ ( c = data [ i ] ) >> 8 ] ; if ( arr != null && arr . get ( c & 0xff ) ) break ; else i ++ ; } else while ( i < out ) { IntBitSet arr = bitset2 [ ( c = data [ i ] ) >> 8 ] ; if ( arr != null && arr . get ( c & 0xff ) ) i ++ ; else break ; } return i - off ; } } throw new IllegalArgumentException ( "can't seek this kind of term:" + term . type ) ; }
repeat while doesn t match
361
5