idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
18,100
private void deleteAppProperties ( ApplicationDefinition appDef ) { Tenant tenant = Tenant . getTenant ( appDef ) ; DBTransaction dbTran = DBService . instance ( tenant ) . startTransaction ( ) ; dbTran . deleteRow ( SchemaService . APPS_STORE_NAME , appDef . getAppName ( ) ) ; DBService . instance ( tenant ) . commit ( dbTran ) ; }
Delete the given application s schema row from the Applications CF .
18,101
private void initializeApplication ( ApplicationDefinition currAppDef , ApplicationDefinition appDef ) { getStorageService ( appDef ) . initializeApplication ( currAppDef , appDef ) ; storeApplicationSchema ( appDef ) ; }
Initialize storage and store the given schema for the given new or updated application .
18,102
private void storeApplicationSchema ( ApplicationDefinition appDef ) { String appName = appDef . getAppName ( ) ; Tenant tenant = Tenant . getTenant ( appDef ) ; DBTransaction dbTran = DBService . instance ( tenant ) . startTransaction ( ) ; dbTran . addColumn ( SchemaService . APPS_STORE_NAME , appName , COLNAME_APP_SCHEMA , appDef . toDoc ( ) . toJSON ( ) ) ; dbTran . addColumn ( SchemaService . APPS_STORE_NAME , appName , COLNAME_APP_SCHEMA_FORMAT , ContentType . APPLICATION_JSON . toString ( ) ) ; dbTran . addColumn ( SchemaService . APPS_STORE_NAME , appName , COLNAME_APP_SCHEMA_VERSION , Integer . toString ( CURRENT_SCHEMA_LEVEL ) ) ; DBService . instance ( tenant ) . commit ( dbTran ) ; }
Store the application row with schema version and format .
18,103
private ApplicationDefinition checkApplicationKey ( ApplicationDefinition appDef ) { Tenant tenant = Tenant . getTenant ( appDef ) ; ApplicationDefinition currAppDef = getApplication ( tenant , appDef . getAppName ( ) ) ; if ( currAppDef == null ) { m_logger . info ( "Defining application: {}" , appDef . getAppName ( ) ) ; } else { m_logger . info ( "Updating application: {}" , appDef . getAppName ( ) ) ; String appKey = currAppDef . getKey ( ) ; Utils . require ( Utils . isEmpty ( appKey ) || appKey . equals ( appDef . getKey ( ) ) , "Application key cannot be changed: %s" , appDef . getKey ( ) ) ; } return currAppDef ; }
Verify key match of an existing application if any and return it s definition .
18,104
private StorageService verifyStorageServiceOption ( ApplicationDefinition currAppDef , ApplicationDefinition appDef ) { String ssName = getStorageServiceOption ( appDef ) ; StorageService storageService = getStorageService ( appDef ) ; Utils . require ( storageService != null , "StorageService is unknown or hasn't been initialized: %s" , ssName ) ; if ( currAppDef != null ) { String currSSName = getStorageServiceOption ( currAppDef ) ; Utils . require ( currSSName . equals ( ssName ) , "'StorageService' cannot be changed for application: %s" , appDef . getAppName ( ) ) ; } return storageService ; }
change ensure it hasn t changed . Return the application s StorageService object .
18,105
private ApplicationDefinition loadAppRow ( Tenant tenant , Map < String , String > colMap ) { ApplicationDefinition appDef = new ApplicationDefinition ( ) ; String appSchema = colMap . get ( COLNAME_APP_SCHEMA ) ; if ( appSchema == null ) { return null ; } String format = colMap . get ( COLNAME_APP_SCHEMA_FORMAT ) ; ContentType contentType = Utils . isEmpty ( format ) ? ContentType . TEXT_XML : new ContentType ( format ) ; String versionStr = colMap . get ( COLNAME_APP_SCHEMA_VERSION ) ; int schemaVersion = Utils . isEmpty ( versionStr ) ? CURRENT_SCHEMA_LEVEL : Integer . parseInt ( versionStr ) ; if ( schemaVersion > CURRENT_SCHEMA_LEVEL ) { m_logger . warn ( "Skipping schema with advanced version: {}" , schemaVersion ) ; return null ; } try { appDef . parse ( UNode . parse ( appSchema , contentType ) ) ; } catch ( Exception e ) { m_logger . warn ( "Error parsing schema for application '" + appDef . getAppName ( ) + "'; skipped" , e ) ; return null ; } appDef . setTenantName ( tenant . getName ( ) ) ; return appDef ; }
Parse the application schema from the given application row .
18,106
private ApplicationDefinition getApplicationDefinition ( Tenant tenant , String appName ) { Iterator < DColumn > colIter = DBService . instance ( tenant ) . getAllColumns ( SchemaService . APPS_STORE_NAME , appName ) . iterator ( ) ; if ( ! colIter . hasNext ( ) ) { return null ; } return loadAppRow ( tenant , getColumnMap ( colIter ) ) ; }
Get the given application s application .
18,107
private Collection < ApplicationDefinition > findAllApplications ( Tenant tenant ) { List < ApplicationDefinition > result = new ArrayList < > ( ) ; Iterator < DRow > rowIter = DBService . instance ( tenant ) . getAllRows ( SchemaService . APPS_STORE_NAME ) . iterator ( ) ; while ( rowIter . hasNext ( ) ) { DRow row = rowIter . next ( ) ; ApplicationDefinition appDef = loadAppRow ( tenant , getColumnMap ( row . getAllColumns ( 1024 ) . iterator ( ) ) ) ; if ( appDef != null ) { result . add ( appDef ) ; } } return result ; }
Get all application definitions for the given Tenant .
18,108
public SearchResultList objectQuery ( TableDefinition tableDef , OlapQuery olapQuery ) { checkServiceState ( ) ; return m_olap . search ( tableDef . getAppDef ( ) , tableDef . getTableName ( ) , olapQuery ) ; }
Perform an object query on the given table using the given query parameters .
18,109
public AggregateResult aggregateQuery ( TableDefinition tableDef , OlapAggregate request ) { checkServiceState ( ) ; AggregationResult result = m_olap . aggregate ( tableDef . getAppDef ( ) , tableDef . getTableName ( ) , request ) ; return AggregateResultConverter . create ( result , request ) ; }
Perform an aggregate query on the given table using the given request .
18,110
public BatchResult addBatch ( ApplicationDefinition appDef , String shardName , OlapBatch batch ) { return addBatch ( appDef , shardName , batch , null ) ; }
Add a batch of updates for the given application to the given shard . Objects can new updated or deleted .
18,111
public void deleteShard ( ApplicationDefinition appDef , String shard ) { checkServiceState ( ) ; m_olap . deleteShard ( appDef , shard ) ; }
Delete the shard for the given application including all of its data . This method is a no - op if the given shard does not exist or has no data .
18,112
public UNode getStatistics ( ApplicationDefinition appDef , String shard , Map < String , String > paramMap ) { checkServiceState ( ) ; CubeSearcher searcher = m_olap . getSearcher ( appDef , shard ) ; String file = paramMap . get ( "file" ) ; if ( file != null ) { return OlapStatistics . getFileData ( searcher , file ) ; } String sort = paramMap . get ( "sort" ) ; boolean memStats = ! "false" . equals ( paramMap . get ( "mem" ) ) ; return OlapStatistics . getStatistics ( searcher , sort , memStats ) ; }
Get detailed shard statistics for the given shard . This command is mostly used for development and diagnostics .
18,113
public Date getExpirationDate ( ApplicationDefinition appDef , String shard ) { checkServiceState ( ) ; return m_olap . getExpirationDate ( appDef , shard ) ; }
Get the expire - date for the given shard name and OLAP application . Null is returned if the shard does not exist or has no expire - date .
18,114
private boolean getOverwriteOption ( Map < String , String > options ) { boolean bOverwrite = true ; if ( options != null ) { for ( String name : options . keySet ( ) ) { if ( "overwrite" . equals ( name . toLowerCase ( ) ) ) { bOverwrite = Boolean . parseBoolean ( options . get ( name ) ) ; } else { Utils . require ( false , "Unknown OLAP batch option: " + name ) ; } } } return bOverwrite ; }
Get case - insensitive overwrite option . Default to true .
18,115
private void validateApplication ( ApplicationDefinition appDef ) { boolean bSawAgingFreq = false ; for ( String optName : appDef . getOptionNames ( ) ) { String optValue = appDef . getOption ( optName ) ; switch ( optName ) { case CommonDefs . OPT_STORAGE_SERVICE : assert optValue . equals ( this . getClass ( ) . getSimpleName ( ) ) ; break ; case CommonDefs . OPT_AGING_CHECK_FREQ : new TaskFrequency ( optValue ) ; bSawAgingFreq = true ; break ; case "auto-merge" : new TaskFrequency ( optValue ) ; break ; default : throw new IllegalArgumentException ( "Unknown option for OLAPService application: " + optName ) ; } } for ( TableDefinition tableDef : appDef . getTableDefinitions ( ) . values ( ) ) { validateTable ( tableDef ) ; } if ( ! bSawAgingFreq ) { appDef . setOption ( CommonDefs . OPT_AGING_CHECK_FREQ , "1 DAY" ) ; } }
Validate the given application for OLAP constraints .
18,116
private void validateTable ( TableDefinition tableDef ) { for ( String optName : tableDef . getOptionNames ( ) ) { Utils . require ( false , "Unknown option for OLAPService table: " + optName ) ; } for ( FieldDefinition fieldDef : tableDef . getFieldDefinitions ( ) ) { validateField ( fieldDef ) ; } }
Validate the given table for OLAP constraints .
18,117
public Collection < String > getKeyspaces ( DBConn dbConn ) { List < String > result = new ArrayList < > ( ) ; try { for ( KsDef ksDef : dbConn . getClientSession ( ) . describe_keyspaces ( ) ) { result . add ( ksDef . getName ( ) ) ; } } catch ( Exception e ) { String errMsg = "Failed to get keyspace description" ; m_logger . error ( errMsg , e ) ; throw new RuntimeException ( errMsg , e ) ; } return result ; }
Get a list of all known keyspaces . This method can be used with any DB connection .
18,118
public void createKeyspace ( DBConn dbConn , String keyspace ) { m_logger . info ( "Creating Keyspace '{}'" , keyspace ) ; try { KsDef ksDef = setKeySpaceOptions ( keyspace ) ; dbConn . getClientSession ( ) . system_add_keyspace ( ksDef ) ; waitForSchemaPropagation ( dbConn ) ; Thread . sleep ( 1000 ) ; } catch ( Exception ex ) { String errMsg = "Failed to create Keyspace '" + keyspace + "'" ; m_logger . error ( errMsg , ex ) ; throw new RuntimeException ( errMsg , ex ) ; } }
Create a new keyspace with the given name . The keyspace is created with parameters defined for our DBService instance if any . This method should be used with a no - keyspace DB connection .
18,119
public boolean keyspaceExists ( DBConn dbConn , String keyspace ) { try { dbConn . getClientSession ( ) . describe_keyspace ( keyspace ) ; return true ; } catch ( Exception e ) { return false ; } }
Return true if a keyspace with the given name exists . This method can be used with any DB connection .
18,120
public void dropKeyspace ( DBConn dbConn , String keyspace ) { m_logger . info ( "Deleting Keyspace '{}'" , keyspace ) ; try { dbConn . getClientSession ( ) . system_drop_keyspace ( keyspace ) ; waitForSchemaPropagation ( dbConn ) ; } catch ( Exception ex ) { String errMsg = "Failed to delete Keyspace '" + keyspace + "'" ; m_logger . error ( errMsg , ex ) ; throw new RuntimeException ( errMsg , ex ) ; } }
Delete the keyspace with the given name . This method can use any DB connection .
18,121
public void createColumnFamily ( DBConn dbConn , String keyspace , String cfName , boolean bBinaryValues ) { m_logger . info ( "Creating ColumnFamily: {}:{}" , keyspace , cfName ) ; CfDef cfDef = new CfDef ( ) ; cfDef . setKeyspace ( keyspace ) ; cfDef . setName ( cfName ) ; cfDef . setColumn_type ( "Standard" ) ; cfDef . setComparator_type ( "UTF8Type" ) ; cfDef . setKey_validation_class ( "UTF8Type" ) ; if ( bBinaryValues ) { cfDef . setDefault_validation_class ( "BytesType" ) ; } else { cfDef . setDefault_validation_class ( "UTF8Type" ) ; } Map < String , Object > cfOptions = m_service . getParamMap ( "cf_defaults" ) ; if ( cfOptions != null ) { for ( String optName : cfOptions . keySet ( ) ) { Object optValue = cfOptions . get ( optName ) ; CfDef . _Fields fieldEnum = CfDef . _Fields . findByName ( optName ) ; if ( fieldEnum == null ) { m_logger . warn ( "Unknown ColumnFamily option: {}" , optName ) ; continue ; } try { cfDef . setFieldValue ( fieldEnum , optValue ) ; } catch ( Exception e ) { m_logger . warn ( "Error setting ColumnFamily option '" + optName + "' to '" + optValue + "' -- ignoring" , e ) ; } } } for ( int attempt = 1 ; ! columnFamilyExists ( dbConn , keyspace , cfName ) ; attempt ++ ) { try { dbConn . getClientSession ( ) . system_add_column_family ( cfDef ) ; waitForSchemaPropagation ( dbConn ) ; } catch ( Exception ex ) { if ( attempt > m_service . getParamInt ( "max_commit_attempts" , 10 ) ) { String msg = String . format ( "%d attempts to create ColumnFamily %s:%s failed" , attempt , keyspace , cfName ) ; throw new RuntimeException ( msg , ex ) ; } try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException e ) { } } } }
Create a new ColumnFamily with the given parameters . If the new CF is created successfully wait for all nodes in the cluster to receive the schema change before returning . An exception is thrown if the CF create fails . The current DB connection can be connected to any keyspace .
18,122
public boolean columnFamilyExists ( DBConn dbConn , String keyspace , String cfName ) { KsDef ksDef = null ; try { ksDef = dbConn . getClientSession ( ) . describe_keyspace ( keyspace ) ; } catch ( Exception ex ) { throw new RuntimeException ( "Failed to get keyspace definition for '" + keyspace + "'" , ex ) ; } List < CfDef > cfDefList = ksDef . getCf_defs ( ) ; for ( CfDef cfDef : cfDefList ) { if ( cfDef . getName ( ) . equals ( cfName ) ) { return true ; } } return false ; }
Return true if the given store name currently exists in the given keyspace . This method can be used with a connection connected to any keyspace .
18,123
public void deleteColumnFamily ( DBConn dbConn , String cfName ) { m_logger . info ( "Deleting ColumnFamily: {}" , cfName ) ; try { dbConn . getClientSession ( ) . system_drop_column_family ( cfName ) ; waitForSchemaPropagation ( dbConn ) ; } catch ( Exception ex ) { throw new RuntimeException ( "drop_column_family failed" , ex ) ; } }
Delete the column family with the given name . The given DB connection must be connected to the keyspace in which the CF is to be deleted .
18,124
private KsDef setKeySpaceOptions ( String keyspace ) { KsDef ksDef = new KsDef ( ) ; ksDef . setName ( keyspace ) ; Map < String , Object > ksDefs = m_service . getParamMap ( "ks_defaults" ) ; if ( ksDefs != null ) { for ( String name : ksDefs . keySet ( ) ) { Object value = ksDefs . get ( name ) ; try { KsDef . _Fields field = KsDef . _Fields . findByName ( name ) ; if ( field == null ) { m_logger . warn ( "Unknown KeySpace option: {} -- ignoring" , name ) ; } else { ksDef . setFieldValue ( field , value ) ; } } catch ( Exception e ) { m_logger . warn ( "Error setting Keyspace option '" + name + "' to '" + value + "' -- ignoring" , e ) ; } } } if ( m_service . getParam ( "ReplicationFactor" ) != null ) { Map < String , String > stratOpts = new HashMap < > ( ) ; stratOpts . put ( "replication_factor" , m_service . getParamString ( "ReplicationFactor" ) ) ; ksDef . setStrategy_options ( stratOpts ) ; } if ( ! ksDef . isSetStrategy_class ( ) ) { ksDef . setStrategy_class ( DEFAULT_KS_STRATEGY_CLASS ) ; } if ( ! ksDef . isSetStrategy_options ( ) ) { Map < String , String > stratOpts = new HashMap < > ( ) ; stratOpts . put ( "replication_factor" , DEFAULT_KS_REPLICATION_FACTOR ) ; ksDef . setStrategy_options ( stratOpts ) ; } if ( ! ksDef . isSetCf_defs ( ) ) { ksDef . setCf_defs ( DEFAULT_KS_CF_DEFS ) ; } if ( ! ksDef . isSetDurable_writes ( ) ) { ksDef . setDurable_writes ( DEFAULT_KS_DURABLE_WRITES ) ; } return ksDef ; }
Build KsDef from doradus . yaml and DBService - specific options .
18,125
private void waitForSchemaPropagation ( DBConn dbConn ) { for ( int i = 0 ; i < 5 ; i ++ ) { try { Map < String , List < String > > versions = dbConn . getClientSession ( ) . describe_schema_versions ( ) ; if ( versions . size ( ) <= 1 ) return ; m_logger . info ( "Schema versions are not synchronized yet. Retrying" ) ; Thread . sleep ( 500 + 1000 * i ) ; } catch ( Exception ex ) { m_logger . warn ( "Error waiting for schema propagation: {}" , ex . getMessage ( ) ) ; } m_logger . error ( "Schema versions have not been synchronized" ) ; } }
This method waits until all the nodes have the same schema
18,126
public static OutputStream outputStream ( File file ) { try { return new FileOutputStream ( file ) ; } catch ( FileNotFoundException e ) { throw E . ioException ( e ) ; } }
Returns a file output stream
18,127
public static Writer writer ( File file ) { try { return new FileWriter ( file ) ; } catch ( IOException e ) { throw E . ioException ( e ) ; } }
Returns a file writer
18,128
public static InputStream inputStream ( File file ) { if ( ! file . exists ( ) ) { file = file . getAbsoluteFile ( ) ; } if ( ! file . exists ( ) ) { throw E . ioException ( "File does not exists: %s" , file . getPath ( ) ) ; } try { return new FileInputStream ( file ) ; } catch ( FileNotFoundException e ) { throw E . ioException ( e ) ; } }
Returns a file input stream
18,129
public static InputStream inputStream ( URL url ) { try { return url . openStream ( ) ; } catch ( IOException e ) { throw E . ioException ( e ) ; } }
Create an input stream from a URL .
18,130
public static Reader reader ( File file ) { E . illegalArgumentIfNot ( file . canRead ( ) , "file not readable: " + file . getPath ( ) ) ; try { return new FileReader ( file ) ; } catch ( IOException e ) { throw E . ioException ( e ) ; } }
Returns a file reader
18,131
public static String checksum ( InputStream is ) { try { MessageDigest md = MessageDigest . getInstance ( "SHA1" ) ; byte [ ] dataBytes = new byte [ 1024 ] ; int nread ; while ( ( nread = is . read ( dataBytes ) ) != - 1 ) { md . update ( dataBytes , 0 , nread ) ; } byte [ ] mdbytes = md . digest ( ) ; S . Buffer sb = S . buffer ( ) ; for ( int i = 0 ; i < mdbytes . length ; i ++ ) { sb . append ( Integer . toString ( ( mdbytes [ i ] & 0xff ) + 0x100 , 16 ) . substring ( 1 ) ) ; } return sb . toString ( ) ; } catch ( NoSuchAlgorithmException e ) { throw E . unexpected ( "SHA1 algorithm not found" ) ; } catch ( IOException e ) { throw E . ioException ( e ) ; } }
Returns checksum from an input stream .
18,132
public static Properties loadProperties ( URL url ) { if ( null == url ) { return new Properties ( ) ; } return loadProperties ( inputStream ( url ) ) ; }
Load properties from a URL
18,133
public static void writeContent ( CharSequence content , File file , String encoding ) { write ( content , file , encoding ) ; }
Write string content to a file with encoding specified .
18,134
public static void write ( CharSequence content , File file , String encoding ) { OutputStream os = null ; try { os = new FileOutputStream ( file ) ; PrintWriter printWriter = new PrintWriter ( new OutputStreamWriter ( os , encoding ) ) ; printWriter . print ( content ) ; printWriter . flush ( ) ; os . flush ( ) ; } catch ( IOException e ) { throw E . unexpected ( e ) ; } finally { close ( os ) ; } }
Write String content to a file with encoding specified
18,135
public static void write ( CharSequence content , Writer writer , boolean closeOs ) { try { writer . write ( content . toString ( ) ) ; } catch ( IOException e ) { throw E . ioException ( e ) ; } finally { if ( closeOs ) { close ( writer ) ; } } }
Write content into a writer .
18,136
public static int copy ( InputStream is , OutputStream os , boolean closeOs ) { if ( closeOs ) { return write ( is ) . ensureCloseSink ( ) . to ( os ) ; } else { return write ( is ) . to ( os ) ; } }
Copy an stream to another one . It close the input stream anyway .
18,137
public static int write ( InputStream is , File f ) { try { return copy ( is , new BufferedOutputStream ( new FileOutputStream ( f ) ) ) ; } catch ( FileNotFoundException e ) { throw E . ioException ( e ) ; } }
Read from inputstream and write into file .
18,138
public static int copy ( Reader reader , Writer writer , boolean closeWriter ) { if ( closeWriter ) { return write ( reader ) . ensureCloseSink ( ) . to ( writer ) ; } else { return write ( reader ) . to ( writer ) ; } }
Copy from a Reader into a Writer .
18,139
public static void write ( byte b , OutputStream os ) { try { os . write ( b ) ; } catch ( IOException e ) { throw E . ioException ( e ) ; } }
Write a byte into outputstream .
18,140
public static void write ( byte [ ] data , File file ) { try { write ( new ByteArrayInputStream ( data ) , new BufferedOutputStream ( new FileOutputStream ( file ) ) ) ; } catch ( FileNotFoundException e ) { throw E . ioException ( e ) ; } }
Write binary data to a file
18,141
public static void write ( byte [ ] data , OutputStream os , boolean closeSink ) { try { os . write ( data ) ; } catch ( IOException e ) { throw E . ioException ( e ) ; } finally { if ( closeSink ) { close ( os ) ; } } }
Write binary data to an outputstream .
18,142
public static void copyDirectory ( File source , File target ) { if ( source . isDirectory ( ) ) { if ( ! target . exists ( ) ) { target . mkdir ( ) ; } for ( String child : source . list ( ) ) { copyDirectory ( new File ( source , child ) , new File ( target , child ) ) ; } } else { try { write ( new FileInputStream ( source ) , new FileOutputStream ( target ) ) ; } catch ( IOException e ) { if ( target . isDirectory ( ) ) { if ( ! target . exists ( ) ) { if ( ! target . mkdirs ( ) ) { throw E . ioException ( "cannot copy [%s] to [%s]" , source , target ) ; } } target = new File ( target , source . getName ( ) ) ; } else { File targetFolder = target . getParentFile ( ) ; if ( ! targetFolder . exists ( ) ) { if ( ! targetFolder . mkdirs ( ) ) { throw E . ioException ( "cannot copy [%s] to [%s]" , source , target ) ; } } } try { write ( new FileInputStream ( source ) , new FileOutputStream ( target ) ) ; } catch ( IOException e0 ) { throw E . ioException ( e0 ) ; } } } }
If target does not exist it will be created .
18,143
public static ISObject zip ( ISObject ... objects ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; ZipOutputStream zos = new ZipOutputStream ( baos ) ; try { for ( ISObject obj : objects ) { ZipEntry entry = new ZipEntry ( obj . getAttribute ( SObject . ATTR_FILE_NAME ) ) ; InputStream is = obj . asInputStream ( ) ; zos . putNextEntry ( entry ) ; copy ( is , zos , false ) ; zos . closeEntry ( ) ; } } catch ( IOException e ) { throw E . ioException ( e ) ; } finally { close ( zos ) ; } return SObject . of ( Codec . encodeUrl ( S . random ( ) ) , baos . toByteArray ( ) ) ; }
Zip a list of sobject into a single sobject .
18,144
public static File zip ( File ... files ) { try { File temp = File . createTempFile ( "osgl" , ".zip" ) ; zipInto ( temp , files ) ; return temp ; } catch ( IOException e ) { throw E . ioException ( e ) ; } }
Zip a list of files into a single file . The name of the zip file is randomly picked up in the temp dir .
18,145
public static void zipInto ( File target , File ... files ) { ZipOutputStream zos = null ; try { zos = new ZipOutputStream ( new BufferedOutputStream ( new FileOutputStream ( target ) ) ) ; byte [ ] buffer = new byte [ 128 ] ; for ( File f : files ) { ZipEntry entry = new ZipEntry ( f . getName ( ) ) ; InputStream is = new BufferedInputStream ( new FileInputStream ( f ) ) ; zos . putNextEntry ( entry ) ; int read = 0 ; while ( ( read = is . read ( buffer ) ) != - 1 ) { zos . write ( buffer , 0 , read ) ; } zos . closeEntry ( ) ; IO . close ( is ) ; } } catch ( IOException e ) { throw E . ioException ( e ) ; } finally { IO . close ( zos ) ; } }
Zip a list of files into specified target file .
18,146
public static < T > T decode ( String string , Class < T > targetType ) { Type type = typeOf ( targetType ) ; return type . decode ( string , targetType ) ; }
Decode a object instance from a string with given target object type
18,147
public static String encode ( Object o ) { Type type = typeOf ( o ) ; return type . encode ( o ) ; }
Encode a object into a String
18,148
public int lastIndexOf ( java . util . List < Character > list ) { return lastIndexOf ( ( CharSequence ) FastStr . of ( list ) ) ; }
Returns the index within this str of the last occurrence of the specified character list
18,149
public static void addGlobalMappingFilters ( String filterSpec , String ... filterSpecs ) { addGlobalMappingFilter ( filterSpec ) ; for ( String s : filterSpecs ) { addGlobalMappingFilter ( s ) ; } }
Register global mapping filters .
18,150
public static void addGlobalMappingFilter ( String filterSpec ) { List < String > list = S . fastSplit ( filterSpec , "," ) ; for ( String s : list ) { if ( S . blank ( s ) ) { continue ; } addSingleGlobalMappingFilter ( s . trim ( ) ) ; } }
Register a global mapping filter . Unlike normal mapping filter global mapping filter spec
18,151
public static FastStr of ( char [ ] ca ) { if ( ca . length == 0 ) return EMPTY_STR ; char [ ] newArray = new char [ ca . length ] ; System . arraycopy ( ca , 0 , newArray , 0 , ca . length ) ; return new FastStr ( ca ) ; }
Construct a FastStr from a char array
18,152
public static FastStr of ( CharSequence cs ) { if ( cs instanceof FastStr ) { return ( FastStr ) cs ; } return of ( cs . toString ( ) ) ; }
Construct a FastStr from a CharSequence
18,153
public static FastStr of ( String s ) { int sz = s . length ( ) ; if ( sz == 0 ) return EMPTY_STR ; char [ ] buf = s . toCharArray ( ) ; return new FastStr ( buf , 0 , sz ) ; }
Construct a FastStr from a String
18,154
public static FastStr of ( StringBuilder sb ) { int sz = sb . length ( ) ; if ( 0 == sz ) return EMPTY_STR ; char [ ] buf = new char [ sz ] ; for ( int i = 0 ; i < sz ; ++ i ) { buf [ i ] = sb . charAt ( i ) ; } return new FastStr ( buf , 0 , sz ) ; }
Construct a FastStr from a StringBuilder
18,155
public static FastStr of ( Iterable < Character > itr ) { StringBuilder sb = new StringBuilder ( ) ; for ( Character c : itr ) { sb . append ( c ) ; } return of ( sb ) ; }
Construct a FastStr instance from an iterable of characters
18,156
public static FastStr of ( Collection < Character > col ) { int sz = col . size ( ) ; if ( 0 == sz ) return EMPTY_STR ; char [ ] buf = new char [ sz ] ; Iterator < Character > itr = col . iterator ( ) ; int i = 0 ; while ( itr . hasNext ( ) ) { buf [ i ++ ] = itr . next ( ) ; } return new FastStr ( buf , 0 , sz ) ; }
Construct a FastStr instance from a collection of characters
18,157
public static FastStr of ( Iterator < Character > itr ) { StringBuilder sb = new StringBuilder ( ) ; while ( itr . hasNext ( ) ) { sb . append ( itr . next ( ) ) ; } return of ( sb ) ; }
Construct a FastStr instance from an iterator of characters
18,158
public static FastStr unsafeOf ( String s ) { int sz = s . length ( ) ; if ( sz == 0 ) return EMPTY_STR ; char [ ] buf = bufOf ( s ) ; return new FastStr ( buf , 0 , sz ) ; }
Construct a FastStr instance from a String instance . The FastStr instance will share the char array buf with the String instance
18,159
@ SuppressWarnings ( "unused" ) public static FastStr unsafeOf ( char [ ] buf ) { E . NPE ( buf ) ; return new FastStr ( buf , 0 , buf . length ) ; }
Construct a FastStr instance from char array without array copying
18,160
public static FastStr unsafeOf ( char [ ] buf , int start , int end ) { E . NPE ( buf ) ; E . illegalArgumentIf ( start < 0 || end > buf . length ) ; if ( end < start ) return EMPTY_STR ; return new FastStr ( buf , start , end ) ; }
Construct a FastStr instance from char array from the start position finished at end position without copying the array . This method might use the array directly instead of copying elements from the array . Thus it is extremely important that the array buf passed in will NOT be updated outside the FastStr instance .
18,161
public StringValueResolver < T > attributes ( Map < String , Object > attributes ) { this . attributes . putAll ( attributes ) ; return this ; }
Set attributes to this resolver
18,162
public static SObject of ( String key , File file ) { if ( file . canRead ( ) && file . isFile ( ) ) { SObject sobj = new FileSObject ( key , file ) ; String fileName = file . getName ( ) ; sobj . setAttribute ( ATTR_FILE_NAME , file . getName ( ) ) ; String fileExtension = S . fileExtension ( fileName ) ; MimeType mimeType = MimeType . findByFileExtension ( fileExtension ) ; String type = null != mimeType ? mimeType . type ( ) : null ; sobj . setAttribute ( ATTR_CONTENT_TYPE , type ) ; sobj . setAttribute ( ATTR_CONTENT_LENGTH , S . string ( file . length ( ) ) ) ; return sobj ; } else { return getInvalidObject ( key , new IOException ( "File is a directory or not readable" ) ) ; } }
Construct an SObject with key and file specified
18,163
public static SObject loadResource ( String url ) { InputStream is = SObject . class . getResourceAsStream ( url ) ; if ( null == is ) { return null ; } String filename = S . afterLast ( url , "/" ) ; if ( S . blank ( filename ) ) { filename = url ; } return of ( randomKey ( ) , is , ATTR_FILE_NAME , filename ) ; }
Load an sobject from classpath by given url path
18,164
public static SObject of ( String key , String content , String ... attrs ) { SObject sobj = of ( key , content ) ; Map < String , String > map = C . Map ( attrs ) ; sobj . setAttributes ( map ) ; return sobj ; }
Construct an sobject with key content and attributes specified in sequence key1 val1 key2 val2 ...
18,165
public static SObject of ( String key , byte [ ] buf , int len ) { if ( len <= 0 ) { return of ( key , new byte [ 0 ] ) ; } if ( len >= buf . length ) { return of ( key , buf ) ; } byte [ ] ba = new byte [ len ] ; System . arraycopy ( buf , 0 , ba , 0 , len ) ; return of ( key , ba ) ; }
Construct an SObject with specified key byte array and number of bytes
18,166
public static String typeOfSuffix ( String fileExtension ) { MimeType mimeType = indexByFileExtension . get ( fileExtension ) ; return null == mimeType ? fileExtension : mimeType . type ; }
Return a content type string corresponding to a given file extension suffix .
18,167
public List < String > preview ( int limit , boolean noHeaderLine ) { E . illegalArgumentIf ( limit < 1 , "limit must be positive integer" ) ; return fetch ( noHeaderLine ? 1 : 0 , limit ) ; }
Returns first limit lines .
18,168
public String fetch ( int lineNumber ) { E . illegalArgumentIf ( lineNumber < 0 , "line number must not be negative number: " + lineNumber ) ; E . illegalArgumentIf ( lineNumber >= lines ( ) , "line number is out of range: " + lineNumber ) ; List < String > list = fetch ( lineNumber , 1 ) ; return list . isEmpty ( ) ? null : list . get ( 0 ) ; }
Returns the line specified by lineNumber .
18,169
public List < String > fetch ( int offset , int limit ) { E . illegalArgumentIf ( offset < 0 , "offset must not be negative number" ) ; E . illegalArgumentIf ( offset >= lines ( ) , "offset is out of range: " + offset ) ; E . illegalArgumentIf ( limit < 1 , "limit must be at least 1" ) ; BufferedReader reader = IO . buffered ( IO . reader ( file ) ) ; try { for ( int i = 0 ; i < offset ; ++ i ) { if ( null == reader . readLine ( ) ) { break ; } } } catch ( IOException e ) { throw E . ioException ( e ) ; } List < String > lines = new ArrayList < > ( ) ; try { for ( int i = 0 ; i < limit ; ++ i ) { String line = reader . readLine ( ) ; if ( null == line ) { break ; } lines . add ( line ) ; } } catch ( IOException e ) { throw E . ioException ( e ) ; } return lines ; }
Returns a number of lines specified by start position offset and limit .
18,170
public static Map < String , Class > buildTypeParamImplLookup ( Class theClass ) { Map < String , Class > lookup = new HashMap < > ( ) ; buildTypeParamImplLookup ( theClass , lookup ) ; return lookup ; }
Build class type variable name and type variable implementation lookup
18,171
public static String encodeUrlSafeBase64 ( String value ) { return new String ( UrlSafeBase64 . encode ( value . getBytes ( Charsets . UTF_8 ) ) ) ; }
Encode a String to base64 using variant URL safe encode scheme
18,172
public static String hexMD5 ( String value ) { try { MessageDigest messageDigest = MessageDigest . getInstance ( "MD5" ) ; messageDigest . reset ( ) ; messageDigest . update ( value . getBytes ( "utf-8" ) ) ; byte [ ] digest = messageDigest . digest ( ) ; return byteToHexString ( digest ) ; } catch ( Exception ex ) { throw new UnexpectedException ( ex ) ; } }
Build an hexadecimal MD5 hash for a String
18,173
public static String hexSHA1 ( String value ) { try { MessageDigest md ; md = MessageDigest . getInstance ( "SHA-1" ) ; md . update ( value . getBytes ( "utf-8" ) ) ; byte [ ] digest = md . digest ( ) ; return byteToHexString ( digest ) ; } catch ( Exception ex ) { throw new UnexpectedException ( ex ) ; } }
Build an hexadecimal SHA1 hash for a String
18,174
public static void NPE ( Object o1 , Object o2 , Object o3 , Object ... objects ) { NPE ( o1 , o2 , o3 ) ; for ( Object o : objects ) { if ( null == o ) { throw new NullPointerException ( ) ; } } }
Throw out NullPointerException if any one of the passed objects is null .
18,175
public static RuntimeException asRuntimeException ( Exception e ) { if ( e instanceof RuntimeException ) { return ( RuntimeException ) e ; } return UnexpectedMethodInvocationException . triage ( e ) ; }
Convert an Exception to RuntimeException
18,176
public Stream < JsonObject > parseJsonLines ( Reader r ) { return StreamSupport . stream ( Spliterators . spliteratorUnknownSize ( jsonLinesIterator ( r ) , Spliterator . ORDERED ) , false ) ; }
Use this to parse jsonlines . org style input . IMPORTANT you have to close the reader yourself with a try ... finally .
18,177
public static org . w3c . dom . Document getW3cDocument ( JsonElement value , String rootName ) { Element root = getElement ( value , rootName ) ; try { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; DOMImplementation impl = builder . getDOMImplementation ( ) ; return DOMConverter . convert ( new Document ( root ) , impl ) ; } catch ( ParserConfigurationException e ) { throw new IllegalStateException ( e ) ; } }
Convert any JsonElement into an w3c DOM tree .
18,178
public JsonBuilder put ( String key , String s ) { object . put ( key , primitive ( s ) ) ; return this ; }
Add a string value to the object .
18,179
public JsonBuilder put ( String key , boolean b ) { object . put ( key , primitive ( b ) ) ; return this ; }
Add a boolean value to the object .
18,180
public JsonBuilder put ( String key , Number n ) { object . put ( key , primitive ( n ) ) ; return this ; }
Add a number to the object .
18,181
public JsonBuilder putArray ( String key , String ... values ) { JsonArray jjArray = new JsonArray ( ) ; for ( String string : values ) { jjArray . add ( primitive ( string ) ) ; } object . put ( key , jjArray ) ; return this ; }
Add a JsonArray to the object with the string values added .
18,182
public static Entry < String , JsonElement > field ( String key , JsonElement value ) { Entry < String , JsonElement > entry = new Entry < String , JsonElement > ( ) { public String getKey ( ) { return key ; } public JsonElement getValue ( ) { return value ; } public JsonElement setValue ( JsonElement value ) { throw new UnsupportedOperationException ( "entries are immutable" ) ; } } ; return entry ; }
Create a new field that can be added to a JsonObject .
18,183
public static Entry < String , JsonElement > field ( String key , Object value ) { return field ( key , fromObject ( value ) ) ; }
Create a new field with the key and the result of fromObject on the value .
18,184
public JsonElement get ( String label ) { int i = 0 ; try { for ( JsonElement e : this ) { if ( e . isPrimitive ( ) && e . asPrimitive ( ) . asString ( ) . equals ( label ) ) { return e ; } else if ( ( e . isObject ( ) || e . isArray ( ) ) && Integer . valueOf ( label ) . equals ( i ) ) { return e ; } i ++ ; } } catch ( NumberFormatException e ) { return null ; } return null ; }
Convenient method providing a few alternate ways of extracting elements from a JsonArray .
18,185
public boolean replace ( JsonElement e1 , JsonElement e2 ) { int index = indexOf ( e1 ) ; if ( index >= 0 ) { set ( index , e2 ) ; return true ; } else { return false ; } }
Replaces the first matching element .
18,186
public boolean replace ( Object e1 , Object e2 ) { return replace ( fromObject ( e1 ) , fromObject ( e2 ) ) ; }
Replaces the element .
18,187
public boolean replaceObject ( JsonObject e1 , JsonObject e2 , String ... path ) { JsonElement compareElement = e1 . get ( path ) ; if ( compareElement == null ) { throw new IllegalArgumentException ( "specified path may not be null in object " + StringUtils . join ( path ) ) ; } int i = 0 ; for ( JsonElement e : this ) { if ( e . isObject ( ) ) { JsonElement fieldValue = e . asObject ( ) . get ( path ) ; if ( compareElement . equals ( fieldValue ) ) { set ( i , e2 ) ; return true ; } } i ++ ; } return false ; }
Convenient replace method that allows you to replace an object based on field equality for a specified field . Useful if you have an id field in your objects . Note the array may contain non objects as well or objects without the specified field . Those elements won t be replaced of course .
18,188
public Iterable < JsonObject > objects ( ) { final JsonArray parent = this ; return ( ) -> { final Iterator < JsonElement > iterator = parent . iterator ( ) ; return new Iterator < JsonObject > ( ) { public boolean hasNext ( ) { return iterator . hasNext ( ) ; } public JsonObject next ( ) { return iterator . next ( ) . asObject ( ) ; } public void remove ( ) { iterator . remove ( ) ; } } ; } ; }
Convenience method to prevent casting JsonElement to JsonObject when iterating in the common case that you have an array of JsonObjects .
18,189
public Iterable < JsonArray > arrays ( ) { final JsonArray parent = this ; return ( ) -> { final Iterator < JsonElement > iterator = parent . iterator ( ) ; return new Iterator < JsonArray > ( ) { public boolean hasNext ( ) { return iterator . hasNext ( ) ; } public JsonArray next ( ) { return iterator . next ( ) . asArray ( ) ; } public void remove ( ) { iterator . remove ( ) ; } } ; } ; }
Convenience method to prevent casting JsonElement to JsonArray when iterating in the common case that you have an array of JsonArrays .
18,190
public Iterable < String > strings ( ) { final JsonArray parent = this ; return ( ) -> { final Iterator < JsonElement > iterator = parent . iterator ( ) ; return new Iterator < String > ( ) { public boolean hasNext ( ) { return iterator . hasNext ( ) ; } public String next ( ) { return iterator . next ( ) . asString ( ) ; } public void remove ( ) { iterator . remove ( ) ; } } ; } ; }
Convenience method to prevent casting JsonElement to String when iterating in the common case that you have an array of strings .
18,191
public Iterable < Double > doubles ( ) { final JsonArray parent = this ; return ( ) -> { final Iterator < JsonElement > iterator = parent . iterator ( ) ; return new Iterator < Double > ( ) { public boolean hasNext ( ) { return iterator . hasNext ( ) ; } public Double next ( ) { return iterator . next ( ) . asDouble ( ) ; } public void remove ( ) { iterator . remove ( ) ; } } ; } ; }
Convenience method to prevent casting JsonElement to Double when iterating in the common case that you have an array of doubles .
18,192
public void add ( final String ... elements ) { for ( String s : elements ) { JsonPrimitive primitive = primitive ( s ) ; if ( ! contains ( primitive ) ) { add ( primitive ) ; } } }
Variant of add that adds multiple strings .
18,193
public boolean add ( final String s ) { JsonPrimitive primitive = primitive ( s ) ; if ( ! contains ( primitive ) ) { return add ( primitive ) ; } else { return false ; } }
Variant of add that takes a string instead of a JsonElement . The inherited add only supports JsonElement .
18,194
public JsonSet withIdStrategy ( IdStrategy strategy ) { this . strategy = strategy ; if ( size ( ) > 0 ) { JsonSet seen = new JsonSet ( ) . withIdStrategy ( strategy ) ; Iterator < JsonElement > iterator = this . iterator ( ) ; while ( iterator . hasNext ( ) ) { JsonElement e = iterator . next ( ) ; if ( seen . contains ( e ) ) { iterator . remove ( ) ; } else { seen . add ( e ) ; } } } return this ; }
Changes the strategy on the current set .
18,195
public static WrappedRequest wrap ( final HttpServletRequest request ) throws IOException { if ( request instanceof WrappedRequest ) { return ( WrappedRequest ) request ; } return new WrappedRequest ( request ) ; }
Factory method used to create a WrappedRequest wrapping a HttpServletRequest .
18,196
public boolean accept ( Class < ? > aClass ) { try { return ( testKryo . getRegistration ( aClass ) != null ) ; } catch ( IllegalArgumentException e ) { return false ; } }
Uses the initialized Kryo instance from the JobConf to test if Kryo will accept the class
18,197
public static String getNameSpaceName ( String pageTitle ) { Matcher matcher = namespacePattern . matcher ( pageTitle ) ; if ( matcher . find ( ) ) { return matcher . group ( 1 ) ; } return null ; }
get the name space name
18,198
@ XmlElementWrapper ( name = "revisions" ) @ XmlElement ( name = "rev" , type = Rev . class ) public List < Rev > getRevisions ( ) { return revisions ; }
Gets the value of the revisions property .
18,199
@ XmlElementWrapper ( name = "images" ) @ XmlElement ( name = "im" , type = Im . class ) public List < Im > getImages ( ) { return images ; }
Gets the value of the images property .