idx
int64 0
41.2k
| question
stringlengths 73
5.81k
| target
stringlengths 5
918
|
|---|---|---|
39,400
|
public static < N > HCounterColumn < N > createCounterColumn ( N name , long value , Serializer < N > nameSerializer ) { return new HCounterColumnImpl < N > ( name , value , nameSerializer ) ; }
|
Create a counter column with a name and long value
|
39,401
|
public static HCounterColumn < String > createCounterColumn ( String name , long value ) { StringSerializer se = StringSerializer . get ( ) ; return createCounterColumn ( name , value , se ) ; }
|
Convenient method for creating a counter column with a String name and long value
|
39,402
|
< N > ColumnPath createColumnPath ( String columnFamilyName , N columnName , Serializer < N > nameSerializer ) { return createColumnPath ( columnFamilyName , nameSerializer . toByteBuffer ( columnName ) ) ; }
|
probably should be typed for thrift vs . avro
|
39,403
|
public < T > T find ( Class < T > clazz , Object id ) { if ( null == clazz ) { throw new IllegalArgumentException ( "clazz cannot be null" ) ; } if ( null == id ) { throw new IllegalArgumentException ( "id cannot be null" ) ; } CFMappingDef < T > cfMapDef = cacheMgr . getCfMapDef ( clazz , false ) ; if ( null == cfMapDef ) { throw new HectorObjectMapperException ( "No class annotated with @" + Entity . class . getSimpleName ( ) + " for type, " + clazz . getName ( ) ) ; } return objMapper . getObject ( keyspace , cfMapDef . getEffectiveColFamName ( ) , id ) ; }
|
Load an entity instance . If the ID does not map to a persisted entity then null is returned .
|
39,404
|
public < T > T find ( Class < T > clazz , Object id , ColumnSlice < String , byte [ ] > colSlice ) { if ( null == clazz ) { throw new IllegalArgumentException ( "clazz cannot be null" ) ; } if ( null == id ) { throw new IllegalArgumentException ( "id cannot be null" ) ; } CFMappingDef < T > cfMapDef = cacheMgr . getCfMapDef ( clazz , false ) ; if ( null == cfMapDef ) { throw new HectorObjectMapperException ( "No class annotated with @" + Entity . class . getSimpleName ( ) + " for type, " + clazz . getName ( ) ) ; } T obj = objMapper . createObject ( cfMapDef , id , colSlice ) ; return obj ; }
|
Load an entity instance given the raw column slice . This is a stop gap solution for instanting objects using entity manager while iterating over rows .
|
39,405
|
public void persist ( Object obj ) { if ( null == obj ) { throw new IllegalArgumentException ( "object to save cannot be null" ) ; } objMapper . saveObj ( keyspace , obj ) ; }
|
Save the entity instance .
|
39,406
|
public boolean addCassandraHost ( CassandraHost cassandraHost ) { if ( ! getHosts ( ) . contains ( cassandraHost ) ) { HClientPool pool = null ; try { cassandraHostConfigurator . applyConfig ( cassandraHost ) ; pool = cassandraHostConfigurator . getLoadBalancingPolicy ( ) . createConnection ( clientFactory , cassandraHost , monitor ) ; hostPools . putIfAbsent ( cassandraHost , pool ) ; log . info ( "Added host {} to pool" , cassandraHost . getName ( ) ) ; listenerHandler . fireOnAddHost ( cassandraHost , true , null , null ) ; return true ; } catch ( HectorTransportException hte ) { String errorMessage = "Transport exception host to HConnectionManager: " + cassandraHost ; log . error ( errorMessage , hte ) ; listenerHandler . fireOnAddHost ( cassandraHost , false , errorMessage , hte ) ; } catch ( Exception ex ) { String errorMessage = "General exception host to HConnectionManager: " + cassandraHost ; log . error ( errorMessage , ex ) ; listenerHandler . fireOnAddHost ( cassandraHost , false , errorMessage , ex ) ; } } else { String message = "Host already existed for pool " + cassandraHost . getName ( ) ; log . info ( message ) ; listenerHandler . fireOnAddHost ( cassandraHost , false , message , null ) ; } return false ; }
|
Returns true if the host was successfully added . In any sort of failure exceptions are caught and logged returning false .
|
39,407
|
public boolean unsuspendCassandraHost ( CassandraHost cassandraHost ) { HClientPool pool = suspendedHostPools . remove ( cassandraHost ) ; boolean readded = pool != null ; if ( readded ) { boolean alreadyThere = hostPools . putIfAbsent ( cassandraHost , pool ) != null ; if ( alreadyThere ) { log . error ( "Unsuspend called on a pool that was already active for CassandraHost {}" , cassandraHost ) ; pool . shutdown ( ) ; } } listenerHandler . fireOnUnSuspendHost ( cassandraHost , readded ) ; log . info ( "UN-Suspend operation status was {} for CassandraHost {}" , readded , cassandraHost ) ; return readded ; }
|
The opposite of suspendCassandraHost places the pool back into selection
|
39,408
|
private void doTimeoutCheck ( CassandraHost cassandraHost ) { if ( hostTimeoutTracker != null && hostPools . size ( ) > 1 ) { if ( hostTimeoutTracker . checkTimeout ( cassandraHost ) ) { suspendCassandraHost ( cassandraHost ) ; } } }
|
Use the HostTimeoutCheck and initiate a suspend if and only if we are configured for such AND there is more than one operating host pool
|
39,409
|
void updateScores ( ) { for ( LatencyAwareHClientPool pool : allPools ) { scores . put ( pool , pool . score ( ) ) ; pool . resetIntervel ( ) ; } }
|
This will be a expensive call .
|
39,410
|
public void insertMulti ( String columnName , Map < String , String > keyValues ) { Mutator < String > m = createMutator ( keyspace , serializer ) ; for ( Map . Entry < String , String > keyValue : keyValues . entrySet ( ) ) { m . addInsertion ( keyValue . getKey ( ) , columnFamilyName , createColumn ( columnName , keyValue . getValue ( ) , keyspace . createClock ( ) , serializer , serializer ) ) ; } m . execute ( ) ; }
|
Insert multiple values for a given columnName
|
39,411
|
private String getContextPath ( ) { ClassLoader loader = getClass ( ) . getClassLoader ( ) ; if ( loader == null ) return null ; URL url = loader . getResource ( "/" ) ; if ( url != null ) { String [ ] elements = url . toString ( ) . split ( "/" ) ; for ( int i = elements . length - 1 ; i > 0 ; -- i ) { if ( "WEB-INF" . equals ( elements [ i ] ) ) { return elements [ i - 1 ] ; } } } return null ; }
|
Tries to guess a context path for the running application . If this is a web application running under a tomcat server this will work . If unsuccessful returns null .
|
39,412
|
public int countColumns ( K key , N start , N end , int max ) { CountQuery < K , N > query = HFactory . createCountQuery ( keyspace , keySerializer , topSerializer ) ; query . setKey ( key ) ; query . setColumnFamily ( columnFamily ) ; query . setRange ( start , end , max ) ; return query . execute ( ) . get ( ) ; }
|
Counts columns in the specified range of a standard column family
|
39,413
|
public < T > T queryColumns ( K key , HSlicePredicate < N > predicate , ColumnFamilyRowMapper < K , N , T > mapper ) { return doExecuteSlice ( key , predicate , mapper ) ; }
|
Queries a range of columns at the given key and maps them to an object of type OBJ using the given mapping object
|
39,414
|
public < T > T queryColumns ( K key , List < N > columns , ColumnFamilyRowMapper < K , N , T > mapper ) { HSlicePredicate < N > predicate = new HSlicePredicate < N > ( topSerializer ) ; predicate . setColumnNames ( columns ) ; return doExecuteSlice ( key , predicate , mapper ) ; }
|
Queries all columns at a given key and maps them to an object of type OBJ using the given mapping object
|
39,415
|
public void doAddNodes ( ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Node discovery running..." ) ; } Set < CassandraHost > foundHosts = discoverNodes ( ) ; if ( foundHosts != null && foundHosts . size ( ) > 0 ) { log . info ( "Found {} new host(s) in Ring" , foundHosts . size ( ) ) ; for ( CassandraHost cassandraHost : foundHosts ) { log . info ( "Addding found host {} to pool" , cassandraHost ) ; cassandraHostConfigurator . applyConfig ( cassandraHost ) ; connectionManager . addCassandraHost ( cassandraHost ) ; } } if ( log . isDebugEnabled ( ) ) { log . debug ( "Node discovery run complete." ) ; } }
|
Find any nodes that are not already in the connection manager but are in the cassandra ring and add them
|
39,416
|
public Set < CassandraHost > discoverNodes ( ) { Cluster cluster = HFactory . getCluster ( connectionManager . getClusterName ( ) ) ; if ( cluster == null ) { return null ; } Set < CassandraHost > existingHosts = connectionManager . getHosts ( ) ; Set < CassandraHost > foundHosts = new HashSet < CassandraHost > ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "using existing hosts {}" , existingHosts ) ; } try { for ( KeyspaceDefinition keyspaceDefinition : cluster . describeKeyspaces ( ) ) { if ( ! keyspaceDefinition . getName ( ) . equals ( Keyspace . KEYSPACE_SYSTEM ) ) { List < TokenRange > tokenRanges = cluster . describeRing ( keyspaceDefinition . getName ( ) ) ; for ( TokenRange tokenRange : tokenRanges ) { for ( EndpointDetails endPointDetail : tokenRange . getEndpoint_details ( ) ) { if ( dataCenterValidator == null || dataCenterValidator . validate ( endPointDetail . getDatacenter ( ) ) ) { CassandraHost foundHost = new CassandraHost ( endPointDetail . getHost ( ) , cassandraHostConfigurator . getPort ( ) ) ; if ( ! existingHosts . contains ( foundHost ) ) { log . info ( "Found a node we don't know about {} for TokenRange {}" , foundHost , tokenRange ) ; foundHosts . add ( foundHost ) ; } } } } break ; } } } catch ( Exception e ) { log . error ( "Discovery Service failed attempt to connect CassandraHost" , e ) ; } return foundHosts ; }
|
Find any unknown nodes in the cassandra ring
|
39,417
|
public AbstractColumnFamilyTemplate < K , N > addColumn ( N columnName , Serializer < ? > valueSerializer ) { columnValueSerializers . put ( columnName , valueSerializer ) ; activeSlicePredicate . addColumnName ( columnName ) ; return this ; }
|
Add a column to the static set of columns which will be used in constructing the single - argument form of slicing operations
|
39,418
|
public void deleteRow ( K key ) { createMutator ( ) . addDeletion ( key , columnFamily , null , topSerializer ) . execute ( ) ; }
|
Immediately delete this row in a single mutation operation
|
39,419
|
public void deleteColumn ( K key , N columnName ) { createMutator ( ) . addDeletion ( key , columnFamily , columnName , topSerializer ) . execute ( ) ; }
|
Immediately delete this column as a single mutation operation
|
39,420
|
public Object getObjectInstance ( Object object , Name jndiName , Context context , Hashtable < ? , ? > environment ) throws Exception { Reference resourceRef = null ; if ( object instanceof Reference ) { resourceRef = ( Reference ) object ; } else { throw new Exception ( "Object provided is not a javax.naming.Reference type" ) ; } if ( cluster == null ) { configure ( resourceRef ) ; } return keyspace ; }
|
Creates an object using the location or reference information specified .
|
39,421
|
public void copy ( ) throws HectorException { if ( this . cf == null ) { throw new HectorException ( "Unable to clone row with null column family" ) ; } if ( this . rowKey == null ) { throw new HectorException ( "Unable to clone row with null row key" ) ; } if ( this . destinationKey == null ) { throw new HectorException ( "Unable to clone row with null clone key" ) ; } ColumnFamilyTemplate < K , ByteBuffer > template = new ThriftColumnFamilyTemplate < K , ByteBuffer > ( this . keyspace , this . cf , this . keySerializer , this . bs ) ; Mutator < K > mutator = HFactory . createMutator ( this . keyspace , this . keySerializer , new BatchSizeHint ( 1 , this . mutateInterval ) ) ; ColumnFamilyUpdater < K , ByteBuffer > updater = template . createUpdater ( this . destinationKey , mutator ) ; SliceQuery < K , ByteBuffer , ByteBuffer > query = HFactory . createSliceQuery ( this . keyspace , this . keySerializer , this . bs , this . bs ) . setColumnFamily ( this . cf ) . setKey ( this . rowKey ) ; ColumnSliceIterator < K , ByteBuffer , ByteBuffer > iterator = new ColumnSliceIterator < K , ByteBuffer , ByteBuffer > ( query , this . bs . fromBytes ( new byte [ 0 ] ) , this . bs . fromBytes ( new byte [ 0 ] ) , false ) ; while ( iterator . hasNext ( ) ) { HColumn < ByteBuffer , ByteBuffer > column = iterator . next ( ) ; updater . setValue ( column . getName ( ) , column . getValue ( ) , this . bs ) ; } template . update ( updater ) ; }
|
Copy the source row to the destination row .
|
39,422
|
@ SuppressWarnings ( "unchecked" ) public void setDefaults ( Class < T > realClass ) { this . realClass = realClass ; this . keyDef = new KeyDefinition ( ) ; effectiveClass = realClass ; boolean entityFound ; while ( ! ( entityFound = ( null != effectiveClass . getAnnotation ( Entity . class ) ) ) ) { if ( ! effectiveClass . isAnonymousClass ( ) ) { break ; } else { effectiveClass = ( Class < T > ) effectiveClass . getSuperclass ( ) ; } } if ( ! entityFound ) { throw new HomMissingEntityAnnotationException ( "class, " + realClass . getName ( ) + ", not annotated with @" + Entity . class . getSimpleName ( ) ) ; } }
|
Setup mapping with defaults for the given class . Does not parse all annotations .
|
39,423
|
public boolean isPerformNameResolution ( ) { String sysprop = System . getProperty ( SystemProperties . HECTOR_PERFORM_NAME_RESOLUTION . toString ( ) ) ; return sysprop != null && Boolean . parseBoolean ( sysprop ) ; }
|
Checks whether name resolution should occur .
|
39,424
|
public void setAutoDiscoveryDataCenter ( String dataCenter ) { if ( StringUtils . isNotBlank ( dataCenter ) ) { this . autoDiscoveryDataCenters = Arrays . asList ( dataCenter ) ; } }
|
Sets the local datacenter for the DiscoveryService . Nodes out of this datacenter will be discarded . For configuration simplicity you can provide an empty or null string with the effect being the same as if you had not set this property .
|
39,425
|
public HSlicePredicate < N > setColumnNames ( Collection < N > columnNames ) { this . columnNames = columnNames ; predicateType = PredicateType . ColumnNames ; return this ; }
|
Same as varargs signature except we take a collection
|
39,426
|
public SlicePredicate toThrift ( ) { SlicePredicate pred = new SlicePredicate ( ) ; switch ( predicateType ) { case ColumnNames : if ( columnNames == null ) { return null ; } pred . setColumn_names ( toThriftColumnNames ( columnNames ) ) ; break ; case Range : Assert . isTrue ( countSet , "Count was not set, neither were column-names set, can't execute" ) ; SliceRange range = new SliceRange ( findBytes ( start ) , findBytes ( finish ) , reversed , count ) ; pred . setSlice_range ( range ) ; break ; case Unknown : default : throw new HectorException ( "Neither column names nor range were set, this is an invalid slice predicate" ) ; } return pred ; }
|
Will throw a runtime exception if neither columnsNames nor count were set .
|
39,427
|
public static byte [ ] bytes ( String s ) { try { return s . getBytes ( ENCODING ) ; } catch ( UnsupportedEncodingException e ) { log . error ( "UnsupportedEncodingException " , e ) ; throw new RuntimeException ( e ) ; } }
|
Gets UTF - 8 bytes from the string .
|
39,428
|
public static String string ( byte [ ] bytes ) { if ( bytes == null ) { return null ; } try { return new String ( bytes , ENCODING ) ; } catch ( UnsupportedEncodingException e ) { log . error ( "UnsupportedEncodingException " , e ) ; throw new RuntimeException ( e ) ; } }
|
Utility for converting bytes to strings . UTF - 8 is assumed .
|
39,429
|
public < K > void insertMulti ( Map < K , String > keyValues , Serializer < K > keySerializer ) { Mutator < K > m = createMutator ( keyspace , keySerializer ) ; for ( Map . Entry < K , String > keyValue : keyValues . entrySet ( ) ) { m . addInsertion ( keyValue . getKey ( ) , CF_NAME , createColumn ( COLUMN_NAME , keyValue . getValue ( ) , keyspace . createClock ( ) , serializer , serializer ) ) ; } m . execute ( ) ; }
|
Insert multiple values
|
39,430
|
private boolean fetchChunk ( ) throws IOException { try { ColumnQuery < T , Long , byte [ ] > query = HFactory . createColumnQuery ( keyspace , rowKeySerializer , LongSerializer . get ( ) , BytesArraySerializer . get ( ) ) ; QueryResult < HColumn < Long , byte [ ] > > result = query . setColumnFamily ( cf ) . setKey ( key ) . setName ( chunkPos ) . execute ( ) ; HColumn < Long , byte [ ] > column = result . get ( ) ; if ( column != null ) { chunk = column . getValue ( ) ; chunkPos ++ ; pos = 0 ; return true ; } else { return false ; } } catch ( HectorException e ) { throw new IOException ( "Unable to read data" , e ) ; } }
|
Fetch the next chunk .
|
39,431
|
public static List < Column > getColumnList ( List < ColumnOrSuperColumn > columns ) { ArrayList < Column > list = new ArrayList < Column > ( columns . size ( ) ) ; for ( ColumnOrSuperColumn col : columns ) { list . add ( col . getColumn ( ) ) ; } return list ; }
|
Converts a list of ColumnOrSuperColumn to Column
|
39,432
|
public < V > V getValue ( N name , Serializer < V > valueSerializer ) { return extractColumnValue ( name , valueSerializer ) ; }
|
Extract a value for the specified name and serializer
|
39,433
|
private void setAcquired ( HLock lock , Map < String , String > canBeEarlier ) { Future < Void > heartbeat = scheduler . schedule ( new Heartbeat ( lock ) , lockTtl / 2 , TimeUnit . MILLISECONDS ) ; ( ( HLockImpl ) lock ) . setHeartbeat ( heartbeat ) ; ( ( HLockImpl ) lock ) . setAcquired ( true ) ; if ( logger . isDebugEnabled ( ) ) { logLock ( lock , canBeEarlier . keySet ( ) ) ; } }
|
Start the heartbeat thread before we return
|
39,434
|
public QueryResult < CqlRows < K , N , V > > execute ( ) { return new QueryResultImpl < CqlRows < K , N , V > > ( keyspace . doExecuteOperation ( new Operation < CqlRows < K , N , V > > ( OperationType . READ ) { public CqlRows < K , N , V > execute ( Client cassandra ) throws HectorException { CqlRows < K , N , V > rows = null ; try { if ( cqlVersion != null ) { cassandra . set_cql_version ( cqlVersion ) ; } CqlResult result = null ; if ( cql3 ) { result = cassandra . execute_cql3_query ( query , useCompression ? Compression . GZIP : Compression . NONE , ThriftConverter . consistencyLevel ( getConsistency ( ) ) ) ; } else { result = cassandra . execute_cql_query ( query , useCompression ? Compression . GZIP : Compression . NONE ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "Found CqlResult: {}" , result ) ; } switch ( result . getType ( ) ) { case VOID : rows = new CqlRows < K , N , V > ( ) ; break ; default : if ( result . getRowsSize ( ) > 0 ) { LinkedHashMap < ByteBuffer , List < Column > > ret = new LinkedHashMap < ByteBuffer , List < Column > > ( result . getRowsSize ( ) ) ; int keyColumnIndex = - 1 ; for ( Iterator < CqlRow > rowsIter = result . getRowsIterator ( ) ; rowsIter . hasNext ( ) ; ) { CqlRow row = rowsIter . next ( ) ; ByteBuffer kbb = ByteBuffer . wrap ( row . getKey ( ) ) ; if ( cql3 ) { List < Column > rowcolumns = row . getColumns ( ) ; if ( keyColumnIndex == - 1 ) { for ( Column c : rowcolumns ) { keyColumnIndex ++ ; String name = StringSerializer . get ( ) . fromBytes ( c . getName ( ) ) ; if ( name . toUpperCase ( ) . equals ( "KEY" ) ) { kbb = ByteBuffer . wrap ( c . getValue ( ) ) ; break ; } } } else { kbb = ByteBuffer . wrap ( row . getColumns ( ) . get ( keyColumnIndex ) . getValue ( ) ) ; } } ret . put ( kbb , filterKeyColumn ( row ) ) ; } Map < K , List < Column > > thriftRet = keySerializer . fromBytesMap ( ret ) ; rows = new CqlRows < K , N , V > ( ( LinkedHashMap < K , List < Column > > ) thriftRet , columnNameSerializer , valueSerializer ) ; } break ; } } catch ( Exception ex ) { throw keyspace . getExceptionsTranslator ( ) . translate ( ex ) ; } return rows ; } } ) , this ) ; }
|
For future releases we should consider refactoring how execute method converts the thrift CqlResult to Hector CqlRows . Starting with CQL3 the KEY is no longer returned by default and is no longer treated as a special thing . To get the KEY from the resultset we have to look at the columns . Using the KEY in CqlRows is nice and makes it easy to get results by the KEY . The downside is that users have to explicitly include the KEY in the statement . Changing how CqlRows work might break some existing use cases . For now the implementation finds the column and expects the statement to have the KEY .
|
39,435
|
private void writeData ( boolean close ) throws IOException { if ( pos != 0 && ( close || pos == chunk . length - 1 ) ) { byte [ ] data ; if ( pos != chunk . length - 1 ) { data = new byte [ ( int ) pos + 1 ] ; System . arraycopy ( chunk , 0 , data , 0 , data . length ) ; } else { data = chunk ; } try { mutator . insert ( key , cf , HFactory . createColumn ( chunkPos , data , LongSerializer . get ( ) , BytesArraySerializer . get ( ) ) ) ; } catch ( HectorException e ) { throw new IOException ( "Unable to write data" , e ) ; } chunkPos ++ ; pos = 0 ; } }
|
Write the data to column if the configured chunk size is reached or if the stream should be closed
|
39,436
|
public < N , V > MutationResult insert ( final K key , final String cf , final HColumn < N , V > c ) { addInsertion ( key , cf , c ) ; return execute ( ) ; }
|
Simple and immediate insertion of a column
|
39,437
|
public < SN , N , V > MutationResult insert ( final K key , final String cf , final HSuperColumn < SN , N , V > superColumn ) { addInsertion ( key , cf , superColumn ) ; return execute ( ) ; }
|
overloaded insert - super
|
39,438
|
public < SN , N > MutationResult subDelete ( final K key , final String cf , final SN supercolumnName , final N columnName , final Serializer < SN > sNameSerializer , final Serializer < N > nameSerializer ) { return new MutationResultImpl ( keyspace . doExecute ( new KeyspaceOperationCallback < Void > ( ) { public Void doInKeyspace ( KeyspaceService ks ) throws HectorException { ks . remove ( keySerializer . toByteBuffer ( key ) , ThriftFactory . createSuperColumnPath ( cf , supercolumnName , columnName , sNameSerializer , nameSerializer ) ) ; return null ; } } , consistency ) ) ; }
|
Deletes a subcolumn of a supercolumn
|
39,439
|
public < SN , N , V > Mutator < K > addSubDelete ( K key , String cf , HSuperColumn < SN , N , V > sc ) { return addSubDelete ( key , cf , sc , keyspace . createClock ( ) ) ; }
|
Deletes the columns defined in the HSuperColumn . If there are no HColumns attached we delete the whole thing .
|
39,440
|
public < N , V > Mutator < K > addInsertion ( K key , String cf , HColumn < N , V > c ) { getPendingMutations ( ) . addInsertion ( key , Arrays . asList ( cf ) , ( ( HColumnImpl < N , V > ) c ) . toThrift ( ) ) ; return this ; }
|
also should throw a typed StatementValidationException or similar perhaps?
|
39,441
|
public MutationResult execute ( ) { if ( pendingMutations == null || pendingMutations . isEmpty ( ) ) { return new MutationResultImpl ( true , 0 , null ) ; } final BatchMutation < K > mutations = pendingMutations . makeCopy ( ) ; pendingMutations = null ; return new MutationResultImpl ( keyspace . doExecuteOperation ( new Operation < Void > ( OperationType . WRITE ) { public Void execute ( Cassandra . Client cassandra ) throws Exception { cassandra . batch_mutate ( mutations . getMutationMap ( ) , ThriftConverter . consistencyLevel ( consistencyLevelPolicy . get ( operationType ) ) ) ; return null ; } } ) ) ; }
|
Batch executes all mutations scheduled to this Mutator instance by addInsertion addDeletion etc . May throw a HectorException which is a RuntimeException .
|
39,442
|
public < N > MutationResult insertCounter ( final K key , final String cf , final HCounterColumn < N > c ) { addCounter ( key , cf , c ) ; return execute ( ) ; }
|
Counters support .
|
39,443
|
private URL findToolsJar ( ) throws MojoExecutionException { final File javaHome = FileUtils . resolveFile ( new File ( File . pathSeparator ) , System . getProperty ( "java.home" ) ) ; final List < File > toolsPaths = new ArrayList < File > ( ) ; File file = null ; if ( SystemUtils . IS_OS_MAC_OSX ) { file = FileUtils . resolveFile ( javaHome , "../Classes/classes.jar" ) ; toolsPaths . add ( file ) ; } if ( file == null || ! file . exists ( ) ) { file = FileUtils . resolveFile ( javaHome , "../lib/tools.jar" ) ; toolsPaths . add ( file ) ; } if ( ! file . exists ( ) ) { throw new MojoExecutionException ( "Could not find tools.jar at " + toolsPaths + " under java.home: " + javaHome ) ; } getLog ( ) . debug ( "Using tools.jar: " + file ) ; final URI fileUri = file . toURI ( ) ; try { return fileUri . toURL ( ) ; } catch ( MalformedURLException e ) { throw new MojoExecutionException ( "Could not generate URL from URI: " + fileUri , e ) ; } }
|
Figure out where the tools . jar file lives .
|
39,444
|
public < T > Observable < T > getAndObserve ( String key , Class < T > classOfT , T defaultValue ) { return getAndObserve ( key , TypeToken . fromClass ( classOfT ) , defaultValue ) ; }
|
Gets value from SharedPreferences with a given key and type as a RxJava Observable which can be subscribed . If value is not found we can return defaultValue . Emit preference as first element of the stream even if preferences wasn t changed .
|
39,445
|
public < T > Observable < T > getAndObserve ( final String key , final TypeToken < T > typeTokenOfT , final T defaultValue ) { return observe ( key , typeTokenOfT , defaultValue ) . mergeWith ( Observable . defer ( new Callable < ObservableSource < ? extends T > > ( ) { public ObservableSource < ? extends T > call ( ) throws Exception { return Observable . just ( get ( key , typeTokenOfT , defaultValue ) ) ; } } ) ) ; }
|
Gets value from SharedPreferences with a given key and type token as a RxJava Observable which can be subscribed If value is not found we can return defaultValue . Emit preference as first element of the stream even if preferences wasn t changed .
|
39,446
|
public Observable < String > observePreferences ( ) { return Observable . create ( new ObservableOnSubscribe < String > ( ) { public void subscribe ( final ObservableEmitter < String > e ) { preferences . registerOnSharedPreferenceChangeListener ( new SharedPreferences . OnSharedPreferenceChangeListener ( ) { public void onSharedPreferenceChanged ( SharedPreferences sharedPrefs , String key ) { if ( ! e . isDisposed ( ) ) { e . onNext ( key ) ; } } } ) ; } } ) ; }
|
returns RxJava Observable from SharedPreferences used inside Prefser object . You can subscribe this Observable and every time when SharedPreferences will change subscriber will be notified about that and you will be able to read key of the value which has been changed .
|
39,447
|
public static boolean isNullOrEmptyOrQuestionMark ( final String string ) { if ( string == null || string . length ( ) == 0 || "?" . equals ( string ) ) { return true ; } return false ; }
|
Checks that the specified String is not null or empty or question mark ? .
|
39,448
|
public static void writeableDirectory ( final String path , String message ) throws IllegalArgumentException { notNullOrEmpty ( path , message ) ; File file = new File ( path ) ; if ( ! file . exists ( ) || ! file . isDirectory ( ) || ! file . canWrite ( ) || ! file . canExecute ( ) ) { throw new IllegalArgumentException ( message ) ; } }
|
FIXME me animal sniffer this is 1 . 6 API only
|
39,449
|
public static void notNullAndNoNullValues ( final Object [ ] objects , final String message ) { notNull ( objects , message ) ; for ( Object object : objects ) { notNull ( object , message ) ; } }
|
Checks that the specified array is not null or contain any null values .
|
39,450
|
public LocalRepositoryManager localRepositoryManager ( final RepositorySystemSession session , boolean legacyLocalRepository ) { Validate . notNull ( session , "session must be specified" ) ; String localRepositoryPath = settings . getLocalRepository ( ) ; Validate . notNullOrEmpty ( localRepositoryPath , "Path to a local repository must be defined" ) ; SWRLocalRepositoryManager factory = SWRLocalRepositoryManager . ENHANCED ; if ( useLegacyLocalRepository || legacyLocalRepository ) { factory = SWRLocalRepositoryManager . LEGACY ; } if ( settings . isOffline ( ) ) { factory = SWRLocalRepositoryManager . SIMPLE ; } LocalRepositoryManager manager = factory . localRepositoryManager ( system , session , new File ( localRepositoryPath ) ) ; return manager ; }
|
Gets manager for local repository
|
39,451
|
public MirrorSelector mirrorSelector ( ) { DefaultMirrorSelector dms = new DefaultMirrorSelector ( ) ; for ( Mirror mirror : settings . getMirrors ( ) ) { dms . add ( mirror . getId ( ) , mirror . getUrl ( ) , mirror . getLayout ( ) , false , mirror . getMirrorOf ( ) , mirror . getMirrorOfLayouts ( ) ) ; } return dms ; }
|
Gets mirror selector
|
39,452
|
public ProxySelector proxySelector ( ) { DefaultProxySelector dps = new DefaultProxySelector ( ) ; for ( Proxy proxy : settings . getProxies ( ) ) { dps . add ( MavenConverter . asProxy ( proxy ) , proxy . getNonProxyHosts ( ) ) ; } return dps ; }
|
Gets proxy selector
|
39,453
|
public ArtifactTypeRegistry artifactTypeRegistry ( ) { DefaultArtifactTypeRegistry stereotypes = new DefaultArtifactTypeRegistry ( ) ; stereotypes . add ( new DefaultArtifactType ( "pom" ) ) ; stereotypes . add ( new DefaultArtifactType ( "maven-plugin" , "jar" , "" , "java" ) ) ; stereotypes . add ( new DefaultArtifactType ( "jar" , "jar" , "" , "java" ) ) ; stereotypes . add ( new DefaultArtifactType ( "ejb" , "jar" , "" , "java" ) ) ; stereotypes . add ( new DefaultArtifactType ( "ejb-client" , "jar" , "client" , "java" ) ) ; stereotypes . add ( new DefaultArtifactType ( "test-jar" , "jar" , "tests" , "java" ) ) ; stereotypes . add ( new DefaultArtifactType ( "javadoc" , "jar" , "javadoc" , "java" ) ) ; stereotypes . add ( new DefaultArtifactType ( "java-source" , "jar" , "sources" , "java" , false , false ) ) ; stereotypes . add ( new DefaultArtifactType ( "war" , "war" , "" , "java" , false , true ) ) ; stereotypes . add ( new DefaultArtifactType ( "ear" , "ear" , "" , "java" , false , true ) ) ; stereotypes . add ( new DefaultArtifactType ( "rar" , "rar" , "" , "java" , false , true ) ) ; stereotypes . add ( new DefaultArtifactType ( "par" , "par" , "" , "java" , false , true ) ) ; return stereotypes ; }
|
Returns artifact type registry . Defines standard Maven stereotypes .
|
39,454
|
public DependencyGraphTransformer dependencyGraphTransformer ( ) { DependencyGraphTransformer transformer = new ConflictResolver ( new NearestVersionSelector ( ) , new JavaScopeSelector ( ) , new SimpleOptionalitySelector ( ) , new JavaScopeDeriver ( ) ) ; return new ChainedDependencyGraphTransformer ( transformer , new JavaDependencyContextRefiner ( ) ) ; }
|
Gets a dependency graph transformer . This one handles scope changes
|
39,455
|
private boolean areEquivalent ( final Artifact artifact , final Artifact foundArtifact ) { boolean areEquivalent = ( foundArtifact . getGroupId ( ) . equals ( artifact . getGroupId ( ) ) && foundArtifact . getArtifactId ( ) . equals ( artifact . getArtifactId ( ) ) && foundArtifact . getVersion ( ) . equals ( artifact . getVersion ( ) ) ) ; return areEquivalent ; }
|
Returns if two artifacts are equivalent that is have the same groupId artifactId and Version
|
39,456
|
static MavenArtifactInfo fromDependencyNode ( final DependencyNode dependencyNode ) { final Artifact artifact = dependencyNode . getDependency ( ) . getArtifact ( ) ; final List < DependencyNode > children = dependencyNode . getChildren ( ) ; ScopeType scopeType = ScopeType . RUNTIME ; try { scopeType = ScopeType . fromScopeType ( dependencyNode . getDependency ( ) . getScope ( ) ) ; } catch ( IllegalArgumentException e ) { log . log ( Level . WARNING , "Invalid scope {0} of retrieved dependency {1} will be replaced by <scope>runtime</scope>" , new Object [ ] { dependencyNode . getDependency ( ) . getScope ( ) , dependencyNode . getDependency ( ) . getArtifact ( ) } ) ; } final boolean optional = dependencyNode . getDependency ( ) . isOptional ( ) ; return new MavenArtifactInfoImpl ( artifact , scopeType , children , optional ) ; }
|
Creates MavenArtifactInfo based on DependencyNode .
|
39,457
|
protected MavenArtifactInfo [ ] parseDependencies ( final List < DependencyNode > children ) { final MavenArtifactInfo [ ] dependecies = new MavenArtifactInfo [ children . size ( ) ] ; int i = 0 ; for ( final DependencyNode child : children ) { dependecies [ i ++ ] = MavenArtifactInfoImpl . fromDependencyNode ( child ) ; } return dependecies ; }
|
Produces MavenArtifactInfo array from List of DependencyNode s .
|
39,458
|
public DefaultRepositorySystemSession getSession ( final Settings settings , boolean legacyLocalRepository ) { DefaultRepositorySystemSession session = new DefaultRepositorySystemSession ( ) ; MavenManagerBuilder builder = new MavenManagerBuilder ( system , settings ) ; session . setLocalRepositoryManager ( builder . localRepositoryManager ( session , legacyLocalRepository ) ) ; session . setWorkspaceReader ( builder . workspaceReader ( ) ) ; session . setTransferListener ( builder . transferListerer ( ) ) ; session . setRepositoryListener ( builder . repositoryListener ( ) ) ; session . setOffline ( settings . isOffline ( ) ) ; session . setMirrorSelector ( builder . mirrorSelector ( ) ) ; session . setProxySelector ( builder . proxySelector ( ) ) ; session . setDependencyManager ( builder . dependencyManager ( ) ) ; session . setArtifactDescriptorPolicy ( builder . artifactRepositoryPolicy ( ) ) ; session . setDependencyTraverser ( builder . dependencyTraverser ( ) ) ; session . setDependencyGraphTransformer ( builder . dependencyGraphTransformer ( ) ) ; session . setArtifactTypeRegistry ( builder . artifactTypeRegistry ( ) ) ; session . setSystemProperties ( SecurityActions . getProperties ( ) ) ; session . setConfigProperties ( SecurityActions . getProperties ( ) ) ; return session ; }
|
Spawns a working session from the repository system . This is used to as environment for execution of Maven commands
|
39,459
|
public Collection < ArtifactResult > resolveDependencies ( final RepositorySystemSession repoSession , final MavenWorkingSession swrSession , final CollectRequest request , final MavenResolutionFilter [ ] filters ) throws DependencyResolutionException { final DependencyRequest depRequest = new DependencyRequest ( request , new MavenResolutionFilterWrap ( filters , Collections . unmodifiableList ( new ArrayList < MavenDependency > ( swrSession . getDependenciesForResolution ( ) ) ) ) ) ; DependencyResult result = system . resolveDependencies ( repoSession , depRequest ) ; return result . getArtifactResults ( ) ; }
|
Resolves artifact dependencies .
|
39,460
|
public ArtifactResult resolveArtifact ( final RepositorySystemSession session , final ArtifactRequest request ) throws ArtifactResolutionException { return system . resolveArtifact ( session , request ) ; }
|
Resolves an artifact
|
39,461
|
public VersionRangeResult resolveVersionRange ( final RepositorySystemSession session , final VersionRangeRequest request ) throws VersionRangeResolutionException { return system . resolveVersionRange ( session , request ) ; }
|
Resolves versions range
|
39,462
|
static Class < ? > loadClass ( ClassLoader cl , String classTypeName ) throws InvocationException { try { return cl . loadClass ( classTypeName ) ; } catch ( ClassNotFoundException e ) { throw new InvocationException ( e , "Unable to load class {0} with class loader {1}" , classTypeName , cl ) ; } }
|
Loads a class from classloader
|
39,463
|
static Class < ? > reloadClass ( ClassLoader cl , Class < ? > classType ) throws InvocationException { try { return cl . loadClass ( classType . getName ( ) ) ; } catch ( ClassNotFoundException e ) { throw new InvocationException ( e , "Unable to reload class {0} with class loader {1}, previously loaded with {2}" , classType . getName ( ) , cl , classType . getClassLoader ( ) ) ; } }
|
Reloads a class from classloader using same fully qualified class name
|
39,464
|
public Settings buildSettings ( SettingsBuildingRequest request ) { SettingsBuildingResult result ; try { SettingsBuilder builder = new DefaultSettingsBuilderFactory ( ) . newInstance ( ) ; if ( request . getGlobalSettingsFile ( ) != null ) { log . log ( Level . FINE , "Using {0} to get global Maven settings.xml" , request . getGlobalSettingsFile ( ) . getAbsolutePath ( ) ) ; } final File userSettingsFile = request . getUserSettingsFile ( ) ; if ( userSettingsFile != null ) { log . log ( Level . FINE , "Using {0} to get user Maven settings.xml" , userSettingsFile . getAbsolutePath ( ) ) ; final XMLStreamReader reader ; try { reader = XMLInputFactory . newInstance ( ) . createXMLStreamReader ( new FileInputStream ( userSettingsFile ) ) ; while ( reader . hasNext ( ) ) { if ( reader . next ( ) == XMLStreamConstants . START_ELEMENT ) { break ; } } final String topLevel = reader . getLocalName ( ) ; if ( ! "settings" . equals ( topLevel ) ) { throw new InvalidConfigurationFileException ( "Invalid format settings.xml found: " + userSettingsFile ) ; } } catch ( final FileNotFoundException e ) { } catch ( final XMLStreamException xmlse ) { throw new RuntimeException ( "Could not check file format of specified settings.xml: " + userSettingsFile , xmlse ) ; } } result = builder . build ( request ) ; } catch ( SettingsBuildingException e ) { StringBuilder sb = new StringBuilder ( "Found " ) . append ( e . getProblems ( ) . size ( ) ) . append ( " problems while building settings.xml model from both global Maven configuration file" ) . append ( request . getGlobalSettingsFile ( ) ) . append ( " and/or user configuration file: " ) . append ( request . getUserSettingsFile ( ) ) . append ( "\n" ) ; int counter = 1 ; for ( SettingsProblem problem : e . getProblems ( ) ) { sb . append ( counter ++ ) . append ( "/ " ) . append ( problem ) . append ( "\n" ) ; } throw new InvalidConfigurationFileException ( sb . toString ( ) ) ; } Settings settings = result . getEffectiveSettings ( ) ; settings = enrichWithLocalRepository ( settings ) ; settings = enrichWithOfflineMode ( settings ) ; settings = decryptPasswords ( settings ) ; return settings ; }
|
Builds Maven settings from request .
|
39,465
|
private Settings enrichWithLocalRepository ( Settings settings ) { if ( settings . getLocalRepository ( ) == null || settings . getLocalRepository ( ) . length ( ) == 0 ) { settings . setLocalRepository ( DEFAULT_REPOSITORY_PATH ) ; } String altLocalRepository = SecurityActions . getProperty ( ALT_LOCAL_REPOSITORY_LOCATION ) ; if ( altLocalRepository != null && altLocalRepository . length ( ) > 0 ) { settings . setLocalRepository ( altLocalRepository ) ; } return settings ; }
|
adds local repository
|
39,466
|
private Settings enrichWithOfflineMode ( Settings settings ) { String goOffline = SecurityActions . getProperty ( ALT_MAVEN_OFFLINE ) ; if ( goOffline != null && goOffline . length ( ) > 0 ) { settings . setOffline ( Boolean . valueOf ( goOffline ) ) ; } return settings ; }
|
adds offline mode from system property
|
39,467
|
public static < RESOLVERSYSTEMTYPE extends ResolverSystem > RESOLVERSYSTEMTYPE use ( final Class < RESOLVERSYSTEMTYPE > clazz ) throws IllegalArgumentException { return ResolverSystemFactory . createFromUserView ( clazz ) ; }
|
Creates and returns a new instance of the specified view type .
|
39,468
|
public static Dependency asDependency ( MavenDependencySPI dependency , ArtifactTypeRegistry registry ) { String scope = dependency . getScope ( ) . toString ( ) ; if ( dependency . isUndeclaredScope ( ) ) { scope = EMPTY ; } return new Dependency ( asArtifact ( dependency , registry ) , scope , dependency . isOptional ( ) , asExclusions ( dependency . getExclusions ( ) ) ) ; }
|
Converts MavenDepedency to Dependency representation used in Aether
|
39,469
|
public static Proxy asProxy ( org . apache . maven . settings . Proxy proxy ) { final Authentication authentication ; if ( proxy . getUsername ( ) != null || proxy . getPassword ( ) != null ) { authentication = new AuthenticationBuilder ( ) . addUsername ( proxy . getUsername ( ) ) . addPassword ( proxy . getPassword ( ) ) . build ( ) ; } else { authentication = null ; } return new Proxy ( proxy . getProtocol ( ) , proxy . getHost ( ) , proxy . getPort ( ) , authentication ) ; }
|
Converts Maven Proxy to Aether Proxy
|
39,470
|
private static String manifestAsString ( Manifest manifest ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; try { manifest . write ( baos ) ; return baos . toString ( "UTF-8" ) ; } catch ( IOException e ) { throw new IllegalStateException ( "Unable to write MANIFEST.MF to an archive Asset" , e ) ; } finally { try { baos . close ( ) ; } catch ( IOException e ) { } } }
|
Conversion method from Manifest to String .
|
39,471
|
@ SuppressWarnings ( "unchecked" ) private < T > ShrinkWrapResolverServiceLocator setServices ( Class < T > type , T ... services ) { CacheItem item = cache . get ( type ) ; if ( item == null ) { item = new CacheItem ( type ) ; } item . replaceInstances ( services ) ; cache . put ( type , item ) ; return this ; }
|
Sets the instances for a service .
|
39,472
|
static MavenResolvedArtifact fromArtifactResult ( final ArtifactResult artifactResult ) { final Artifact artifact = artifactResult . getArtifact ( ) ; final DependencyNode root = artifactResult . getRequest ( ) . getDependencyNode ( ) ; ScopeType scopeType = ScopeType . RUNTIME ; try { scopeType = ScopeType . fromScopeType ( root . getDependency ( ) . getScope ( ) ) ; } catch ( IllegalArgumentException e ) { log . log ( Level . WARNING , "Invalid scope {0} of retrieved dependency {1} will be replaced by <scope>runtime</scope>" , new Object [ ] { root . getDependency ( ) . getScope ( ) , root . getDependency ( ) . getArtifact ( ) } ) ; } final List < DependencyNode > children = root . getChildren ( ) ; final boolean optional = root . getDependency ( ) . isOptional ( ) ; return new MavenResolvedArtifactImpl ( artifact , scopeType , children , optional ) ; }
|
Creates MavenResolvedArtifact based on ArtifactResult .
|
39,473
|
private static File artifactToFile ( final Artifact artifact ) throws IllegalArgumentException { if ( artifact == null ) { throw new IllegalArgumentException ( "ArtifactResult must not be null" ) ; } if ( "pom.xml" . equals ( artifact . getFile ( ) . getName ( ) ) ) { String artifactId = artifact . getArtifactId ( ) ; String extension = artifact . getExtension ( ) ; String classifier = artifact . getClassifier ( ) ; File root = new File ( artifact . getFile ( ) . getParentFile ( ) , "target/classes" ) ; if ( ! Validate . isNullOrEmpty ( classifier ) && "tests" . equals ( classifier ) ) { root = new File ( artifact . getFile ( ) . getParentFile ( ) , "target/test-classes" ) ; } else if ( "war" . equals ( artifact . getProperty ( ArtifactProperties . TYPE , null ) ) ) { root = new File ( artifact . getFile ( ) . getParentFile ( ) , "target/" + artifactId + "-" + artifact . getVersion ( ) ) ; } try { File archive = File . createTempFile ( artifactId + "-" , "." + extension ) ; archive . deleteOnExit ( ) ; PackageDirHelper . packageDirectories ( archive , root ) ; return archive ; } catch ( IOException e ) { throw new IllegalArgumentException ( "Unable to get artifact " + artifactId + " from the classpath" , e ) ; } } else { return artifact . getFile ( ) ; } }
|
Maps an artifact to a file . This allows ShrinkWrap Maven resolver to package reactor related dependencies .
|
39,474
|
public static List < String > explicitlyActivatedProfiles ( String ... profiles ) { if ( profiles . length == 0 ) { return Collections . < String > emptyList ( ) ; } List < String > activated = new ArrayList < String > ( ) ; for ( String profileId : profiles ) { Validate . notNullOrEmpty ( profileId , "Invalid name (\"" + profileId + "\") of a profile to be activated" ) ; if ( ! ( profileId . startsWith ( "-" ) || profileId . startsWith ( "!" ) ) ) { activated . add ( profileId ) ; } } return activated ; }
|
selects all profile ids to be activated
|
39,475
|
public static List < String > explicitlyDisabledProfiles ( String ... profiles ) { if ( profiles . length == 0 ) { return Collections . < String > emptyList ( ) ; } List < String > disabled = new ArrayList < String > ( ) ; for ( String profileId : profiles ) { if ( profileId != null && ( profileId . startsWith ( "-" ) || profileId . startsWith ( "!" ) ) ) { String disabledId = profileId . substring ( 1 ) ; Validate . notNullOrEmpty ( disabledId , "Invalid name (\"" + profileId + "\") of a profile do be disabled" ) ; disabled . add ( disabledId ) ; } } return disabled ; }
|
selects all profiles ids to be disabled
|
39,476
|
private ClassLoader getCombinedClassLoader ( ClassRealmManager manager ) { List < URL > urlList = new ArrayList < URL > ( ) ; ClassLoader threadCL = SecurityActions . getThreadContextClassLoader ( ) ; if ( threadCL instanceof URLClassLoader ) { urlList . addAll ( Arrays . asList ( ( ( URLClassLoader ) threadCL ) . getURLs ( ) ) ) ; } ClassRealm core = manager . getCoreRealm ( ) ; if ( core != null ) { urlList . addAll ( Arrays . asList ( core . getURLs ( ) ) ) ; } ClassRealm mavenApi = manager . getMavenApiRealm ( ) ; if ( mavenApi != null ) { urlList . addAll ( Arrays . asList ( mavenApi . getURLs ( ) ) ) ; } URLClassLoader cl = new URLClassLoader ( urlList . toArray ( new URL [ 0 ] ) , threadCL ) ; return cl ; }
|
creates a class loader that has access to both current thread classloader and Maven Core classloader
|
39,477
|
static Collection < MavenResolvedArtifact > postFilter ( final Collection < MavenResolvedArtifact > artifactResults ) { final MavenResolutionFilter postResolutionFilter = RestrictPomArtifactFilter . INSTANCE ; final Collection < MavenResolvedArtifact > filteredArtifacts = new ArrayList < MavenResolvedArtifact > ( ) ; final List < MavenDependency > emptyList = Collections . emptyList ( ) ; for ( final MavenResolvedArtifact artifact : artifactResults ) { final MavenDependency dependency = MavenDependencies . createDependency ( artifact . getCoordinate ( ) , ScopeType . COMPILE , false ) ; if ( postResolutionFilter . accepts ( dependency , emptyList , emptyList ) ) { filteredArtifacts . add ( artifact ) ; } } return Collections . unmodifiableCollection ( filteredArtifacts ) ; }
|
Run post - resolution filtering to weed out POMs .
|
39,478
|
public void setAdapter ( SlideShowAdapter adapter ) { if ( this . adapter != null ) { this . adapter . unregisterDataSetObserver ( adapterObserver ) ; } this . adapter = adapter ; this . adapter . registerDataSetObserver ( adapterObserver ) ; if ( adapter != null ) { PlayList pl = getPlaylist ( ) ; pl . onSlideCountChanged ( adapter . getCount ( ) ) ; pl . rewind ( ) ; prepareSlide ( pl . getFirstSlide ( ) ) ; } }
|
Set the adapter that will create views for the slides
|
39,479
|
public void setPlaylist ( PlayList playlist ) { this . playlist = playlist ; if ( adapter != null ) { playlist . onSlideCountChanged ( adapter . getCount ( ) ) ; } }
|
Set the playlist
|
39,480
|
public void next ( ) { final PlayList pl = getPlaylist ( ) ; final int previousPosition = pl . getCurrentSlide ( ) ; pl . next ( ) ; final int currentPosition = pl . getCurrentSlide ( ) ; playSlide ( currentPosition , previousPosition ) ; }
|
Move to the next slide
|
39,481
|
public void previous ( ) { final PlayList pl = getPlaylist ( ) ; final int previousPosition = pl . getCurrentSlide ( ) ; pl . previous ( ) ; final int currentPosition = pl . getCurrentSlide ( ) ; playSlide ( currentPosition , previousPosition ) ; }
|
Move to the previous slide
|
39,482
|
public void stop ( ) { status = Status . STOPPED ; slideHandler . removeCallbacksAndMessages ( null ) ; removeAllViews ( ) ; recycledViews . clear ( ) ; }
|
Stop playing the show
|
39,483
|
public void pause ( ) { switch ( status ) { case PAUSED : case STOPPED : return ; case PLAYING : status = Status . PAUSED ; slideHandler . removeCallbacksAndMessages ( null ) ; } }
|
Pause the slide show
|
39,484
|
public void resume ( ) { switch ( status ) { case PLAYING : return ; case STOPPED : play ( ) ; return ; default : status = Status . PLAYING ; PlayList pl = getPlaylist ( ) ; if ( pl . isAutoAdvanceEnabled ( ) ) { slideHandler . removeCallbacks ( moveToNextSlide ) ; slideHandler . postDelayed ( moveToNextSlide , pl . getSlideDuration ( pl . getCurrentSlide ( ) ) ) ; } } }
|
Resume the slideshow
|
39,485
|
protected void playSlide ( int currentPosition , int previousPosition ) { final SlideStatus slideStatus = adapter . getSlideStatus ( currentPosition ) ; final PlayList pl = getPlaylist ( ) ; if ( currentPosition < 0 ) { stop ( ) ; return ; } slideHandler . removeCallbacksAndMessages ( null ) ; switch ( slideStatus ) { case READY : notAvailableSlidesSkipped = 0 ; status = Status . PLAYING ; if ( pl . isAutoAdvanceEnabled ( ) ) { slideHandler . postDelayed ( moveToNextSlide , pl . getSlideDuration ( currentPosition ) ) ; } displaySlide ( currentPosition , previousPosition ) ; break ; case NOT_AVAILABLE : Log . w ( "SlideShowView" , "Slide is not available: " + currentPosition ) ; ++ notAvailableSlidesSkipped ; if ( notAvailableSlidesSkipped < adapter . getCount ( ) ) { prepareSlide ( pl . getNextSlide ( ) ) ; next ( ) ; } else { Log . w ( "SlideShowView" , "Skipped too many slides in a row. Stopping playback." ) ; stop ( ) ; } break ; case LOADING : Log . d ( "SlideShowView" , "Slide is not yet ready, waiting for it: " + currentPosition ) ; showProgressIndicator ( ) ; waitForCurrentSlide . startWaiting ( currentPosition , previousPosition ) ; break ; } }
|
Play the current slide in the playlist if it is ready . If that slide is not available we move to the next one . If that slide is loading we wait until it is ready and then we play it .
|
39,486
|
private void displaySlide ( final int currentPosition , final int previousPosition ) { Log . v ( "SlideShowView" , "Displaying slide at position: " + currentPosition ) ; hideProgressIndicator ( ) ; final View inView = getSlideView ( currentPosition ) ; inView . setVisibility ( View . INVISIBLE ) ; addView ( inView ) ; notifyBeforeSlideShown ( currentPosition ) ; final TransitionFactory tf = getTransitionFactory ( ) ; final Animator inAnimator = tf . getInAnimator ( inView , this , previousPosition , currentPosition ) ; if ( inAnimator != null ) { inAnimator . addListener ( new AnimatorListenerAdapter ( ) { public void onAnimationStart ( Animator animation ) { inView . setVisibility ( View . VISIBLE ) ; } public void onAnimationEnd ( Animator animation ) { notifySlideShown ( currentPosition ) ; } } ) ; inAnimator . start ( ) ; } else { inView . setVisibility ( View . VISIBLE ) ; notifySlideShown ( currentPosition ) ; } int childCount = getChildCount ( ) ; if ( childCount > 1 ) { notifyBeforeSlideHidden ( previousPosition ) ; final View outView = getChildAt ( 0 ) ; final Animator outAnimator = tf . getOutAnimator ( outView , this , previousPosition , currentPosition ) ; if ( outAnimator != null ) { outAnimator . addListener ( new AnimatorListenerAdapter ( ) { public void onAnimationEnd ( Animator animation ) { outView . setVisibility ( View . INVISIBLE ) ; notifySlideHidden ( previousPosition ) ; recyclePreviousSlideView ( previousPosition , outView ) ; } } ) ; outAnimator . start ( ) ; } else { outView . setVisibility ( View . INVISIBLE ) ; notifySlideHidden ( previousPosition ) ; recyclePreviousSlideView ( previousPosition , outView ) ; } } }
|
Display the view for the given slide launching the appropriate transitions if available
|
39,487
|
private View getSlideView ( int position ) { int viewType = adapter . getItemViewType ( position ) ; View recycledView = recycledViews . get ( viewType ) ; View v = adapter . getView ( position , recycledView , this ) ; return v ; }
|
Get a view for the slide at the given index . If possible we will reuse a view from our recycled pool . If not we will ask the adapter to create one from scratch .
|
39,488
|
private void recyclePreviousSlideView ( int position , View view ) { removeView ( view ) ; int viewType = adapter . getItemViewType ( position ) ; recycledViews . put ( viewType , view ) ; view . destroyDrawingCache ( ) ; if ( view instanceof ImageView ) { ( ( ImageView ) view ) . setImageDrawable ( null ) ; } Log . d ( "SlideShowView" , "View added to recycling bin: " + view ) ; adapter . discardSlide ( position ) ; prepareSlide ( getPlaylist ( ) . getNextSlide ( ) ) ; }
|
Once the previous slide has disappeared we remove its view from our hierarchy and add it to the views that can be re - used .
|
39,489
|
protected void showProgressIndicator ( ) { removeView ( progressIndicator ) ; progressIndicator . setAlpha ( 0 ) ; addView ( progressIndicator ) ; progressIndicator . animate ( ) . alpha ( 1 ) . setDuration ( 500 ) . start ( ) ; }
|
Show the progress indicator when a slide is being loaded
|
39,490
|
public void setOnSlideClickListener ( OnSlideClickListener slideClickListener ) { this . slideClickListener = slideClickListener ; if ( slideClickListener != null ) { setClickable ( true ) ; setOnClickListener ( this ) ; } else { setClickable ( false ) ; setOnClickListener ( null ) ; } }
|
Set the click listener for the slides and makes this view clickable
|
39,491
|
protected void onBitmapLoaded ( int position , Bitmap bitmap ) { BitmapCache bc = cachedBitmaps . get ( position ) ; if ( bc != null ) { bc . status = bitmap == null ? SlideStatus . NOT_AVAILABLE : SlideStatus . READY ; bc . bitmap = new WeakReference < Bitmap > ( bitmap ) ; } }
|
This function should be called by subclasses once they have actually loaded the bitmap .
|
39,492
|
protected void onBitmapNotAvailable ( int position ) { BitmapCache bc = cachedBitmaps . get ( position ) ; if ( bc != null ) { bc . status = SlideStatus . NOT_AVAILABLE ; bc . bitmap = null ; } }
|
This function should be called by subclasses when they could not load a bitmap
|
39,493
|
protected ImageView newImageViewInstance ( ) { ImageView iv = new ImageView ( context ) ; iv . setScaleType ( ImageView . ScaleType . CENTER_CROP ) ; RelativeLayout . LayoutParams lp = new RelativeLayout . LayoutParams ( ViewGroup . LayoutParams . MATCH_PARENT , RelativeLayout . LayoutParams . MATCH_PARENT ) ; lp . addRule ( RelativeLayout . ALIGN_PARENT_TOP ) ; lp . addRule ( RelativeLayout . ALIGN_PARENT_LEFT ) ; iv . setLayoutParams ( lp ) ; return iv ; }
|
Create the ImageView that will be used to show the bitmap .
|
39,494
|
public String getSignature ( Request request , ClientCredential credential ) throws RequestSigningException { return getSignature ( request , credential , System . currentTimeMillis ( ) , generateNonce ( ) ) ; }
|
Generates signature for a given HTTP request and client credential . The result of this method call should be appended as the Authorization header to an HTTP request .
|
39,495
|
private void buildRuntimeTree ( ) { updateRuntime ( ) ; Runtime rootInfo = findRuntime ( ) ; root = new RuntimeNode ( ) ; root . setFrameName ( "_top" ) ; root . setRuntimeID ( rootInfo . getRuntimeID ( ) ) ; List < Runtime > runtimeInfos = Lists . newArrayList ( runtimesList . values ( ) ) ; runtimeInfos . remove ( rootInfo ) ; for ( Runtime runtimeInfo : runtimeInfos ) { addNode ( runtimeInfo , root ) ; } }
|
Updates the runtimes list to most recent version .
|
39,496
|
private Runtime getRuntime ( int runtimeID ) { ListRuntimesArg . Builder builder = ListRuntimesArg . newBuilder ( ) ; builder . addRuntimeIDList ( runtimeID ) ; builder . setCreate ( true ) ; Response response = executeMessage ( EcmascriptMessage . LIST_RUNTIMES , builder ) ; RuntimeList . Builder runtimeListBuilder = RuntimeList . newBuilder ( ) ; buildPayload ( response , runtimeListBuilder ) ; List < Runtime > runtimes = runtimeListBuilder . build ( ) . getRuntimeListList ( ) ; return ( runtimes . isEmpty ( ) ) ? null : runtimes . get ( 0 ) ; }
|
Queries for the given runtime ID
|
39,497
|
public static JSONWrapper wrap ( String s ) { if ( S . empty ( s ) ) { return null ; } return new JSONWrapper ( s ) ; }
|
Parse the string and return the JSONWrapper
|
39,498
|
public boolean contains ( Object o ) { if ( o instanceof String ) { return set . contains ( ( ( String ) o ) . toLowerCase ( ) ) ; } else { return set . contains ( o ) ; } }
|
Returns true if this set contains the specified string compared case - insensitively .
|
39,499
|
public void deleteCache ( TemplateClass tc ) { if ( ! writeEnabled ( ) ) return ; try { File f = getCacheFile ( tc ) ; if ( f . exists ( ) && ! f . delete ( ) ) { f . deleteOnExit ( ) ; } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
|
Delete the bytecode
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.