idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
5,700
protected Object getFieldValue ( String fieldname ) { ActionContext actionCtx = ActionContext . getContext ( ) ; ValueStack valueStack = actionCtx . getValueStack ( ) ; Object value = valueStack . findValue ( fieldname , false ) ; String overwriteValue = getOverwriteValue ( fieldname ) ; if ( overwriteValue != null ) { return overwriteValue ; } return value ; }
Return Strus2 field value .
5,701
protected String getOverwriteValue ( String fieldname ) { ActionContext ctx = ServletActionContext . getContext ( ) ; ValueStack stack = ctx . getValueStack ( ) ; Map < Object , Object > overrideMap = stack . getExprOverrides ( ) ; if ( overrideMap == null || overrideMap . isEmpty ( ) ) { return null ; } if ( ! overrideMap . containsKey ( fieldname ) ) { return null ; } String convertionValue = ( String ) overrideMap . get ( fieldname ) ; String altString = StringEscapeUtils . unescapeJava ( convertionValue ) ; altString = altString . substring ( 1 , altString . length ( ) - 1 ) ; return altString ; }
If Type - Convertion Error found at Struts2 overwrite request - parameter same name .
5,702
public final void setPresetSize ( int sizeType ) { switch ( sizeType ) { case SMALL : case NORMAL : case LARGE : case CUSTOM : this . presetSizeType = sizeType ; break ; default : throw new IllegalArgumentException ( "Must use a predefined preset size" ) ; } requestLayout ( ) ; }
Apply a preset size to this profile photo
5,703
public final void setProfileId ( String profileId ) { boolean force = false ; if ( Utility . isNullOrEmpty ( this . profileId ) || ! this . profileId . equalsIgnoreCase ( profileId ) ) { setBlankProfilePicture ( ) ; force = true ; } this . profileId = profileId ; refreshImage ( force ) ; }
Sets the profile Id for this profile photo
5,704
protected Parcelable onSaveInstanceState ( ) { Parcelable superState = super . onSaveInstanceState ( ) ; Bundle instanceState = new Bundle ( ) ; instanceState . putParcelable ( SUPER_STATE_KEY , superState ) ; instanceState . putString ( PROFILE_ID_KEY , profileId ) ; instanceState . putInt ( PRESET_SIZE_KEY , presetSizeType ) ; instanceState . putBoolean ( IS_CROPPED_KEY , isCropped ) ; instanceState . putParcelable ( BITMAP_KEY , imageContents ) ; instanceState . putInt ( BITMAP_WIDTH_KEY , queryWidth ) ; instanceState . putInt ( BITMAP_HEIGHT_KEY , queryHeight ) ; instanceState . putBoolean ( PENDING_REFRESH_KEY , lastRequest != null ) ; return instanceState ; }
Some of the current state is returned as a Bundle to allow quick restoration of the ProfilePictureView object in scenarios like orientation changes .
5,705
protected void onRestoreInstanceState ( Parcelable state ) { if ( state . getClass ( ) != Bundle . class ) { super . onRestoreInstanceState ( state ) ; } else { Bundle instanceState = ( Bundle ) state ; super . onRestoreInstanceState ( instanceState . getParcelable ( SUPER_STATE_KEY ) ) ; profileId = instanceState . getString ( PROFILE_ID_KEY ) ; presetSizeType = instanceState . getInt ( PRESET_SIZE_KEY ) ; isCropped = instanceState . getBoolean ( IS_CROPPED_KEY ) ; queryWidth = instanceState . getInt ( BITMAP_WIDTH_KEY ) ; queryHeight = instanceState . getInt ( BITMAP_HEIGHT_KEY ) ; setImageBitmap ( ( Bitmap ) instanceState . getParcelable ( BITMAP_KEY ) ) ; if ( instanceState . getBoolean ( PENDING_REFRESH_KEY ) ) { refreshImage ( true ) ; } } }
If the passed in state is a Bundle an attempt is made to restore from it .
5,706
private void enhanceFAB ( final FloatingActionButton fab , int dx , int dy ) { if ( isEnhancedFAB ( ) && getFab ( ) != null ) { final FloatingActionButton mFloatingActionButton = this . fab ; if ( getLinearLayoutManager ( ) != null ) { if ( dy > 0 ) { if ( mFloatingActionButton . getVisibility ( ) == View . VISIBLE ) { mFloatingActionButton . hide ( ) ; } } else { if ( mFloatingActionButton . getVisibility ( ) != View . VISIBLE ) { mFloatingActionButton . show ( ) ; } } } } }
Enhanced FAB UX Logic Handle RecyclerView scrolling
5,707
private void enhanceFAB ( final FloatingActionButton fab , MotionEvent e ) { if ( hasAllItemsShown ( ) ) { if ( fab . getVisibility ( ) != View . VISIBLE ) { fab . show ( ) ; } } }
Enhanced FAB UX Logic Handle RecyclerView scrolled If all item visible within view port FAB will show
5,708
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
5,709
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
5,710
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
5,711
@ 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 ( ) ) ) ; MediaType mediaType = HttpResponse . contentType ( ResponseCreationSupport . uriFromUrl ( resourceUrl ) ) ; setMaxAge ( response , ( maxAgeCalculator == null ? DEFAULT_MAX_AGE_CALCULATOR : maxAgeCalculator ) . maxAge ( request , mediaType ) ) ; 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 ) ) ; ( 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 .
5,712
@ 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 ) { } 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 ) { } } 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 ) { } return new ResourceInfo ( null , null ) ; }
Attempts to lookup the additional resource information for the given URL .
5,713
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 .
5,714
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 .
5,715
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 ( ) { public void call ( Session callbackSession , SessionState state , Exception exception ) { 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 .
5,716
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 .
5,717
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 .
5,718
@ 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 .
5,719
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 .
5,720
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 ; } 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 ; } } }
Get the underlying Session object to use with 3 . 0 api .
5,721
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 .
5,722
@ Handler ( priority = - 10000 ) public void onStop ( Stop event ) throws InterruptedException { synchronized ( this ) { if ( runner == null ) { return ; } while ( runner . isAlive ( ) ) { runner . interrupt ( ) ; selector . wakeup ( ) ; runner . join ( 10 ) ; } runner = null ; } }
Stops the thread that is associated with this dispatcher .
5,723
public void onNioRegistration ( NioRegistration event ) throws IOException { SelectableChannel channel = event . ioChannel ( ) ; channel . configureBlocking ( false ) ; SelectionKey key ; synchronized ( selectorGate ) { selector . wakeup ( ) ; key = channel . register ( selector , event . ops ( ) , event . handler ( ) ) ; } event . setResult ( new Registration ( key ) ) ; }
Handle the NIO registration .
5,724
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
5,725
@ 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 .
5,726
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 .
5,727
@ Handler ( channels = Channel . class ) public void discard ( DiscardSession event ) { removeSession ( event . session ( ) . id ( ) ) ; }
Discards the given session .
5,728
@ 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 .
5,729
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 .
5,730
@ 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 .
5,731
@ 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 .
5,732
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
5,733
@ 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 ; for ( int pathIdx = 0 ; pathIdx < pathPatternElements . length ; pathIdx ++ ) { String [ ] pathPattern = pathPatternElements [ pathIdx ] ; if ( prefixSegs [ pathIdx ] == pathPattern . length - 1 && lastIsEmpty ( pathPattern ) ) { 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 .
5,734
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 .
5,735
@ 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 .
5,736
@ 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 .
5,737
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 .
5,738
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 .
5,739
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 .
5,740
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
5,741
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 .
5,742
public static void enableSSLValidation ( ) { try { SSLContext . getInstance ( "SSL" ) . init ( null , null , null ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Enable SSL Validation .
5,743
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 .
5,744
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 .
5,745
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 .
5,746
public void unsetUserConfigurations ( UserConfigurationsProvider provider ) { if ( userConfigurations . isPresent ( ) && userConfigurations . get ( ) . equals ( provider ) ) { this . userConfigurations = Optional . empty ( ) ; } }
Unset reference added automatically from setUserConfigurations annotation
5,747
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 .
5,748
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 ) ; if ( attributeValue instanceof IncludeValue ) externalConfigurations . add ( ( ( IncludeValue ) attributeValue ) . getConfigName ( ) ) ; }
Adds an attribute value . If the attribute doesn t exist it will be created .
5,749
public void onClose ( Close event , WebAppMsgChannel appChannel ) throws InterruptedException { appChannel . handleClose ( event ) ; }
Handles a close event from downstream by closing the upstream connections .
5,750
@ 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 .
5,751
public Matcher matcher ( CharSequence s ) { Matcher m = new Matcher ( this ) ; m . setTarget ( s ) ; return m ; }
Returns a matcher for a specified string .
5,752
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 .
5,753
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 .
5,754
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
5,755
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
5,756
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
5,757
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
5,758
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
5,759
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
5,760
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
5,761
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 .
5,762
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 .
5,763
public static Timer schedule ( TimeoutHandler timeoutHandler , Instant scheduledFor ) { return scheduler . schedule ( timeoutHandler , scheduledFor ) ; }
Schedules the given timeout handler for the given instance .
5,764
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 .
5,765
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
5,766
public static Bundle parseUrl ( String url ) { 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 .
5,767
public static String openUrl ( String url , String method , Bundle params ) throws MalformedURLException , IOException { String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f" ; String endLine = "\r\n" ; OutputStream os ; if ( method . equals ( "GET" ) ) { url = url + "?" + encodeUrl ( params ) ; } Utility . logd ( "Facebook-Util" , method + " URL: " + url ) ; HttpURLConnection conn = ( HttpURLConnection ) new URL ( url ) . openConnection ( ) ; conn . setRequestProperty ( "User-Agent" , System . getProperties ( ) . getProperty ( "http.agent" ) + " FacebookAndroidSDK" ) ; if ( ! method . equals ( "GET" ) ) { Bundle dataparams = new Bundle ( ) ; for ( String key : params . keySet ( ) ) { Object parameter = params . get ( key ) ; if ( parameter instanceof byte [ ] ) { dataparams . putByteArray ( key , ( byte [ ] ) parameter ) ; } } if ( ! params . containsKey ( "method" ) ) { params . putString ( "method" , method ) ; } if ( params . containsKey ( "access_token" ) ) { String decoded_token = URLDecoder . decode ( params . getString ( "access_token" ) ) ; params . putString ( "access_token" , decoded_token ) ; } conn . setRequestMethod ( "POST" ) ; conn . setRequestProperty ( "Content-Type" , "multipart/form-data;boundary=" + strBoundary ) ; conn . setDoOutput ( true ) ; conn . setDoInput ( true ) ; conn . setRequestProperty ( "Connection" , "Keep-Alive" ) ; conn . connect ( ) ; os = new BufferedOutputStream ( conn . getOutputStream ( ) ) ; try { os . write ( ( "--" + strBoundary + endLine ) . getBytes ( ) ) ; os . write ( ( encodePostBody ( params , strBoundary ) ) . getBytes ( ) ) ; os . write ( ( endLine + "--" + strBoundary + endLine ) . getBytes ( ) ) ; if ( ! dataparams . isEmpty ( ) ) { for ( String key : dataparams . keySet ( ) ) { os . write ( ( "Content-Disposition: form-data; filename=\"" + key + "\"" + endLine ) . getBytes ( ) ) ; os . write ( ( "Content-Type: content/unknown" + endLine + endLine ) . getBytes ( ) ) ; os . write ( dataparams . getByteArray ( key ) ) ; os . write ( ( endLine + "--" + strBoundary + endLine ) . getBytes ( ) ) ; } } os . flush ( ) ; } finally { os . close ( ) ; } } String response = "" ; try { response = read ( conn . getInputStream ( ) ) ; } catch ( FileNotFoundException e ) { response = read ( conn . getErrorStream ( ) ) ; } return response ; }
Connect to an HTTP URL and return the response as a string .
5,768
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 .
5,769
public Character set ( final int index , final Character ok ) { return set ( index , ok . charValue ( ) ) ; }
Delegates to the corresponding type - specific method .
5,770
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 .
5,771
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 .
5,772
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 .
5,773
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 .
5,774
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 .
5,775
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 .
5,776
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 .
5,777
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 .
5,778
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 .
5,779
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 .
5,780
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 .
5,781
private boolean cleanupInventory ( ) { boolean modified = false ; modified |= removeUnreadable ( ) ; modified |= recreateMismatching ( ) ; modified |= importConfigurations ( ) ; return modified ; }
Cleans up the inventory .
5,782
private boolean removeUnreadable ( ) { List < File > unreadable = inventory . removeUnreadable ( ) ; unreadable . forEach ( v -> v . delete ( ) ) ; return ! unreadable . isEmpty ( ) ; }
Removes unreadable configurations from the file system .
5,783
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 .
5,784
private boolean importConfigurations ( ) { 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 ) && f . getName ( ) . endsWith ( CONFIG_EXT ) && ! files . contains ( f ) ) ) ; 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 .
5,785
@ 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 .
5,786
@ 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 .
5,787
public Event < T > setResult ( T result ) { synchronized ( this ) { if ( results == null ) { 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 .
5,788
protected List < T > currentResults ( ) { return results == null ? Collections . emptyList ( ) : Collections . unmodifiableList ( results ) ; }
Allows access to the intermediate result before the completion of the event .
5,789
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
5,790
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
5,791
< T > void bindWith ( final PeasyRecyclerView < T > binder , final int viewType ) { this . itemView . setOnClickListener ( new View . OnClickListener ( ) { 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 ( ) { 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
5,792
@ SuppressWarnings ( "PMD.UseVarargs" ) public void fire ( Event < ? > event , Channel [ ] channels ) { eventPipeline . add ( event , channels ) ; }
Forward to the thread s event manager .
5,793
@ SuppressWarnings ( "PMD.UseVarargs" ) void dispatch ( EventPipeline pipeline , EventBase < ? > event , Channel [ ] channels ) { HandlerList handlers = getEventHandlers ( event , channels ) ; handlers . process ( pipeline , event ) ; }
Send the event to all matching handlers .
5,794
public static String readlineFromStdIn ( ) throws IOException { StringBuilder ret = new StringBuilder ( ) ; int c ; while ( ( c = System . in . read ( ) ) != '\n' && c != - 1 ) { if ( c != '\r' ) ret . append ( ( char ) c ) ; } return ret . toString ( ) ; }
Reads a line from standard input .
5,795
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 .
5,796
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 .
5,797
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 .
5,798
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 .
5,799
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 .