idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
18,200 | public Api getActionResult ( String action , String params , TokenResult token , Object pFormData ) throws Exception { return getActionResult ( action , params , token , pFormData , format ) ; } | get the action result for the default format | 44 | 8 |
18,201 | public Api getActionResult ( String action , String params ) throws Exception { Api result = this . getActionResult ( action , params , null , null ) ; return result ; } | get the result for the given action and query | 39 | 9 |
18,202 | public Api getQueryResult ( String query ) throws Exception { Api result = this . getActionResult ( "query" , query , null , null ) ; return result ; } | get the Result for the given query | 38 | 7 |
18,203 | public TokenResult prepareLogin ( String username ) throws Exception { username = encode ( username ) ; Api apiResult = null ; TokenResult token = new TokenResult ( ) ; token . tokenName = "lgtoken" ; token . tokenMode = TokenMode . token1_19 ; // see https://github.com/WolfgangFahl/Mediawiki-Japi/issues/31 if ( this . isVersion128 ( ) ) { apiResult = this . getQueryResult ( "&meta=tokens&type=login" ) ; super . handleError ( apiResult ) ; token . token = apiResult . getQuery ( ) . getTokens ( ) . getLogintoken ( ) ; } else { apiResult = getActionResult ( "login" , "&lgname=" + username , null , null ) ; super . handleError ( apiResult ) ; Login login = apiResult . getLogin ( ) ; token . token = login . getToken ( ) ; } return token ; } | prepare the login by getting the login token | 213 | 9 |
18,204 | public Login login ( String username , String password , String domain ) throws Exception { // login is a two step process // first we get a token TokenResult token = prepareLogin ( username ) ; // and then with the token we login using the password Login login = login ( token , username , password , domain ) ; return login ; } | login with the given username password and domain | 68 | 8 |
18,205 | public Login login ( String username , String password ) throws Exception { return login ( username , password , null ) ; } | login with the given username and password | 24 | 7 |
18,206 | public void logout ( ) throws Exception { Api apiResult = getActionResult ( "logout" , "" , null , null ) ; if ( apiResult != null ) { userid = null ; // FIXME check apiResult } if ( cookies != null ) { cookies . clear ( ) ; cookies = null ; } } | end the session | 69 | 3 |
18,207 | public String getSectionText ( String pageTitle , int sectionNumber ) throws Exception { String result = this . getPageContent ( pageTitle , "&rvsection=" + sectionNumber , false ) ; return result ; } | get the text for the given section | 46 | 7 |
18,208 | public Parse getParse ( String params ) throws Exception { String action = "parse" ; Api api = getActionResult ( action , params ) ; super . handleError ( api ) ; return api . getParse ( ) ; } | get the parse Result for the given params | 51 | 8 |
18,209 | public synchronized void upload ( InputStream fileToUpload , String filename , String contents , String comment ) throws Exception { TokenResult token = getEditToken ( "File:" + filename , "edit" ) ; final FormDataMultiPart multiPart = new FormDataMultiPart ( ) ; // http://stackoverflow.com/questions/5772225/trying-to-upload-a-file-to-a-jax-rs-jersey-server multiPart . bodyPart ( new StreamDataBodyPart ( "file" , fileToUpload ) ) ; multiPart . field ( "filename" , filename ) ; multiPart . field ( "ignorewarnings" , "true" ) ; multiPart . field ( "text" , contents ) ; if ( ! comment . isEmpty ( ) ) multiPart . field ( "comment" , comment ) ; String params = "" ; Api api = this . getActionResult ( "upload" , params , token , multiPart ) ; handleError ( api ) ; } | upload from the given inputstream | 216 | 6 |
18,210 | public static void showVersion ( ) { System . err . println ( "Mediawiki-Japi Version: " + VERSION ) ; System . err . println ( ) ; System . err . println ( " github: https://github.com/WolfgangFahl/Mediawiki-Japi" ) ; System . err . println ( "" ) ; } | show the Version | 74 | 3 |
18,211 | public void usage ( String msg ) { System . err . println ( msg ) ; showVersion ( ) ; System . err . println ( " usage: java com.bitplan.mediawiki.japi.Mediawiki" ) ; parser . printUsage ( System . err ) ; exitCode = 1 ; } | show a usage | 64 | 3 |
18,212 | public Api createAccount ( String name , String eMail , String realname , boolean mailpassword , String reason , String language ) throws Exception { String createtoken = "?" ; if ( getVersion ( ) . compareToIgnoreCase ( "Mediawiki 1.27" ) >= 0 ) { Api apiResult = this . getQueryResult ( "&meta=tokens&type=createaccount" ) ; super . handleError ( apiResult ) ; createtoken = apiResult . getQuery ( ) . getTokens ( ) . getCreateaccounttoken ( ) ; } Api api = null ; if ( getVersion ( ) . compareToIgnoreCase ( "Mediawiki 1.27" ) >= 0 ) { Map < String , String > lFormData = new HashMap < String , String > ( ) ; lFormData . put ( "createtoken" , createtoken ) ; lFormData . put ( "username" , name ) ; lFormData . put ( "email" , eMail ) ; lFormData . put ( "realname" , realname ) ; lFormData . put ( "mailpassword" , mailpassword ? "1" : "0" ) ; lFormData . put ( "reason" , reason ) ; lFormData . put ( "createcontinue" , "1" ) ; String params = "" ; api = getActionResult ( "createaccount" , params , null , lFormData ) ; } else { String params = "&name=" + this . encode ( name ) ; params += "&email=" + this . encode ( eMail ) ; params += "&realname=" + this . encode ( realname ) ; params += "&mailpassword=" + mailpassword ; params += "&reason=" + this . encode ( reason ) ; params += "&token=" ; api = getActionResult ( "createaccount" , params ) ; handleError ( api ) ; String token = api . getCreateaccount ( ) . getToken ( ) ; params += token ; api = getActionResult ( "createaccount" , params ) ; } return api ; } | create the given user account | 451 | 5 |
18,213 | public List < Rc > sortByTitleAndFilterDoubles ( List < Rc > rcList ) { List < Rc > result = new ArrayList < Rc > ( ) ; List < Rc > sorted = new ArrayList < Rc > ( ) ; sorted . addAll ( rcList ) ; Collections . sort ( sorted , new Comparator < Rc > ( ) { @ Override public int compare ( Rc lRc , Rc rRc ) { int result = lRc . getTitle ( ) . compareTo ( rRc . getTitle ( ) ) ; if ( result == 0 ) { result = rRc . getTimestamp ( ) . compare ( lRc . getTimestamp ( ) ) ; } return result ; } } ) ; Rc previous = null ; for ( Rc rc : sorted ) { if ( previous == null || ( ! rc . getTitle ( ) . equals ( previous . getTitle ( ) ) ) ) { result . add ( rc ) ; } previous = rc ; } Collections . sort ( result , new Comparator < Rc > ( ) { @ Override public int compare ( Rc lRc , Rc rRc ) { int result = rRc . getTimestamp ( ) . compare ( lRc . getTimestamp ( ) ) ; return result ; } } ) ; return result ; } | sort the given List by title and filter double titles | 295 | 10 |
18,214 | public String dateToMWTimeStamp ( Date date ) { SimpleDateFormat mwTimeStampFormat = new SimpleDateFormat ( "yyyyMMddHHmmss" ) ; String result = mwTimeStampFormat . format ( date ) ; return result ; } | convert a data to a MediaWiki API timestamp | 58 | 10 |
18,215 | public List < Rc > getMostRecentChanges ( int days , int rcLimit ) throws Exception { Date today = new Date ( ) ; Calendar cal = new GregorianCalendar ( ) ; cal . setTime ( today ) ; cal . add ( Calendar . DAY_OF_MONTH , - days ) ; Date date30daysbefore = cal . getTime ( ) ; String rcstart = dateToMWTimeStamp ( today ) ; String rcend = dateToMWTimeStamp ( date30daysbefore ) ; List < Rc > rcList = this . getRecentChanges ( rcstart , rcend , rcLimit ) ; List < Rc > result = this . sortByTitleAndFilterDoubles ( rcList ) ; return result ; } | get the most recent changes | 158 | 5 |
18,216 | protected void handleError ( String errMsg ) throws Exception { // log it LOGGER . log ( Level . SEVERE , errMsg ) ; // and throw an error if this is configured if ( this . isThrowExceptionOnError ( ) ) { throw new Exception ( errMsg ) ; } } | handle the given error Message according to the exception setting | 62 | 10 |
18,217 | protected void handleError ( Error error ) throws Exception { String errMsg = "error: " + error . getCode ( ) + " info: " + error . getInfo ( ) ; handleError ( errMsg ) ; } | handle the given api error | 47 | 5 |
18,218 | public Api fromXML ( String xml ) throws Exception { // retrieve the JAXB wrapper representation from the xml received Api api = Api . fromXML ( xml ) ; // check whether an error code was sent Error error = api . getError ( ) ; // if there is an error - handle it if ( error != null ) { // prepare the error message String errMsg = "error code=" + error . getCode ( ) + " info:'" + error . getInfo ( ) + "'" ; this . handleError ( errMsg ) ; } return api ; } | return Api from the given xml | 123 | 7 |
18,219 | protected String encode ( String param ) throws Exception { String result = URLEncoder . encode ( param , "UTF-8" ) ; return result ; } | request parameter encoding | 33 | 3 |
18,220 | protected String decode ( String html ) throws Exception { String result = StringEscapeUtils . unescapeHtml4 ( html ) ; return result ; } | decode the given html markup | 32 | 6 |
18,221 | public String normalizeTitle ( String title ) throws Exception { String result = encode ( title ) ; result = result . replace ( "+" , "_" ) ; return result ; } | normalize the given page title | 37 | 6 |
18,222 | public static AccessContext getAccessContextOnThread ( ) { final Stack < AccessContext > stack = threadLocal . get ( ) ; return stack != null ? stack . peek ( ) : null ; } | Get prepared access - context on thread . | 41 | 8 |
18,223 | public static void setAccessContextOnThread ( AccessContext accessContext ) { if ( accessContext == null ) { String msg = "The argument[accessContext] must not be null." ; throw new IllegalArgumentException ( msg ) ; } Stack < AccessContext > stack = threadLocal . get ( ) ; if ( stack == null ) { stack = new Stack < AccessContext > ( ) ; threadLocal . set ( stack ) ; } stack . add ( accessContext ) ; } | Set prepared access - context on thread . | 100 | 8 |
18,224 | public static boolean isExistAccessContextOnThread ( ) { final Stack < AccessContext > stack = threadLocal . get ( ) ; return stack != null ? ! stack . isEmpty ( ) : false ; } | Is existing prepared access - context on thread? | 44 | 9 |
18,225 | public void downloadStreamCall ( ResponseDownloadResource resource , HttpServletResponse response ) { final WrittenStreamCall streamCall = resource . getStreamCall ( ) ; if ( streamCall == null ) { String msg = "Either byte data or input stream is required: " + resource ; throw new IllegalArgumentException ( msg ) ; } try { final Integer contentLength = resource . getContentLength ( ) ; if ( contentLength != null ) { response . setContentLength ( contentLength ) ; } final OutputStream out = response . getOutputStream ( ) ; try { streamCall . callback ( createWrittenStreamOut ( out ) ) ; flushDownloadStream ( out ) ; } finally { closeDownloadStream ( out ) ; } } catch ( RuntimeException e ) { throw new ResponseDownloadFailureException ( "Failed to download the input stream: " + resource , e ) ; } catch ( IOException e ) { handleDownloadIOException ( resource , e ) ; } } | switched to stream call way for closing headache | 202 | 9 |
18,226 | public static Date getTransactionTime ( ) { final Stack < Date > stack = threadLocal . get ( ) ; return stack != null ? stack . peek ( ) : null ; } | Get the value of the transaction time . | 37 | 8 |
18,227 | public static void setTransactionTime ( Date transactionTime ) { if ( transactionTime == null ) { String msg = "The argument 'transactionTime' should not be null." ; throw new IllegalArgumentException ( msg ) ; } Stack < Date > stack = threadLocal . get ( ) ; if ( stack == null ) { stack = new Stack < Date > ( ) ; threadLocal . set ( stack ) ; } stack . push ( transactionTime ) ; } | Set the value of the transaction time . | 96 | 8 |
18,228 | public ActionExecute findActionExecute ( String paramPath ) { // null allowed when not found for ( ActionExecute execute : executeMap . values ( ) ) { if ( execute . determineTargetByPathParameter ( paramPath ) ) { return execute ; } } return null ; } | optional unused for performance | 59 | 4 |
18,229 | protected void doSetFrom ( String from , String personal ) { assertArgumentNotEmpty ( "from" , from ) ; assertArgumentNotEmpty ( "personal" , personal ) ; // only from required postcard . setFrom ( createAddress ( from , personal ) ) ; } | public methods are prepared at sub - class | 59 | 8 |
18,230 | public void pushLogging ( String key , Object value ) { assertArgumentNotNull ( "key" , key ) ; assertArgumentNotNull ( "value" , value ) ; postcard . pushLogging ( key , value ) ; } | Push element of mail logging . | 52 | 6 |
18,231 | protected List < Class < ? extends Annotation > > createAnnotationTypeList ( Class < ? > ... annotations ) { final List < Class < ? extends Annotation > > annotationList = new ArrayList < Class < ? extends Annotation > > ( ) ; for ( Class < ? > annoType : annotations ) { @ SuppressWarnings ( "unchecked" ) final Class < ? extends Annotation > castType = ( Class < ? extends Annotation > ) annoType ; annotationList . add ( castType ) ; } return annotationList ; } | for Generic headache . | 118 | 4 |
18,232 | protected SqlStringFilter createSqlStringFilter ( ActionRuntime runtime ) { final Method actionMethod = runtime . getExecuteMethod ( ) ; return newRomanticTraceableSqlStringFilter ( actionMethod , ( ) -> { return buildSqlMarkingAdditionalInfo ( ) ; // lazy because it may be auto-login later } ) ; } | Create the filter of SQL string for DBFlute . | 74 | 11 |
18,233 | protected void checkLoginRequired ( ActionRuntime runtime ) throws LoginRequiredException { loginManager . ifPresent ( nager -> { nager . checkLoginRequired ( createLogingHandlingResource ( runtime ) ) ; } ) ; } | Check the login required for the requested action . | 47 | 9 |
18,234 | public void setWrappedData ( Object data ) { if ( data == null ) { inner = null ; arrayFromInner = null ; setRowIndex ( - 1 ) ; } else { inner = ( Collection < E > ) data ; arrayFromInner = ( E [ ] ) new Object [ inner . size ( ) ] ; inner . toArray ( arrayFromInner ) ; setRowIndex ( 0 ) ; } } | Set the wrapped data . | 90 | 5 |
18,235 | protected SqlAnalyzer createSqlAnalyzer ( String templateText , boolean blockNullParameter ) { final SqlAnalyzer analyzer = new SqlAnalyzer ( templateText , blockNullParameter ) { @ Override protected String filterAtFirst ( String sql ) { return sql ; // keep body } @ Override protected EmbeddedVariableNode newEmbeddedVariableNode ( String expr , String testValue , String specifiedSql , boolean blockNullParameter , NodeAdviceFactory adviceFactory , boolean replaceOnly , boolean terminalDot , boolean overlookNativeBinding ) { return createTemplikeEmbeddedVariableNode ( expr , testValue , specifiedSql , blockNullParameter , adviceFactory , replaceOnly , terminalDot , overlookNativeBinding ) ; } } . overlookNativeBinding ( ) . switchBindingToReplaceOnlyEmbedded ( ) ; // adjust for plain template return analyzer ; } | almost same as mailflute | 188 | 6 |
18,236 | @ Override public OptionalEntity < USER_ENTITY > findLoginUser ( Object userId ) { assertUserIdRequired ( userId ) ; try { @ SuppressWarnings ( "unchecked" ) final ID castId = ( ID ) userId ; return doFindLoginUser ( castId ) ; } catch ( ClassCastException e ) { // also find method, because of generic cast throw new IllegalStateException ( "Cannot cast the user ID: " + userId . getClass ( ) + ", " + userId , e ) ; } } | Find the login user in the database . | 119 | 8 |
18,237 | protected void doLogin ( LoginCredential credential , LoginSpecifiedOption option ) throws LoginFailureException { handleLoginSuccess ( findLoginUser ( credential ) . orElseThrow ( ( ) -> { final String msg = "Not found the user by the credential: " + credential + ", " + option ; return handleLoginFailure ( msg , credential , OptionalThing . of ( option ) ) ; } ) , option ) ; } | Do actually login for the user by credential . | 89 | 9 |
18,238 | protected void handleLoginSuccess ( USER_ENTITY userEntity , LoginSpecifiedOption option ) { assertUserEntityRequired ( userEntity ) ; final USER_BEAN userBean = saveLoginInfoToSession ( userEntity ) ; if ( userBean instanceof SyncCheckable ) { ( ( SyncCheckable ) userBean ) . manageLastestSyncCheckTime ( timeManager . currentDateTime ( ) ) ; } if ( option . isRememberMe ( ) ) { saveRememberMeKeyToCookie ( userEntity , userBean ) ; } if ( ! option . isSilentLogin ( ) ) { // mainly here saveLoginHistory ( userEntity , userBean , option ) ; processOnBrightLogin ( userEntity , userBean , option ) ; } else { processOnSilentLogin ( userEntity , userBean , option ) ; } } | Handle login success for the found login user . | 185 | 9 |
18,239 | protected USER_BEAN saveLoginInfoToSession ( USER_ENTITY userEntity ) { regenerateSessionId ( ) ; logger . debug ( "...Saving login info to session" ) ; final USER_BEAN userBean = createUserBean ( userEntity ) ; sessionManager . setAttribute ( getUserBeanKey ( ) , userBean ) ; return userBean ; } | Save login info as user bean to session . | 85 | 9 |
18,240 | protected void saveRememberMeKeyToCookie ( USER_ENTITY userEntity , USER_BEAN userBean ) { final int expireDays = getRememberMeAccessTokenExpireDays ( ) ; getCookieRememberMeKey ( ) . ifPresent ( cookieKey -> { doSaveRememberMeCookie ( userEntity , userBean , expireDays , cookieKey ) ; } ) ; } | Save remember - me key to cookie . | 85 | 8 |
18,241 | protected void doSaveRememberMeCookie ( USER_ENTITY userEntity , USER_BEAN userBean , int expireDays , String cookieKey ) { logger . debug ( "...Saving remember-me key to cookie: key={}" , cookieKey ) ; final String value = buildRememberMeCookieValue ( userEntity , userBean , expireDays ) ; final int expireSeconds = expireDays * 60 * 60 * 24 ; // cookie's expire, same as access token cookieManager . setCookieCiphered ( cookieKey , value , expireSeconds ) ; } | Do save remember - me key to cookie . | 124 | 9 |
18,242 | protected boolean isValidRememberMeCookie ( String userKey , String expireDate ) { final String currentDate = formatForRememberMeExpireDate ( timeManager . currentHandyDate ( ) ) ; if ( currentDate . compareTo ( expireDate ) < 0 ) { // String v.s. String return true ; // valid access token within time limit } // expired here logger . debug ( "The access token for remember-me expired: userKey={} expireDate={}" , userKey , expireDate ) ; return false ; } | Are the user ID and expire date extracted from cookie valid? | 112 | 12 |
18,243 | protected boolean doRememberMe ( ID userId , String expireDate , RememberMeLoginSpecifiedOption option ) { final boolean updateToken = option . isUpdateToken ( ) ; final boolean silentLogin = option . isSilentLogin ( ) ; if ( logger . isDebugEnabled ( ) ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( "...Doing remember-me: user=" ) . append ( userId ) ; sb . append ( ", expire=" ) . append ( expireDate ) ; if ( updateToken ) { sb . append ( ", updateToken" ) ; } if ( silentLogin ) { sb . append ( ", silently" ) ; } logger . debug ( sb . toString ( ) ) ; } try { identityLogin ( userId , op -> op . rememberMe ( updateToken ) . silentLogin ( silentLogin ) ) ; return true ; } catch ( NumberFormatException invalidUserKey ) { // just in case // to know invalid user key or bug logger . debug ( "*The user key might be invalid: {}, {}" , userId , invalidUserKey . getMessage ( ) ) ; return false ; } catch ( LoginFailureException autoLoginFailed ) { return false ; } } | Do actually remember - me for the user . | 264 | 9 |
18,244 | protected void asLoginRequired ( LoginHandlingResource resource ) throws LoginRequiredException { logger . debug ( "...Checking login status for login required" ) ; if ( tryAlreadyLoginOrRememberMe ( resource ) ) { checkPermission ( resource ) ; // throws if denied return ; // Good } if ( needsSavingRequestedLoginRedirect ( resource ) ) { saveRequestedLoginRedirectInfo ( ) ; } throwLoginRequiredException ( "Cannot access the action: " + resource ) ; } | Check as the login - required action . | 105 | 8 |
18,245 | protected void asNonLoginRequired ( LoginHandlingResource resource ) throws LoginRequiredException { if ( ! isSuppressRememberMeOfNonLoginRequired ( resource ) ) { // option just in case logger . debug ( "...Checking login status for non login required" ) ; if ( tryAlreadyLoginOrRememberMe ( resource ) ) { checkPermission ( resource ) ; // throws if denied return ; // Good } } if ( isLoginRedirectBeanKeptAction ( resource ) ) { // keep login-redirect path in session logger . debug ( "...Passing login check as login action (or redirect-kept action)" ) ; } else { clearLoginRedirectBean ( ) ; logger . debug ( "...Passing login check as non login required" ) ; } } | Check as the non login required action . | 162 | 8 |
18,246 | public Object remove ( Serializable key ) { if ( component . initialStateMarked ( ) ) { Object retVal = deltaMap . remove ( key ) ; if ( retVal == null ) { return defaultMap . remove ( key ) ; } else { defaultMap . remove ( key ) ; return retVal ; } } else { return defaultMap . remove ( key ) ; } } | We need to remove from both maps if we do remove an existing key . | 80 | 15 |
18,247 | public Object saveState ( FacesContext context ) { if ( context == null ) { throw new NullPointerException ( ) ; } if ( component . initialStateMarked ( ) ) { return saveMap ( context , deltaMap ) ; } else { return saveMap ( context , defaultMap ) ; } } | One and only implementation of save - state - makes all other implementations unnecessary . | 64 | 15 |
18,248 | public void restoreState ( FacesContext context , Object state ) { if ( context == null ) { throw new NullPointerException ( ) ; } if ( state == null ) { return ; } if ( ! component . initialStateMarked ( ) && ! defaultMap . isEmpty ( ) ) { defaultMap . clear ( ) ; if ( deltaMap != null && ! deltaMap . isEmpty ( ) ) { deltaMap . clear ( ) ; } } Object [ ] savedState = ( Object [ ] ) state ; if ( savedState [ savedState . length - 1 ] != null ) { component . initialState = ( Boolean ) savedState [ savedState . length - 1 ] ; } int length = ( savedState . length - 1 ) / 2 ; for ( int i = 0 ; i < length ; i ++ ) { Object value = savedState [ i * 2 + 1 ] ; Serializable serializable = ( Serializable ) savedState [ i * 2 ] ; if ( value != null ) { if ( value instanceof Collection ) { value = restoreAttachedState ( context , value ) ; } else if ( value instanceof StateHolderSaver ) { value = ( ( StateHolderSaver ) value ) . restore ( context ) ; } else { value = ( value instanceof Serializable ? value : restoreAttachedState ( context , value ) ) ; } } if ( value instanceof Map ) { for ( Map . Entry < String , Object > entry : ( ( Map < String , Object > ) value ) . entrySet ( ) ) { this . put ( serializable , entry . getKey ( ) , entry . getValue ( ) ) ; } } else if ( value instanceof List ) { List < Object > list = ( List ) get ( serializable ) ; for ( Object o : ( ( List < Object > ) value ) ) { if ( list == null || ! list . contains ( o ) ) { this . add ( serializable , o ) ; } } } else { put ( serializable , value ) ; } } } | One and only implementation of restore state . Makes all other implementations unnecessary . | 432 | 14 |
18,249 | private void advance ( ) { try { if ( tok == null ) tok = source . token ( ) ; } catch ( LexerException e ) { throw new IllegalStateException ( e ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } | Rethrows IOException inside IllegalStateException . | 61 | 10 |
18,250 | @ Override public Token next ( ) { if ( ! hasNext ( ) ) throw new NoSuchElementException ( ) ; Token t = this . tok ; this . tok = null ; return t ; } | Returns the next token from the enclosed Source . | 45 | 9 |
18,251 | private static Object saveBindings ( FacesContext context , Map < String , ValueExpression > bindings ) { // Note: This code is copied from UIComponentBase. In a future // version of the JSF spec, it would be useful to define a // attribute/property/bindings/state helper object that can be // shared across components/behaviors/validaters/converters. if ( bindings == null ) { return ( null ) ; } Object values [ ] = new Object [ 2 ] ; values [ 0 ] = bindings . keySet ( ) . toArray ( new String [ bindings . size ( ) ] ) ; Object [ ] bindingValues = bindings . values ( ) . toArray ( ) ; for ( int i = 0 ; i < bindingValues . length ; i ++ ) { bindingValues [ i ] = UIComponentBase . saveAttachedState ( context , bindingValues [ i ] ) ; } values [ 1 ] = bindingValues ; return ( values ) ; } | Utility for saving bindings state | 210 | 6 |
18,252 | private static Map < String , ValueExpression > restoreBindings ( FacesContext context , Object state ) { // Note: This code is copied from UIComponentBase. See note above // in saveBindings(). if ( state == null ) { return ( null ) ; } Object values [ ] = ( Object [ ] ) state ; String names [ ] = ( String [ ] ) values [ 0 ] ; Object states [ ] = ( Object [ ] ) values [ 1 ] ; Map < String , ValueExpression > bindings = new HashMap < String , ValueExpression > ( names . length ) ; for ( int i = 0 ; i < names . length ; i ++ ) { bindings . put ( names [ i ] , ( ValueExpression ) UIComponentBase . restoreAttachedState ( context , states [ i ] ) ) ; } return ( bindings ) ; } | Utility for restoring bindings from state | 184 | 7 |
18,253 | private void setLiteralValue ( String propertyName , ValueExpression expression ) { assert ( expression . isLiteralText ( ) ) ; Object value ; ELContext context = FacesContext . getCurrentInstance ( ) . getELContext ( ) ; try { value = expression . getValue ( context ) ; } catch ( ELException ele ) { throw new FacesException ( ele ) ; } if ( ONEVENT . equals ( propertyName ) ) { onevent = ( String ) value ; } else if ( DELAY . equals ( propertyName ) ) { delay = ( String ) value ; } else if ( ONERROR . equals ( propertyName ) ) { onerror = ( String ) value ; } else if ( IMMEDIATE . equals ( propertyName ) ) { immediate = ( Boolean ) value ; } else if ( RESET_VALUES . equals ( propertyName ) ) { resetValues = ( Boolean ) value ; } else if ( DISABLED . equals ( propertyName ) ) { disabled = ( Boolean ) value ; } else if ( EXECUTE . equals ( propertyName ) ) { execute = toList ( propertyName , expression , value ) ; } else if ( RENDER . equals ( propertyName ) ) { render = toList ( propertyName , expression , value ) ; } } | Sets a property converting it from a literal | 275 | 9 |
18,254 | private static List < String > toSingletonList ( String propertyName , String value ) { if ( ( null == value ) || ( value . length ( ) == 0 ) ) { return null ; } if ( value . charAt ( 0 ) == ' ' ) { // These are very common, so we use shared copies // of these collections instead of re-creating. List < String > list ; if ( ALL . equals ( value ) ) { list = ALL_LIST ; } else if ( FORM . equals ( value ) ) { list = FORM_LIST ; } else if ( THIS . equals ( value ) ) { list = THIS_LIST ; } else if ( NONE . equals ( value ) ) { list = NONE_LIST ; } else { // RELEASE_PENDING i18n ; throw new FacesException ( value + " : Invalid id keyword specified for '" + propertyName + "' attribute" ) ; } return list ; } return Collections . singletonList ( value ) ; } | Converts a String with no spaces to a singleton list | 210 | 12 |
18,255 | private static Object [ ] toObjectArray ( Object primitiveArray ) { if ( primitiveArray == null ) { throw new NullPointerException ( ) ; } if ( primitiveArray instanceof Object [ ] ) { return ( Object [ ] ) primitiveArray ; } if ( primitiveArray instanceof Collection ) { return ( ( Collection ) primitiveArray ) . toArray ( ) ; } Class clazz = primitiveArray . getClass ( ) ; if ( ! clazz . isArray ( ) ) { return null ; } int length = Array . getLength ( primitiveArray ) ; Object [ ] array = new Object [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { array [ i ] = Array . get ( primitiveArray , i ) ; } return array ; } | Convert an array of primitives to an array of boxed objects . | 163 | 14 |
18,256 | public boolean hasMessageOf ( String property ) { assertArgumentNotNull ( "property" , property ) ; final UserMessageItem item = getPropertyItem ( property ) ; return item != null && ! item . getMessageList ( ) . isEmpty ( ) ; } | Does the property has user message? | 56 | 7 |
18,257 | public boolean hasMessageOf ( String property , String messageKey ) { assertArgumentNotNull ( "property" , property ) ; assertArgumentNotNull ( "messageKey" , messageKey ) ; final UserMessageItem item = getPropertyItem ( property ) ; return item != null && item . getMessageList ( ) . stream ( ) . anyMatch ( message -> { final String myKey = resolveMessageKey ( messageKey ) ; if ( message . isResource ( ) ) { if ( myKey . equals ( resolveMessageKey ( message . getMessageKey ( ) ) ) ) { return true ; } } else { // direct message if ( message . getValidatorMessageKey ( ) . filter ( vlkey -> resolveMessageKey ( vlkey ) . equals ( myKey ) ) . isPresent ( ) ) { return true ; } } return false ; } ) ; } | Does the property has user message for the message key? | 185 | 11 |
18,258 | private static int _indexOfStartingFrom ( List < ? > list , int startIndex , Object searchValue ) { int itemCount = list . size ( ) ; boolean found = false ; // start searching from location remembered from last time for ( int currIndex = startIndex ; currIndex < itemCount ; currIndex ++ ) { Object currId = list . get ( currIndex ) ; if ( ( searchValue == currId ) || ( ( searchValue != null ) && searchValue . equals ( currId ) ) ) { return currIndex ; } } // handle case where we started past the first item and didn't find the // searchValue. Now search from the beginning to where we started if ( startIndex > 0 ) { for ( int currIndex = 0 ; currIndex < startIndex ; currIndex ++ ) { Object currId = list . get ( currIndex ) ; if ( ( searchValue == currId ) || ( ( searchValue != null ) && searchValue . equals ( currId ) ) ) { return currIndex ; } } } // didn't find it return - 1 ; } | Similar to List . indexOf except that we start searching from a specific index and then wrap aroud . For this to be performant the List should implement RandomAccess . | 244 | 34 |
18,259 | private Resource findComponentResourceBundleLocaleMatch ( FacesContext context , String resourceName , String libraryName ) { Resource result = null ; ResourceBundle resourceBundle = null ; int i ; if ( - 1 != ( i = resourceName . lastIndexOf ( "." ) ) ) { resourceName = resourceName . substring ( 0 , i ) + ".properties" ; if ( null != context ) { result = context . getApplication ( ) . getResourceHandler ( ) . createResource ( resourceName , libraryName ) ; InputStream propertiesInputStream = null ; try { propertiesInputStream = result . getInputStream ( ) ; resourceBundle = new PropertyResourceBundle ( propertiesInputStream ) ; } catch ( IOException ex ) { Logger . getLogger ( UIComponent . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } finally { if ( null != propertiesInputStream ) { try { propertiesInputStream . close ( ) ; } catch ( IOException ioe ) { if ( LOGGER . isLoggable ( Level . SEVERE ) ) { LOGGER . log ( Level . SEVERE , null , ioe ) ; } } } } } } result = ( null != resourceBundle ) ? result : null ; return result ; } | way to handle this . | 280 | 5 |
18,260 | private void clearFacesEvents ( FacesContext context ) { if ( context . getRenderResponse ( ) || context . getResponseComplete ( ) ) { if ( events != null ) { for ( List < FacesEvent > eventList : events ) { if ( eventList != null ) { eventList . clear ( ) ; } } events = null ; } } } | or if there is a response complete signal . | 75 | 9 |
18,261 | private static Locale getLocaleFromString ( String localeStr ) throws IllegalArgumentException { // length must be at least 2. if ( null == localeStr || localeStr . length ( ) < 2 ) { throw new IllegalArgumentException ( "Illegal locale String: " + localeStr ) ; } Locale result = null ; String lang = null ; String country = null ; String variant = null ; char [ ] seps = { ' ' , ' ' } ; int inputLength = localeStr . length ( ) ; int i = 0 ; int j = 0 ; // to have a language, the length must be >= 2 if ( ( inputLength >= 2 ) && ( ( i = indexOfSet ( localeStr , seps , 0 ) ) == - 1 ) ) { // we have only Language, no country or variant if ( 2 != localeStr . length ( ) ) { throw new IllegalArgumentException ( "Illegal locale String: " + localeStr ) ; } lang = localeStr . toLowerCase ( ) ; } // we have a separator, it must be either '-' or '_' if ( i != - 1 ) { lang = localeStr . substring ( 0 , i ) ; // look for the country sep. // to have a country, the length must be >= 5 if ( ( inputLength >= 5 ) && ( - 1 == ( j = indexOfSet ( localeStr , seps , i + 1 ) ) ) ) { // no further separators, length must be 5 if ( inputLength != 5 ) { throw new IllegalArgumentException ( "Illegal locale String: " + localeStr ) ; } country = localeStr . substring ( i + 1 ) ; } if ( j != - 1 ) { country = localeStr . substring ( i + 1 , j ) ; // if we have enough separators for language, locale, // and variant, the length must be >= 8. if ( inputLength >= 8 ) { variant = localeStr . substring ( j + 1 ) ; } else { throw new IllegalArgumentException ( "Illegal locale String: " + localeStr ) ; } } } if ( variant != null && country != null && lang != null ) { result = new Locale ( lang , country , variant ) ; } else if ( lang != null && country != null ) { result = new Locale ( lang , country ) ; } else if ( lang != null ) { result = new Locale ( lang , "" ) ; } return result ; } | language - country - variant . | 531 | 6 |
18,262 | protected String convertToPerformanceView ( long afterMinusBefore ) { // from DfTraceViewUtil.java if ( afterMinusBefore < 0 ) { return String . valueOf ( afterMinusBefore ) ; } long sec = afterMinusBefore / 1000 ; final long min = sec / 60 ; sec = sec % 60 ; final long mil = afterMinusBefore % 1000 ; final StringBuffer sb = new StringBuffer ( ) ; if ( min >= 10 ) { // Minute sb . append ( min ) . append ( "m" ) ; } else if ( min < 10 && min >= 0 ) { sb . append ( "0" ) . append ( min ) . append ( "m" ) ; } if ( sec >= 10 ) { // Second sb . append ( sec ) . append ( "s" ) ; } else if ( sec < 10 && sec >= 0 ) { sb . append ( "0" ) . append ( sec ) . append ( "s" ) ; } if ( mil >= 100 ) { // Millisecond sb . append ( mil ) . append ( "ms" ) ; } else if ( mil < 100 && mil >= 10 ) { sb . append ( "0" ) . append ( mil ) . append ( "ms" ) ; } else if ( mil < 10 && mil >= 0 ) { sb . append ( "00" ) . append ( mil ) . append ( "ms" ) ; } return sb . toString ( ) ; } | Convert to performance view . | 322 | 6 |
18,263 | protected List < Object > resolveLabelParameter ( Locale locale , String key , Object [ ] args ) { final MessageResourceBundle bundle = getBundle ( locale ) ; if ( args == null || args . length == 0 ) { return DfCollectionUtil . emptyList ( ) ; } final List < Object > resolvedList = new ArrayList < Object > ( args . length ) ; for ( Object arg : args ) { if ( canBeLabelKey ( arg ) ) { final String labelKey = ( String ) arg ; final String label = bundle . get ( labelKey ) ; if ( label != null ) { resolvedList . add ( label ) ; continue ; } else { throwMessageLabelByLabelParameterNotFoundException ( locale , key , labelKey ) ; } } resolvedList . add ( arg ) ; } return resolvedList ; } | Resolve label parameters in the arguments . | 177 | 8 |
18,264 | @ Override public void handleWarning ( Source source , int line , int column , String msg ) throws LexerException { warnings ++ ; print ( source . getName ( ) + ":" + line + ":" + column + ": warning: " + msg ) ; } | Handles a warning . | 57 | 5 |
18,265 | @ Override public void handleError ( Source source , int line , int column , String msg ) throws LexerException { errors ++ ; print ( source . getName ( ) + ":" + line + ":" + column + ": error: " + msg ) ; } | Handles an error . | 57 | 5 |
18,266 | protected OptionalThing < ClassificationMeta > findMeta ( Class < ? > defmetaType , String classificationName ) { return LaClassificationUtil . findMeta ( defmetaType , classificationName ) ; } | helper for sub class | 43 | 5 |
18,267 | private void executeValidate ( FacesContext context ) { try { validate ( context ) ; } catch ( RuntimeException e ) { context . renderResponse ( ) ; throw e ; } if ( ! isValid ( ) ) { context . validationFailed ( ) ; context . renderResponse ( ) ; } } | Executes validation logic . | 63 | 5 |
18,268 | protected void fire ( ActionRuntime runtime ) throws IOException , ServletException { final ActionResponseReflector reflector = createResponseReflector ( runtime ) ; ready ( runtime , reflector ) ; final OptionalThing < VirtualForm > form = prepareActionForm ( runtime ) ; populateParameter ( runtime , form ) ; final VirtualAction action = createAction ( runtime , reflector ) ; final NextJourney journey = performAction ( action , form , runtime ) ; // #to_action toNext ( runtime , journey ) ; } | Fire the action creating populating performing and to next . | 111 | 11 |
18,269 | protected GsonJsonEngine createGsonJsonEngine ( JsonEngineResource resource ) { final boolean serializeNulls = isGsonSerializeNulls ( ) ; final boolean prettyPrinting = isGsonPrettyPrinting ( ) ; final Consumer < GsonBuilder > builderSetupper = prepareGsonBuilderSetupper ( serializeNulls , prettyPrinting ) ; final Consumer < JsonMappingOption > optionSetupper = prepareMappingOptionSetupper ( resource . getMappingOption ( ) ) ; return resource . getYourEngineCreator ( ) . map ( creator -> { // rare option return createYourEngine ( creator , builderSetupper , optionSetupper ) ; } ) . orElseGet ( ( ) -> { // mainly here return newGsonJsonEngine ( builderSetupper , optionSetupper ) ; } ) ; } | mappingOption is specified for another engine | 180 | 8 |
18,270 | public static BegunTx < ? > getBegunTxOnThread ( ) { final Stack < BegunTx < ? > > stack = threadLocal . get ( ) ; return stack != null ? stack . peek ( ) : null ; } | Get prepared begun - tx on thread . | 50 | 8 |
18,271 | public static void setBegunTxOnThread ( BegunTx < ? > begunTx ) { if ( begunTx == null ) { String msg = "The argument[begunTx] must not be null." ; throw new IllegalArgumentException ( msg ) ; } Stack < BegunTx < ? > > stack = threadLocal . get ( ) ; if ( stack == null ) { stack = new Stack < BegunTx < ? > > ( ) ; threadLocal . set ( stack ) ; } stack . add ( begunTx ) ; } | Set prepared begun - tx on thread . | 114 | 8 |
18,272 | public static boolean existsBegunTxOnThread ( ) { final Stack < BegunTx < ? > > stack = threadLocal . get ( ) ; return stack != null ? ! stack . isEmpty ( ) : false ; } | Is existing prepared begun - tx on thread? | 47 | 9 |
18,273 | public static void clearBegunTxOnThread ( ) { final Stack < BegunTx < ? > > stack = threadLocal . get ( ) ; if ( stack != null ) { stack . pop ( ) ; // remove latest if ( stack . isEmpty ( ) ) { perfectlyClear ( ) ; } } } | Clear prepared begun - tx on thread . | 65 | 8 |
18,274 | public static RomanticTransaction getRomanticTransaction ( ) { final Stack < RomanticTransaction > stack = threadLocal . get ( ) ; return stack != null ? stack . peek ( ) : null ; } | Get the value of the romantic transaction . | 40 | 8 |
18,275 | public static void setRomanticTransaction ( RomanticTransaction romanticTransaction ) { if ( romanticTransaction == null ) { String msg = "The argument 'romanticTransaction' should not be null." ; throw new IllegalArgumentException ( msg ) ; } Stack < RomanticTransaction > stack = threadLocal . get ( ) ; if ( stack == null ) { stack = new Stack < RomanticTransaction > ( ) ; threadLocal . set ( stack ) ; } stack . push ( romanticTransaction ) ; } | Set the value of the romantic transaction . | 100 | 8 |
18,276 | private boolean visitColumnsAndColumnFacets ( VisitContext context , VisitCallback callback , boolean visitRows ) { if ( visitRows ) { setRowIndex ( - 1 ) ; } if ( getChildCount ( ) > 0 ) { for ( UIComponent column : getChildren ( ) ) { if ( column instanceof UIColumn ) { VisitResult result = context . invokeVisitCallback ( column , callback ) ; // visit the column directly if ( result == VisitResult . COMPLETE ) { return true ; } if ( column . getFacetCount ( ) > 0 ) { for ( UIComponent columnFacet : column . getFacets ( ) . values ( ) ) { if ( columnFacet . visitTree ( context , callback ) ) { return true ; } } } } } } return false ; } | Visit each UIColumn and any facets it may have defined exactly once | 176 | 15 |
18,277 | private boolean visitRows ( VisitContext context , VisitCallback callback , boolean visitRows ) { // Iterate over our UIColumn children, once per row int processed = 0 ; int rowIndex = 0 ; int rows = 0 ; if ( visitRows ) { rowIndex = getFirst ( ) - 1 ; rows = getRows ( ) ; } while ( true ) { // Have we processed the requested number of rows? if ( visitRows ) { if ( ( rows > 0 ) && ( ++ processed > rows ) ) { break ; } // Expose the current row in the specified request attribute setRowIndex ( ++ rowIndex ) ; if ( ! isRowAvailable ( ) ) { break ; // Scrolled past the last row } } // Visit as required on the *children* of the UIColumn // (facets have been done a single time with rowIndex=-1 already) if ( getChildCount ( ) > 0 ) { for ( UIComponent kid : getChildren ( ) ) { if ( ! ( kid instanceof UIColumn ) ) { continue ; } if ( kid . getChildCount ( ) > 0 ) { for ( UIComponent grandkid : kid . getChildren ( ) ) { if ( grandkid . visitTree ( context , callback ) ) { return true ; } } } } } if ( ! visitRows ) { break ; } } return false ; } | Visit each column and row | 300 | 5 |
18,278 | public boolean isForwardToHtml ( ) { if ( ! isHtmlResponse ( ) ) { // e.g. exception, AJAX return false ; } final HtmlResponse htmlResponse = ( ( HtmlResponse ) actionResponse ) ; return ! htmlResponse . isRedirectTo ( ) && isHtmlTemplateResponse ( htmlResponse ) ; } | Is the result of the action execute forward to HTML template? | 74 | 12 |
18,279 | public boolean handleActionPath ( String requestPath , ActionFoundPathHandler handler ) throws Exception { assertArgumentNotNull ( "requestPath" , requestPath ) ; assertArgumentNotNull ( "handler" , handler ) ; final MappingPathResource pathResource = customizeActionMapping ( requestPath ) ; return mappingActionPath ( pathResource , handler ) ; } | Handle the action path from the specified request path . | 76 | 10 |
18,280 | public synchronized String encrypt ( String plainText ) { assertArgumentNotNull ( "plainText" , plainText ) ; if ( encryptingCipher == null ) { initialize ( ) ; } return new String ( encodeHex ( doEncrypt ( plainText ) ) ) ; } | Encrypt the text as invertible . | 59 | 9 |
18,281 | public UrlChain moreUrl ( Object ... urlParts ) { final String argTitle = "urlParts" ; assertArgumentNotNull ( argTitle , urlParts ) ; checkWrongUrlChainUse ( argTitle , urlParts ) ; this . urlParts = urlParts ; return this ; } | Set up more URL parts as URL chain . | 62 | 9 |
18,282 | public UrlChain params ( Object ... paramsOnGet ) { final String argTitle = "paramsOnGet" ; assertArgumentNotNull ( argTitle , paramsOnGet ) ; checkWrongUrlChainUse ( argTitle , paramsOnGet ) ; this . paramsOnGet = paramsOnGet ; return this ; } | Set up parameters on GET as URL chain . | 67 | 9 |
18,283 | protected void assertArgumentNotNull ( String argumentName , Object value ) { if ( argumentName == null ) { String msg = "The argument name should not be null: argName=null value=" + value ; throw new IllegalArgumentException ( msg ) ; } if ( value == null ) { String msg = "The value should not be null: argName=" + argumentName ; throw new IllegalArgumentException ( msg ) ; } } | Assert that the argument is not null . | 93 | 9 |
18,284 | @ Nonnull public BigDecimal toBigDecimal ( ) { int scale = 0 ; String text = getIntegerPart ( ) ; String t_fraction = getFractionalPart ( ) ; if ( t_fraction != null ) { text += getFractionalPart ( ) ; // XXX Wrong for anything but base 10. scale += t_fraction . length ( ) ; } String t_exponent = getExponent ( ) ; if ( t_exponent != null ) scale -= Integer . parseInt ( t_exponent ) ; BigInteger unscaled = new BigInteger ( text , getBase ( ) ) ; return new BigDecimal ( unscaled , scale ) ; } | So it turns out that parsing arbitrary bases into arbitrary precision numbers is nontrivial and this routine gets it wrong in many important cases . | 147 | 27 |
18,285 | protected void handleSqlCount ( ActionRuntime runtime ) { final CallbackContext context = CallbackContext . getCallbackContextOnThread ( ) ; if ( context == null ) { return ; } final SqlStringFilter filter = context . getSqlStringFilter ( ) ; if ( filter == null || ! ( filter instanceof ExecutedSqlCounter ) ) { return ; } final ExecutedSqlCounter counter = ( ( ExecutedSqlCounter ) filter ) ; final int sqlExecutionCountLimit = getSqlExecutionCountLimit ( runtime ) ; if ( sqlExecutionCountLimit >= 0 && counter . getTotalCountOfSql ( ) > sqlExecutionCountLimit ) { // minus means no check here, by-annotation cannot specify it, can only as default limit // if it needs to specify it by-annotation, enough to set large size handleTooManySqlExecution ( runtime , counter , sqlExecutionCountLimit ) ; } saveRequestedSqlCount ( counter ) ; } | Handle count of SQL execution in the request . | 213 | 9 |
18,286 | protected void handleTooManySqlExecution ( ActionRuntime runtime , ExecutedSqlCounter sqlCounter , int sqlExecutionCountLimit ) { final int totalCountOfSql = sqlCounter . getTotalCountOfSql ( ) ; final String actionDisp = buildActionDisp ( runtime ) ; logger . warn ( "*Too many SQL executions: {}/{} in {}" , totalCountOfSql , sqlExecutionCountLimit , actionDisp ) ; } | Handle too many SQL executions . | 101 | 6 |
18,287 | protected void handleMailCount ( ActionRuntime runtime ) { if ( ThreadCacheContext . exists ( ) ) { final PostedMailCounter counter = ThreadCacheContext . findMailCounter ( ) ; if ( counter != null ) { saveRequestedMailCount ( counter ) ; } } } | Handle count of mail posting in the request . | 57 | 9 |
18,288 | protected void handleRemoteApiCount ( ActionRuntime runtime ) { if ( ThreadCacheContext . exists ( ) ) { final CalledRemoteApiCounter counter = ThreadCacheContext . findRemoteApiCounter ( ) ; if ( counter != null ) { saveRequestedRemoteApiCount ( counter ) ; } } } | Handle count of remoteApi calling in the request . | 65 | 11 |
18,289 | public UIComponent getFacet ( String name ) { if ( facets != null ) { return ( facets . get ( name ) ) ; } else { return ( null ) ; } } | Do not allocate the facets Map to answer this question | 40 | 10 |
18,290 | private Object saveBehaviorsState ( FacesContext context ) { Object state = null ; if ( null != behaviors && behaviors . size ( ) > 0 ) { boolean stateWritten = false ; Object [ ] attachedBehaviors = new Object [ behaviors . size ( ) ] ; int i = 0 ; for ( List < ClientBehavior > eventBehaviors : behaviors . values ( ) ) { // we need to take different action depending on whether // or not markInitialState() was called. If it's not called, // assume JSF 1.2 style state saving and call through to // saveAttachedState(), otherwise, call saveState() on the // behaviors directly. Object [ ] attachedEventBehaviors = new Object [ eventBehaviors . size ( ) ] ; for ( int j = 0 ; j < attachedEventBehaviors . length ; j ++ ) { attachedEventBehaviors [ j ] = ( ( initialStateMarked ( ) ) ? saveBehavior ( context , eventBehaviors . get ( j ) ) : saveAttachedState ( context , eventBehaviors . get ( j ) ) ) ; if ( ! stateWritten ) { stateWritten = ( attachedEventBehaviors [ j ] != null ) ; } } attachedBehaviors [ i ++ ] = attachedEventBehaviors ; } if ( stateWritten ) { state = new Object [ ] { behaviors . keySet ( ) . toArray ( new String [ behaviors . size ( ) ] ) , attachedBehaviors } ; } } return state ; } | Save state of the behaviors map . | 325 | 7 |
18,291 | @ SuppressWarnings ( "unchecked" ) public static < OBJ > OBJ getObject ( String key ) { if ( ! exists ( ) ) { throwThreadCacheNotInitializedException ( key ) ; } return ( OBJ ) threadLocal . get ( ) . get ( key ) ; } | Get the value of the object by the key . | 64 | 10 |
18,292 | public static void setObject ( String key , Object value ) { if ( ! exists ( ) ) { throwThreadCacheNotInitializedException ( key ) ; } threadLocal . get ( ) . put ( key , value ) ; } | Set the value of the object . | 47 | 7 |
18,293 | @ SuppressWarnings ( "unchecked" ) public static < OBJ > OBJ removeObject ( String key ) { if ( ! exists ( ) ) { throwThreadCacheNotInitializedException ( key ) ; } return ( OBJ ) threadLocal . get ( ) . remove ( key ) ; } | Remove the value of the object from the cache . | 64 | 10 |
18,294 | public static boolean determineObject ( String key ) { if ( ! exists ( ) ) { throwThreadCacheNotInitializedException ( key ) ; } final Object obj = threadLocal . get ( ) . get ( key ) ; return obj != null && ( boolean ) obj ; } | Determine the object as boolean . | 56 | 8 |
18,295 | public static void clearAccessContextOnThread ( ) { final Stack < AccessContext > stack = threadLocal . get ( ) ; if ( stack != null ) { stack . pop ( ) ; // remove latest if ( stack . isEmpty ( ) ) { perfectlyClear ( ) ; } } } | Clear prepared access - context on thread . | 60 | 8 |
18,296 | public static void endAccessContext ( ) { AccessContext . clearAccessContextOnThread ( ) ; final AccessContext accessContext = SuspendedAccessContext . getAccessContextOnThread ( ) ; if ( accessContext != null ) { // resume AccessContext . setAccessContextOnThread ( accessContext ) ; SuspendedAccessContext . clearAccessContextOnThread ( ) ; } } | End access - context use for DBFlute . | 77 | 10 |
18,297 | protected TreeMap < String , Object > prepareOrderedMap ( Object form , Set < ConstraintViolation < Object > > vioSet ) { final Map < String , Object > vioPropMap = new HashMap <> ( vioSet . size ( ) ) ; for ( ConstraintViolation < Object > vio : vioSet ) { final String propertyPath = extractPropertyPath ( vio ) ; final boolean nested = propertyPath . contains ( "." ) ; final String propertyName = nested ? Srl . substringFirstFront ( propertyPath , "." ) : propertyPath ; Object holder = vioPropMap . get ( propertyName ) ; if ( holder == null ) { holder = nested ? new ArrayList <> ( 4 ) : vio ; // direct holder for performance vioPropMap . put ( propertyName , holder ) ; } else if ( holder instanceof ConstraintViolation < ? > ) { @ SuppressWarnings ( "unchecked" ) final ConstraintViolation < Object > existing = ( ( ConstraintViolation < Object > ) holder ) ; final List < Object > listHolder = new ArrayList <> ( 4 ) ; listHolder . add ( existing ) ; listHolder . add ( vio ) ; vioPropMap . put ( propertyName , listHolder ) ; // override } if ( holder instanceof List < ? > ) { @ SuppressWarnings ( "unchecked" ) final List < Object > listHolder = ( List < Object > ) holder ; listHolder . add ( vio ) ; } } final BeanDesc beanDesc = BeanDescFactory . getBeanDesc ( form . getClass ( ) ) ; final int pdSize = beanDesc . getPropertyDescSize ( ) ; final Map < String , Integer > priorityMap = new HashMap <> ( vioPropMap . size ( ) ) ; for ( int i = 0 ; i < pdSize ; i ++ ) { final PropertyDesc pd = beanDesc . getPropertyDesc ( i ) ; final String propertyName = pd . getPropertyName ( ) ; if ( vioPropMap . containsKey ( propertyName ) ) { priorityMap . put ( propertyName , i ) ; } } final TreeMap < String , Object > orderedMap = new TreeMap < String , Object > ( ( key1 , key2 ) -> { final String rootProperty1 = Srl . substringFirstFront ( key1 , "[" , "." ) ; final String rootProperty2 = Srl . substringFirstFront ( key2 , "[" , "." ) ; final Integer priority1 = priorityMap . getOrDefault ( rootProperty1 , Integer . MAX_VALUE ) ; final Integer priority2 = priorityMap . getOrDefault ( rootProperty2 , Integer . MAX_VALUE ) ; if ( priority1 > priority2 ) { return 1 ; } else if ( priority2 > priority1 ) { return - 1 ; } else { /* same group */ return key1 . compareTo ( key2 ) ; } } ) ; orderedMap . putAll ( vioPropMap ) ; return orderedMap ; } | basically for batch display | 673 | 5 |
18,298 | public static boolean cannotBeValidatable ( Object value ) { // called by e.g. ResponseBeanValidator return value instanceof String // yes-yes-yes || value instanceof Number // e.g. Integer || DfTypeUtil . isAnyLocalDate ( value ) // e.g. LocalDate || value instanceof Boolean // of course || value instanceof Classification // e.g. CDef || value . getClass ( ) . isPrimitive ( ) // probably no way, just in case ; } | similar logic is on action response reflector | 110 | 8 |
18,299 | @ CheckForNull public String getPath ( ) { Source parent = getParent ( ) ; if ( parent != null ) return parent . getPath ( ) ; return null ; } | Returns the File currently being lexed . | 37 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.