idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
29,200 | public String [ ] execute ( ) throws IOException , SpotifyWebApiException { List < String > genres = new Gson ( ) . fromJson ( new JsonParser ( ) . parse ( getJson ( ) ) . getAsJsonObject ( ) . get ( "genres" ) . getAsJsonArray ( ) , new TypeToken < List < String > > ( ) { } . getType ( ) ) ; return genres . toArray ( new String [ 0 ] ) ; } | Get all available genre seeds . |
29,201 | @ SuppressWarnings ( "unchecked" ) public PagingCursorbased < PlayHistory > execute ( ) throws IOException , SpotifyWebApiException { return new PlayHistory . JsonUtil ( ) . createModelObjectPagingCursorbased ( getJson ( ) ) ; } | Get an user s recently played tracks . |
29,202 | @ SuppressWarnings ( "unchecked" ) public Paging < Track > execute ( ) throws IOException , SpotifyWebApiException { return new Track . JsonUtil ( ) . createModelObjectPaging ( getJson ( ) ) ; } | Get an user s top tracks . |
29,203 | @ SuppressWarnings ( "unchecked" ) public Paging < AlbumSimplified > execute ( ) throws IOException , SpotifyWebApiException { return new AlbumSimplified . JsonUtil ( ) . createModelObjectPaging ( getJson ( ) , "albums" ) ; } | Search for albums . |
29,204 | @ SuppressWarnings ( "unchecked" ) public Paging < TrackSimplified > execute ( ) throws IOException , SpotifyWebApiException { return new TrackSimplified . JsonUtil ( ) . createModelObjectPaging ( getJson ( ) ) ; } | Get the tracks from the album . |
29,205 | public < T > Future < T > executeAsync ( ) { return SpotifyApiThreading . executeAsync ( new Callable < T > ( ) { public T call ( ) throws IOException , SpotifyWebApiException { return execute ( ) ; } } ) ; } | Get something asynchronously . |
29,206 | @ SuppressWarnings ( "unchecked" ) public Paging < SavedTrack > execute ( ) throws IOException , SpotifyWebApiException { return new SavedTrack . JsonUtil ( ) . createModelObjectPaging ( getJson ( ) ) ; } | Get the songs from the current users Your Music library . |
29,207 | public Boolean [ ] execute ( ) throws IOException , SpotifyWebApiException { return new Gson ( ) . fromJson ( new JsonParser ( ) . parse ( getJson ( ) ) . getAsJsonArray ( ) , Boolean [ ] . class ) ; } | Check whether a user is following a playlist or not . |
29,208 | @ SuppressWarnings ( "unchecked" ) public Paging < Artist > execute ( ) throws IOException , SpotifyWebApiException { return new Artist . JsonUtil ( ) . createModelObjectPaging ( getJson ( ) , "artists" ) ; } | Search for artists . |
29,209 | public void setPostFailureUrl ( String postFailureUrl ) { AuthenticationFailureHandler failureHandler = getFailureHandler ( ) ; if ( failureHandler instanceof SocialAuthenticationFailureHandler ) { failureHandler = ( ( SocialAuthenticationFailureHandler ) failureHandler ) . getDelegate ( ) ; } if ( failureHandler instanceof SimpleUrlAuthenticationFailureHandler ) { SimpleUrlAuthenticationFailureHandler h = ( SimpleUrlAuthenticationFailureHandler ) failureHandler ; h . setDefaultFailureUrl ( postFailureUrl ) ; } else { throw new IllegalStateException ( "can't set postFailureUrl on unknown failureHandler, type is " + failureHandler . getClass ( ) . getName ( ) ) ; } } | The URL to redirect to if authentication fails or if authorization is denied by the user . |
29,210 | void addConnection ( String userId , ConnectionFactoryLocator connectionFactoryLocator , UsersConnectionRepository connectionRepository ) { connectionRepository . createConnectionRepository ( userId ) . addConnection ( getConnection ( connectionFactoryLocator ) ) ; } | Connect the new local user to the provider . |
29,211 | public Connection < ? > completeConnection ( OAuth1ConnectionFactory < ? > connectionFactory , NativeWebRequest request ) { String verifier = request . getParameter ( "oauth_verifier" ) ; AuthorizedRequestToken requestToken = new AuthorizedRequestToken ( extractCachedRequestToken ( request ) , verifier ) ; OAuthToken accessToken = connectionFactory . getOAuthOperations ( ) . exchangeForAccessToken ( requestToken , null ) ; return connectionFactory . createConnection ( accessToken ) ; } | Complete the connection to the OAuth1 provider . |
29,212 | public Connection < ? > completeConnection ( OAuth2ConnectionFactory < ? > connectionFactory , NativeWebRequest request ) { if ( connectionFactory . supportsStateParameter ( ) ) { verifyStateParameter ( request ) ; } String code = request . getParameter ( "code" ) ; try { AccessGrant accessGrant = connectionFactory . getOAuthOperations ( ) . exchangeForAccess ( code , callbackUrl ( request ) , null ) ; return connectionFactory . createConnection ( accessGrant ) ; } catch ( HttpClientErrorException e ) { logger . warn ( "HttpClientErrorException while completing connection: " + e . getMessage ( ) ) ; logger . warn ( " Response body: " + e . getResponseBodyAsString ( ) ) ; throw e ; } } | Complete the connection to the OAuth2 provider . |
29,213 | protected BeanDefinition getConnectionFactoryBeanDefinition ( String appId , String appSecret , Map < String , Object > allAttributes ) { return BeanDefinitionBuilder . genericBeanDefinition ( connectionFactoryClass ) . addConstructorArgValue ( appId ) . addConstructorArgValue ( appSecret ) . getBeanDefinition ( ) ; } | Creates a BeanDefinition for a provider connection factory . Although most providers will not need to override this method it does allow for overriding to address any provider - specific needs . |
29,214 | protected BeanDefinitionBuilder getApiHelperBeanDefinitionBuilder ( Map < String , Object > allAttributes ) { return BeanDefinitionBuilder . genericBeanDefinition ( apiHelperClass ) . addConstructorArgReference ( "usersConnectionRepository" ) . addConstructorArgReference ( "userIdSource" ) ; } | Subclassing hook to allow api helper bean to be configured with attributes from annotation |
29,215 | protected void initKey ( String providerId , String providerUserId ) { if ( providerUserId == null ) { providerUserId = setValues ( ) . providerUserId ; } key = new ConnectionKey ( providerId , providerUserId ) ; } | Hook that should be called by subclasses to initialize the key property when establishing a new connection . |
29,216 | public void addDisconnectInterceptor ( DisconnectInterceptor < ? > interceptor ) { Class < ? > serviceApiType = GenericTypeResolver . resolveTypeArgument ( interceptor . getClass ( ) , DisconnectInterceptor . class ) ; disconnectInterceptors . add ( serviceApiType , interceptor ) ; } | Adds a DisconnectInterceptor to receive callbacks during the disconnection process . Useful for programmatic configuration . |
29,217 | @ RequestMapping ( method = RequestMethod . GET ) public String connectionStatus ( NativeWebRequest request , Model model ) { setNoCache ( request ) ; processFlash ( request , model ) ; Map < String , List < Connection < ? > > > connections = connectionRepository . findAllConnections ( ) ; model . addAttribute ( "providerIds" , connectionFactoryLocator . registeredProviderIds ( ) ) ; model . addAttribute ( "connectionMap" , connections ) ; return connectView ( ) ; } | Render the status of connections across all providers to the user as HTML in their web browser . |
29,218 | public URIBuilder queryParam ( String name , String value ) { parameters . add ( name , value ) ; return this ; } | Adds a query parameter to the URI |
29,219 | public URI build ( ) { try { StringBuilder builder = new StringBuilder ( ) ; Set < Entry < String , List < String > > > entrySet = parameters . entrySet ( ) ; for ( Iterator < Entry < String , List < String > > > entryIt = entrySet . iterator ( ) ; entryIt . hasNext ( ) ; ) { Entry < String , List < String > > entry = entryIt . next ( ) ; String name = entry . getKey ( ) ; List < String > values = entry . getValue ( ) ; for ( Iterator < String > valueIt = values . iterator ( ) ; valueIt . hasNext ( ) ; ) { String value = valueIt . next ( ) ; builder . append ( formEncode ( name ) ) . append ( "=" ) ; if ( value != null ) { builder . append ( formEncode ( value ) ) ; } if ( valueIt . hasNext ( ) ) { builder . append ( "&" ) ; } } if ( entryIt . hasNext ( ) ) { builder . append ( "&" ) ; } } String queryDelimiter = "?" ; if ( URI . create ( baseUri ) . getQuery ( ) != null ) { queryDelimiter = "&" ; } return new URI ( baseUri + ( builder . length ( ) > 0 ? queryDelimiter + builder . toString ( ) : "" ) ) ; } catch ( URISyntaxException e ) { throw new URIBuilderException ( "Unable to build URI: Bad URI syntax" , e ) ; } } | Builds the URI |
29,220 | public static RestTemplate create ( OAuth1Credentials credentials ) { RestTemplate client = new RestTemplate ( ClientHttpRequestFactorySelector . getRequestFactory ( ) ) ; OAuth1RequestInterceptor interceptor = new OAuth1RequestInterceptor ( credentials ) ; List < ClientHttpRequestInterceptor > interceptors = new LinkedList < ClientHttpRequestInterceptor > ( ) ; interceptors . add ( interceptor ) ; client . setInterceptors ( interceptors ) ; return client ; } | Constructs a RestTemplate that adds the OAuth1 Authorization header to each request before it is executed . |
29,221 | public String buildAuthorizationHeaderValue ( HttpMethod method , URI targetUrl , Map < String , String > oauthParameters , MultiValueMap < String , String > additionalParameters , String consumerSecret , String tokenSecret ) { StringBuilder header = new StringBuilder ( ) ; header . append ( "OAuth " ) ; for ( Entry < String , String > entry : oauthParameters . entrySet ( ) ) { header . append ( oauthEncode ( entry . getKey ( ) ) ) . append ( "=\"" ) . append ( oauthEncode ( entry . getValue ( ) ) ) . append ( "\", " ) ; } MultiValueMap < String , String > collectedParameters = new LinkedMultiValueMap < String , String > ( ( int ) ( ( oauthParameters . size ( ) + additionalParameters . size ( ) ) / .75 + 1 ) ) ; collectedParameters . setAll ( oauthParameters ) ; collectedParameters . putAll ( additionalParameters ) ; String baseString = buildBaseString ( method , getBaseStringUri ( targetUrl ) , collectedParameters ) ; String signature = calculateSignature ( baseString , consumerSecret , tokenSecret ) ; header . append ( oauthEncode ( "oauth_signature" ) ) . append ( "=\"" ) . append ( oauthEncode ( signature ) ) . append ( "\"" ) ; return header . toString ( ) ; } | Builds the authorization header . The elements in additionalParameters are expected to not be encoded . |
29,222 | public String buildAuthorizationHeaderValue ( HttpRequest request , byte [ ] body , OAuth1Credentials oauth1Credentials ) { Map < String , String > oauthParameters = commonOAuthParameters ( oauth1Credentials . getConsumerKey ( ) ) ; oauthParameters . put ( "oauth_token" , oauth1Credentials . getAccessToken ( ) ) ; MultiValueMap < String , String > additionalParameters = union ( readFormParameters ( request . getHeaders ( ) . getContentType ( ) , body ) , parseFormParameters ( request . getURI ( ) . getRawQuery ( ) ) ) ; return buildAuthorizationHeaderValue ( request . getMethod ( ) , request . getURI ( ) , oauthParameters , additionalParameters , oauth1Credentials . getConsumerSecret ( ) , oauth1Credentials . getAccessTokenSecret ( ) ) ; } | Builds an authorization header from a request . Expects that the request s query parameters are form - encoded . |
29,223 | private MultiValueMap < String , String > union ( MultiValueMap < String , String > map1 , MultiValueMap < String , String > map2 ) { MultiValueMap < String , String > union = new LinkedMultiValueMap < String , String > ( map1 ) ; Set < Entry < String , List < String > > > map2Entries = map2 . entrySet ( ) ; for ( Iterator < Entry < String , List < String > > > entryIt = map2Entries . iterator ( ) ; entryIt . hasNext ( ) ; ) { Entry < String , List < String > > entry = entryIt . next ( ) ; String key = entry . getKey ( ) ; List < String > values = entry . getValue ( ) ; for ( String value : values ) { union . add ( key , value ) ; } } return union ; } | can t use putAll here because it will overwrite anything that has the same key in both maps |
29,224 | public void stop ( ) { int notProcessed = worker . shutdownNow ( ) . size ( ) ; if ( notProcessed != 0 ) { LogFilter . log ( LOGGER , LogLevel . INFO , "Worker exiting, {} execution events remaining, time: {}" , notProcessed , System . currentTimeMillis ( ) ) ; } } | Shutdowns StatisticsQueue completely new StatisticsQueue should be created to start gathering statistics again |
29,225 | public Future enqueue ( final QueryExecutionEvent event ) { if ( ! paused ) { return worker . submit ( new Runnable ( ) { public void run ( ) { QueryStats queryStats = statsByQuery . get ( event . getQuery ( ) ) ; if ( queryStats == null ) { statsByQuery . put ( event . getQuery ( ) , queryStats = new QueryStats ( event . getQuery ( ) ) ) ; } queryStats . addQueryTime ( event . getTime ( ) ) ; } } ) ; } else { return null ; } } | Enqueues a query execution event for processing . |
29,226 | public List < QueryStats > getReportSortedBy ( String sortByVal ) { SortBy sortBy ; try { sortBy = SortBy . valueOf ( sortByVal ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "allowed values are: " + Arrays . toString ( SortBy . values ( ) ) ) ; } List < QueryStats > res = new ArrayList < > ( statsByQuery . values ( ) ) ; Collections . sort ( res , sortBy . getComparator ( ) ) ; return res ; } | Produces a report sorted by one of the accepted value . |
29,227 | public static < T extends Model > T findOrCreateIt ( Object ... namesAndValues ) { return ModelDelegate . findOrCreateIt ( modelClass ( ) , namesAndValues ) ; } | A convenience method to fetch existing model from db or to create and insert new record with attribute values . |
29,228 | public static < T extends Model > T findOrInit ( Object ... namesAndValues ) { return ModelDelegate . findOrInit ( modelClass ( ) , namesAndValues ) ; } | A convenience method to fetch existing model from db or to create a new instance in memory initialized with some attribute values . |
29,229 | protected Set < String > hydrate ( Map < String , Object > attributesMap , boolean fireAfterLoad ) { Set < String > changedAttributeNames = new HashSet < > ( ) ; Set < String > attributeNames = metaModelLocal . getAttributeNames ( ) ; for ( Map . Entry < String , Object > entry : attributesMap . entrySet ( ) ) { if ( attributeNames . contains ( entry . getKey ( ) ) ) { if ( entry . getValue ( ) instanceof Clob && metaModelLocal . cached ( ) ) { String convertedString = Convert . toString ( entry . getValue ( ) ) ; if ( willAttributeModifyModel ( entry . getKey ( ) , convertedString ) ) { this . attributes . put ( entry . getKey ( ) , convertedString ) ; changedAttributeNames . add ( entry . getKey ( ) ) ; } } else { Object convertedObject = metaModelLocal . getDialect ( ) . overrideDriverTypeConversion ( metaModelLocal , entry . getKey ( ) , entry . getValue ( ) ) ; if ( willAttributeModifyModel ( entry . getKey ( ) , convertedObject ) ) { this . attributes . put ( entry . getKey ( ) , convertedObject ) ; changedAttributeNames . add ( entry . getKey ( ) ) ; } } } } if ( getCompositeKeys ( ) != null ) { compositeKeyPersisted = true ; } if ( fireAfterLoad ) { fireAfterLoad ( ) ; } return changedAttributeNames ; } | Hydrates a this instance of model from a map . Only picks values from a map that match this instance s attribute names while ignoring the others . |
29,230 | private boolean willAttributeModifyModel ( String attributeName , Object newValue ) { Object currentValue = get ( attributeName ) ; return currentValue != null ? ! currentValue . equals ( newValue ) : newValue != null ; } | Verifies if the passed value for attributeName will set this instance to modified state . |
29,231 | public void set ( String [ ] attributeNames , Object [ ] values ) { if ( attributeNames == null || values == null || attributeNames . length != values . length ) { throw new IllegalArgumentException ( "must pass non-null arrays of equal length" ) ; } for ( int i = 0 ; i < attributeNames . length ; i ++ ) { set ( attributeNames [ i ] , values [ i ] ) ; } } | Sets values for this model instance . The sequence of values must correspond to sequence of names . |
29,232 | private < T extends Model > T setRaw ( String attributeName , Object value ) { if ( manageTime && attributeName . equalsIgnoreCase ( "created_at" ) ) { throw new IllegalArgumentException ( "cannot set 'created_at'" ) ; } metaModelLocal . checkAttribute ( attributeName ) ; if ( willAttributeModifyModel ( attributeName , value ) ) { attributes . put ( attributeName , value ) ; dirtyAttributeNames . add ( attributeName ) ; } return ( T ) this ; } | Sets raw value of an attribute without applying conversions . |
29,233 | private void deleteManyToManyLinks ( Many2ManyAssociation association ) { String join = association . getJoin ( ) ; String sourceFK = association . getSourceFkName ( ) ; new DB ( metaModelLocal . getDbName ( ) ) . exec ( "DELETE FROM " + join + " WHERE " + sourceFK + " = ?" , getId ( ) ) ; } | Deletes all records from a join table related to this model . |
29,234 | private void deleteOne2ManyChildrenShallow ( OneToManyAssociation association ) { String targetTable = metaModelOf ( association . getTargetClass ( ) ) . getTableName ( ) ; new DB ( metaModelLocal . getDbName ( ) ) . exec ( "DELETE FROM " + targetTable + " WHERE " + association . getFkName ( ) + " = ?" , getId ( ) ) ; } | Deletes immediate children . |
29,235 | private void deletePolymorphicChildrenShallow ( OneToManyPolymorphicAssociation association ) { String targetTable = metaModelOf ( association . getTargetClass ( ) ) . getTableName ( ) ; String parentType = association . getTypeLabel ( ) ; new DB ( metaModelLocal . getDbName ( ) ) . exec ( "DELETE FROM " + targetTable + " WHERE parent_id = ? AND parent_type = ?" , getId ( ) , parentType ) ; } | Deletes immediate polymorphic children |
29,236 | public boolean exists ( ) { return null != new DB ( metaModelLocal . getDbName ( ) ) . firstCell ( metaModelLocal . getDialect ( ) . selectExists ( metaModelLocal ) , getId ( ) ) ; } | Returns true if record corresponding to the id of this instance exists in the DB . |
29,237 | public static int update ( String updates , String conditions , Object ... params ) { return ModelDelegate . update ( modelClass ( ) , updates , conditions , params ) ; } | Updates records associated with this model . |
29,238 | public static int updateAll ( String updates , Object ... params ) { return ModelDelegate . updateAll ( modelClass ( ) , updates , params ) ; } | Updates all records associated with this model . |
29,239 | public Map < String , Object > toMap ( ) { Map < String , Object > retVal = new TreeMap < > ( ) ; for ( Map . Entry < String , Object > entry : attributes . entrySet ( ) ) { Object v = entry . getValue ( ) ; if ( v != null ) { if ( v instanceof Clob ) { retVal . put ( entry . getKey ( ) . toLowerCase ( ) , Convert . toString ( v ) ) ; } else { retVal . put ( entry . getKey ( ) . toLowerCase ( ) , v ) ; } } } for ( Entry < Class , Model > parent : cachedParents . entrySet ( ) ) { retVal . put ( underscore ( parent . getKey ( ) . getSimpleName ( ) ) , parent . getValue ( ) . toMap ( ) ) ; } for ( Entry < Class , List < Model > > cachedChild : cachedChildren . entrySet ( ) ) { List < Model > children = cachedChild . getValue ( ) ; List < Map > childMaps = new ArrayList < > ( children . size ( ) ) ; for ( Model child : children ) { childMaps . add ( child . toMap ( ) ) ; } retVal . put ( tableize ( cachedChild . getKey ( ) . getSimpleName ( ) ) , childMaps ) ; } return retVal ; } | Returns all values of the model with all attribute names converted to lower case regardless how these names came from DB . This method is a convenience method for displaying values on web pages . |
29,240 | public void beforeClosingTag ( StringBuilder sb , boolean pretty , String indent , String ... attributeNames ) { StringWriter writer = new StringWriter ( ) ; beforeClosingTag ( indent . length ( ) , writer , attributeNames ) ; sb . append ( writer . toString ( ) ) ; } | Override in a subclass to inject custom content onto XML just before the closing tag . |
29,241 | public String toJson ( boolean pretty , String ... attributeNames ) { StringBuilder sb = new StringBuilder ( ) ; toJsonP ( sb , pretty , "" , attributeNames ) ; return sb . toString ( ) ; } | Generates a JSON document from content of this model . |
29,242 | public void beforeClosingBrace ( StringBuilder sb , boolean pretty , String indent , String ... attributeNames ) { StringWriter writer = new StringWriter ( ) ; beforeClosingBrace ( pretty , indent , writer ) ; sb . append ( writer . toString ( ) ) ; } | Override in subclasses in order to inject custom content into Json just before the closing brace . |
29,243 | public void refresh ( ) { QueryCache . instance ( ) . purgeTableCache ( metaModelLocal ) ; Model fresh = ModelDelegate . findById ( this . getClass ( ) , getId ( ) ) ; if ( fresh == null ) { throw new StaleModelException ( "Failed to refresh self because probably record with " + "this ID does not exist anymore. Stale model: " + this ) ; } fresh . copyTo ( this ) ; dirtyAttributeNames . clear ( ) ; } | Re - reads all attribute values from DB . Will invalidate cache and will force a trip to the database . |
29,244 | private Object getRaw ( String attributeName ) { if ( frozen ) { throw new FrozenException ( this ) ; } if ( attributeName == null ) { throw new IllegalArgumentException ( "attributeName cannot be null" ) ; } metaModelLocal . checkAttribute ( attributeName ) ; return attributes . get ( attributeName ) ; } | Gets raw value of the attribute without conversions applied . |
29,245 | public < C extends Model > LazyList < C > get ( Class < C > targetModelClass , String criteria , Object ... params ) { OneToManyAssociation oneToManyAssociation = metaModelLocal . getAssociationForTarget ( targetModelClass , OneToManyAssociation . class ) ; MetaModel mm = metaModelLocal ; Many2ManyAssociation manyToManyAssociation = metaModelLocal . getAssociationForTarget ( targetModelClass , Many2ManyAssociation . class ) ; OneToManyPolymorphicAssociation oneToManyPolymorphicAssociation = metaModelLocal . getAssociationForTarget ( targetModelClass , OneToManyPolymorphicAssociation . class ) ; String additionalCriteria = criteria != null ? " AND ( " + criteria + " ) " : "" ; String subQuery ; String targetId = metaModelOf ( targetModelClass ) . getIdName ( ) ; MetaModel targetMM = metaModelOf ( targetModelClass ) ; String targetTable = targetMM . getTableName ( ) ; if ( oneToManyAssociation != null ) { subQuery = oneToManyAssociation . getFkName ( ) + " = ? " + additionalCriteria ; } else if ( manyToManyAssociation != null ) { String joinTable = manyToManyAssociation . getJoin ( ) ; String query = "SELECT " + targetTable + ".* FROM " + targetTable + ", " + joinTable + " WHERE " + targetTable + "." + targetId + " = " + joinTable + "." + manyToManyAssociation . getTargetFkName ( ) + " AND " + joinTable + "." + manyToManyAssociation . getSourceFkName ( ) + " = ? " + additionalCriteria ; Object [ ] allParams = new Object [ params . length + 1 ] ; allParams [ 0 ] = getId ( ) ; System . arraycopy ( params , 0 , allParams , 1 , params . length ) ; return new LazyList < > ( true , metaModelOf ( manyToManyAssociation . getTargetClass ( ) ) , query , allParams ) ; } else if ( oneToManyPolymorphicAssociation != null ) { subQuery = "parent_id = ? AND " + " parent_type = '" + oneToManyPolymorphicAssociation . getTypeLabel ( ) + "'" + additionalCriteria ; } else { throw new NotAssociatedException ( metaModelLocal . getModelClass ( ) , targetModelClass ) ; } Object [ ] allParams = new Object [ params . length + 1 ] ; allParams [ 0 ] = getId ( ) ; System . arraycopy ( params , 0 , allParams , 1 , params . length ) ; return new LazyList < > ( subQuery , targetMM , allParams ) ; } | Provides a list of child models in one to many many to many and polymorphic associations but in addition also allows to filter this list by criteria . |
29,246 | protected static void addScope ( String name , String criteria ) { ModelDelegate . addScope ( modelClass ( ) . getName ( ) , name , criteria ) ; } | Use in a static block of a model definotion to add a scope . |
29,247 | protected static ValidationBuilder validateRegexpOf ( String attributeName , String pattern ) { return ModelDelegate . validateRegexpOf ( modelClass ( ) , attributeName , pattern ) ; } | Validates an attribite format with a ree hand regular expression . |
29,248 | protected static ValidationBuilder convertWith ( org . javalite . activejdbc . validation . Converter converter ) { return ModelDelegate . convertWith ( modelClass ( ) , converter ) ; } | Adds a custom converter to the model . |
29,249 | protected static void convertWith ( Converter converter , String ... attributeNames ) { ModelDelegate . convertWith ( modelClass ( ) , converter , attributeNames ) ; } | Registers a custom converter for the specified attributes . |
29,250 | public void validate ( ) { fireBeforeValidation ( ) ; errors = new Errors ( ) ; List < Validator > validators = modelRegistryLocal . validators ( ) ; if ( validators != null ) { for ( Validator validator : validators ) { validator . validate ( this ) ; } } fireAfterValidation ( ) ; } | Executes all validators attached to this model . |
29,251 | public void addValidator ( Validator validator , String errorKey ) { if ( ! errors . containsKey ( errorKey ) ) errors . addValidator ( errorKey , validator ) ; } | Binds a validator to an attribute if validation fails . |
29,252 | public static Long count ( String query , Object ... params ) { return ModelDelegate . count ( modelClass ( ) , query , params ) ; } | Returns count of records in table under a condition . |
29,253 | public static String setProperty ( String name , String value ) { String val = null ; if ( props . containsKey ( name ) ) { val = props . get ( name ) . getValue ( ) ; } props . put ( name , new Property ( name , value , "dynamically added" ) ) ; LOGGER . warn ( "Temporary overriding property: " + name + ". Old value: " + val + ". New value: " + value ) ; return val ; } | Sets a property in memory . If property exists it will be overwritten if not a new one will be created . |
29,254 | public static String getProperty ( String key ) { if ( ! isInited ( ) ) { init ( ) ; } Property p = props . get ( key ) ; return p == null ? null : p . getValue ( ) ; } | Returns property value for a key . |
29,255 | public static List < String > getKeys ( String prefix ) { List < String > res = new ArrayList < > ( ) ; for ( String key : props . keySet ( ) ) { if ( key . startsWith ( prefix ) ) { res . add ( key ) ; } } return res ; } | Returns all keys that start with a prefix |
29,256 | public void addQueryTime ( long time ) { if ( time < min || min == 0 ) min = time ; if ( time > max || max == 0 ) max = time ; avg = Math . round ( ( avg + ( time - avg ) / ( double ) ( ++ count ) ) ) ; total += time ; } | Whenever this query was executed add execution time with this method . This class will then recalculate all statistics . |
29,257 | public final void flush ( CacheEvent event , boolean propagate ) { doFlush ( event ) ; if ( propagate ) { propagate ( event ) ; } String message = "Cache purged: " + ( event . getType ( ) == CacheEvent . CacheEventType . ALL ? "all caches" : "table: " + event . getGroup ( ) ) ; LogFilter . log ( LOGGER , LogLevel . DEBUG , message ) ; } | Flashes cache . |
29,258 | public String getKey ( String tableName , String query , Object [ ] params ) { return tableName + query + ( params == null ? null : Arrays . asList ( params ) . toString ( ) ) ; } | Generates a cache key . Subclasses may override this implementation . |
29,259 | public static < T > Set < T > set ( T ... values ) { return new HashSet < T > ( Arrays . asList ( values ) ) ; } | Creates a set from values . |
29,260 | public static < K , V > Map < K , V > map ( Object ... keysAndValues ) { if ( keysAndValues . length % 2 != 0 ) { throw new IllegalArgumentException ( "number of arguments must be even" ) ; } Map < K , V > map = new HashMap < K , V > ( Math . max ( keysAndValues . length , 16 ) ) ; for ( int i = 0 ; i < keysAndValues . length ; ) { map . put ( ( K ) keysAndValues [ i ++ ] , ( V ) keysAndValues [ i ++ ] ) ; } return map ; } | Create a map from keys and values . |
29,261 | public static < T > List < T > list ( T ... values ) { return new ArrayList < T > ( Arrays . asList ( values ) ) ; } | Create a list from values . |
29,262 | public Multipart field ( String name , String value ) { formFields . add ( new FormField ( name , value ) ) ; return this ; } | Convenience method to add a form field to the request . |
29,263 | public Multipart file ( String fieldName , String filePath ) { formFields . add ( new FileField ( fieldName , new File ( filePath ) ) ) ; return this ; } | Convenience method to add a file fields to the request . |
29,264 | public T header ( String name , String value ) { connection . setRequestProperty ( name , value ) ; return ( T ) this ; } | Sets an HTTP header - call before making a request . |
29,265 | public InputStream getInputStream ( ) { try { return connection . getInputStream ( ) ; } catch ( SocketTimeoutException e ) { throw new HttpException ( "Failed URL: " + url + ", waited for: " + connection . getConnectTimeout ( ) + " milliseconds" , e ) ; } catch ( Exception e ) { throw new HttpException ( "Failed URL: " + url , e ) ; } } | Returns input stream to read server response from . |
29,266 | public String responseMessage ( ) { try { connect ( ) ; return connection . getResponseMessage ( ) ; } catch ( Exception e ) { throw new HttpException ( "Failed URL: " + url , e ) ; } } | Returns response message from server such as OK or Created etc . |
29,267 | public byte [ ] bytes ( ) { connect ( ) ; ByteArrayOutputStream bout = new ByteArrayOutputStream ( ) ; byte [ ] bytes = new byte [ 1024 ] ; int count ; try { InputStream in = connection . getInputStream ( ) ; while ( ( count = in . read ( bytes ) ) != - 1 ) { bout . write ( bytes , 0 , count ) ; } } catch ( Exception e ) { throw new HttpException ( "Failed URL: " + url , e ) ; } finally { dispose ( ) ; } return bout . toByteArray ( ) ; } | Fetches response content from server as bytes . |
29,268 | public String text ( ) { try { connect ( ) ; return responseCode ( ) >= 400 ? read ( connection . getErrorStream ( ) ) : read ( connection . getInputStream ( ) ) ; } catch ( IOException e ) { throw new HttpException ( "Failed URL: " + url , e ) ; } finally { dispose ( ) ; } } | Fetches response content from server as String . |
29,269 | public T basic ( String user , String password ) { connection . setRequestProperty ( "Authorization" , "Basic " + toBase64 ( ( user + ":" + password ) . getBytes ( ) ) ) ; return ( T ) this ; } | Sets a user and password for basic authentication . |
29,270 | public Set < String > getAttributeNamesSkipId ( ) { if ( attributeNamesNoId == null ) { Set < String > attributesNames = new CaseInsensitiveSet ( getAttributeNames ( ) ) ; attributesNames . remove ( getIdName ( ) ) ; attributeNamesNoId = attributesNames ; } return attributeNamesNoId ; } | Finds all attribute names except for id . |
29,271 | public Set < String > getAttributeNamesSkip ( String ... names ) { Set < String > attributes = new CaseInsensitiveSet ( getAttributeNames ( ) ) ; for ( String name : names ) { attributes . remove ( name ) ; } return attributes ; } | Finds all attribute names except those provided as arguments . |
29,272 | protected Set < String > getAttributeNames ( ) { if ( columnMetadata == null || columnMetadata . isEmpty ( ) ) throw new InitException ( "Failed to find table: " + getTableName ( ) ) ; return Collections . unmodifiableSet ( columnMetadata . keySet ( ) ) ; } | Retrieves all attribute names . |
29,273 | boolean hasAttribute ( String attribute ) { if ( columnMetadata != null ) { if ( columnMetadata . containsKey ( attribute ) ) { return true ; } else if ( attribute . startsWith ( "\"" ) && attribute . endsWith ( "\"" ) ) { return columnMetadata . containsKey ( attribute . substring ( 1 , attribute . length ( ) - 1 ) ) ; } } return false ; } | returns true if this attribute is present in this meta model . This method i case insensitive . |
29,274 | protected void checkAttribute ( String attribute ) { if ( ! hasAttribute ( attribute ) ) { String sb = "Attribute: '" + attribute + "' is not defined in model: '" + getModelClass ( ) + ". " + "Available attributes: " + getAttributeNames ( ) ; throw new IllegalArgumentException ( sb ) ; } } | Checks if this model has a named attribute that has the same name as argument . |
29,275 | public Map < String , ColumnMetadata > getColumnMetadata ( ) { if ( columnMetadata == null || columnMetadata . isEmpty ( ) ) throw new InitException ( "Failed to find table: " + getTableName ( ) ) ; return Collections . unmodifiableMap ( columnMetadata ) ; } | Provides column metadata map keyed by attribute names . Table columns correspond to ActiveJDBC model attributes . |
29,276 | public boolean isAssociatedTo ( Class < ? extends Model > targetModelClass ) { if ( targetModelClass == null ) { throw new NullPointerException ( ) ; } for ( Association association : associations ) { if ( association . getTargetClass ( ) . getName ( ) . equals ( targetModelClass . getName ( ) ) ) { return true ; } } return false ; } | Checks if there is association to the target model class . |
29,277 | public static Response execute ( int maxBuffer , String ... command ) { if ( command . length == 0 ) { throw new IllegalArgumentException ( "Command must be provided." ) ; } String [ ] commandAndArgs = command . length == 1 && command [ 0 ] . contains ( " " ) ? Util . split ( command [ 0 ] , " " ) : command ; try { Process process = Runtime . getRuntime ( ) . exec ( commandAndArgs ) ; OutputReader stdOutReader = new OutputReader ( process . getInputStream ( ) , maxBuffer ) ; OutputReader stdErrReader = new OutputReader ( process . getErrorStream ( ) , maxBuffer ) ; Thread t1 = new Thread ( stdOutReader ) ; t1 . start ( ) ; Thread t2 = new Thread ( stdErrReader ) ; t2 . start ( ) ; int code = process . waitFor ( ) ; t1 . join ( ) ; t2 . join ( ) ; String out = stdOutReader . getOutput ( ) ; String err = stdErrReader . getOutput ( ) ; return new Response ( out , err , code ) ; } catch ( InterruptedException ie ) { Thread . currentThread ( ) . interrupt ( ) ; throw new RuntimeException ( "Interrupted" ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } | Executes an external command and provides results of execution . Will accumulate limited output from the external process . |
29,278 | public List < Map < String , Object > > toMaps ( ) { hydrate ( ) ; List < Map < String , Object > > maps = new ArrayList < > ( delegate . size ( ) ) ; for ( T t : delegate ) { maps . add ( t . toMap ( ) ) ; } return maps ; } | Converts the resultset to list of maps where each map represents a row in the resultset keyed off column names . |
29,279 | public String toJson ( boolean pretty , String ... attrs ) { hydrate ( ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( '[' ) ; if ( pretty ) sb . append ( '\n' ) ; for ( int i = 0 ; i < delegate . size ( ) ; i ++ ) { if ( i > 0 ) { sb . append ( ',' ) ; if ( pretty ) { sb . append ( '\n' ) ; } } delegate . get ( i ) . toJsonP ( sb , pretty , ( pretty ? " " : "" ) , attrs ) ; } if ( pretty ) { sb . append ( '\n' ) ; } sb . append ( ']' ) ; return sb . toString ( ) ; } | Generates JSON from content of this list |
29,280 | public String toSql ( boolean showParameters ) { String sql ; if ( forPaginator ) { sql = metaModel . getDialect ( ) . formSelect ( null , null , fullQuery , orderBys , limit , offset ) ; } else { sql = fullQuery != null ? fullQuery : metaModel . getDialect ( ) . formSelect ( metaModel . getTableName ( ) , null , subQuery , orderBys , limit , offset ) ; } if ( showParameters ) { StringBuilder sb = new StringBuilder ( sql ) . append ( ", with parameters: " ) ; join ( sb , params , ", " ) ; sql = sb . toString ( ) ; } return sql ; } | Use to see what SQL will be sent to the database . |
29,281 | public void dump ( OutputStream out ) { hydrate ( ) ; PrintWriter p = new PrintWriter ( out ) ; for ( Model m : delegate ) { p . write ( m . toString ( ) ) ; p . write ( '\n' ) ; } p . flush ( ) ; } | Dumps content of list to a stream . Use for debugging . |
29,282 | public String formatMessage ( Locale locale , Object ... params ) { return Messages . message ( message , locale , params ) ; } | Provides default implementation will look for a property in resource bundle using set message as key . If property in resource bundle not found treats message verbatim . |
29,283 | static void attach ( String dbName , Connection connection , String extraInfo ) { if ( ConnectionsAccess . getConnectionMap ( ) . get ( dbName ) != null ) { throw new InternalException ( "You are opening a connection " + dbName + " without closing a previous one. Check your logic. Connection still remains on thread: " + ConnectionsAccess . getConnectionMap ( ) . get ( dbName ) ) ; } ConnectionsAccess . getConnectionMap ( ) . put ( dbName , connection ) ; LogFilter . log ( LOGGER , LogLevel . DEBUG , "Attached connection named: {}: to current thread: {}. Extra info: {}" , dbName , connection , extraInfo ) ; } | Attaches a connection to a ThreadLocal and binds it to a name . |
29,284 | public static String mergeFromPath ( String templatePath , Map < String , ? > values ) { return mergeFromTemplate ( readResource ( templatePath ) , values ) ; } | This method is used in one - off operations where it is OK to load a template every time . |
29,285 | public static String mergeFromTemplate ( String template , Map < String , ? > values ) { for ( String param : values . keySet ( ) ) { template = template . replace ( "{{" + param + "}}" , values . get ( param ) == null ? "" : values . get ( param ) . toString ( ) ) ; } return template . replaceAll ( "\n|\r| " , "" ) ; } | Merges from string as template . |
29,286 | public static List < ConnectionSpecWrapper > getConnectionSpecWrappers ( String env ) { return connectionWrappers . get ( env ) == null ? new ArrayList < > ( ) : connectionWrappers . get ( env ) ; } | Provides a list of all connection wrappers corresponding to a given environment . |
29,287 | public static void addScope ( String className , String scope , String criteria ) { if ( ! scopes . containsKey ( className ) ) { scopes . put ( className , new HashMap < > ( ) ) ; } scopes . get ( className ) . put ( scope , criteria ) ; } | has to be public because it is called from models . |
29,288 | public static Get get ( String url , int connectTimeout , int readTimeout ) { try { return new Get ( url , connectTimeout , readTimeout ) ; } catch ( Exception e ) { throw new HttpException ( "Failed URL: " + url , e ) ; } } | Executes a GET request |
29,289 | public static Multipart multipart ( String url , int connectTimeout , int readTimeout ) { return new Multipart ( url , connectTimeout , connectTimeout ) ; } | Create multipart request |
29,290 | public static Delete delete ( String url , int connectTimeout , int readTimeout ) { try { return new Delete ( url , connectTimeout , readTimeout ) ; } catch ( Exception e ) { throw new HttpException ( "Failed URL: " + url , e ) ; } } | Executes a DELETE request . |
29,291 | public static DB open ( String driver , String url , String user , String password ) { return new DB ( DB . DEFAULT_NAME ) . open ( driver , url , user , password ) ; } | Opens a new connection based on JDBC properties and attaches it to a current thread . |
29,292 | public static DB open ( String driver , String url , Properties props ) { return new DB ( DB . DEFAULT_NAME ) . open ( driver , url , props ) ; } | Opens a new connection in case additional driver - specific parameters need to be passed in . |
29,293 | public static Long count ( String table , String query , Object ... params ) { return new DB ( DB . DEFAULT_NAME ) . count ( table , query , params ) ; } | Runs a count query returns a number of matching records . |
29,294 | public static List < Map > findAll ( String query ) { return new DB ( DB . DEFAULT_NAME ) . findAll ( query ) ; } | This method returns entire resultset as one list . Do not use it for large result sets . |
29,295 | public static int exec ( String query , Object ... params ) { return new DB ( DB . DEFAULT_NAME ) . exec ( query , params ) ; } | Executes parametrized DML - will contain question marks as placeholders . |
29,296 | static Object execInsert ( String query , String autoIncrementColumnName , Object ... params ) { return new DB ( DB . DEFAULT_NAME ) . execInsert ( query , autoIncrementColumnName , params ) ; } | This method is specific for inserts . |
29,297 | private void processFilePath ( File file ) { try { if ( file . getCanonicalPath ( ) . toLowerCase ( ) . endsWith ( ".jar" ) || file . getCanonicalPath ( ) . toLowerCase ( ) . endsWith ( ".zip" ) ) { ZipFile zip = new ZipFile ( file ) ; Enumeration < ? extends ZipEntry > entries = zip . entries ( ) ; while ( entries . hasMoreElements ( ) ) { ZipEntry entry = entries . nextElement ( ) ; if ( entry . getName ( ) . endsWith ( "class" ) ) { InputStream zin = zip . getInputStream ( entry ) ; tryClass ( entry . getName ( ) . replace ( File . separatorChar , '.' ) . substring ( 0 , entry . getName ( ) . length ( ) - 6 ) ) ; zin . close ( ) ; } } } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } | Finds and processes property files inside zip or jar files . |
29,298 | private void processDirectory ( File directory ) throws IOException , ClassNotFoundException { findFiles ( directory ) ; File [ ] files = directory . listFiles ( ) ; if ( files != null ) { for ( File file : files ) { if ( file . isDirectory ( ) ) { processDirectory ( file ) ; } } } } | Recursively processes this directory . |
29,299 | private void findFiles ( File directory ) throws IOException , ClassNotFoundException { File [ ] files = directory . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . endsWith ( ".class" ) ; } } ) ; if ( files != null ) { for ( File file : files ) { int current = currentDirectoryPath . length ( ) ; String fileName = file . getCanonicalPath ( ) . substring ( ++ current ) ; String className = fileName . replace ( File . separatorChar , '.' ) . substring ( 0 , fileName . length ( ) - 6 ) ; tryClass ( className ) ; } } } | This will scan directory for class files non - recursive . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.