idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
28,400
private Set < String > getOcspUrls ( Certificate bcCert ) { TBSCertificate bcTbsCert = bcCert . getTBSCertificate ( ) ; Extensions bcExts = bcTbsCert . getExtensions ( ) ; if ( bcExts == null ) { throw new RuntimeException ( "Failed to get Tbs Certificate." ) ; } Set < String > ocsp = new HashSet < > ( ) ; for ( Enumer...
Gets OCSP URLs associated with the certificate .
28,401
private static boolean isValidityRange ( Date currentTime , Date thisUpdate , Date nextUpdate ) { long tolerableValidity = calculateTolerableVadility ( thisUpdate , nextUpdate ) ; return thisUpdate . getTime ( ) - MAX_CLOCK_SKEW_IN_MILLISECONDS <= currentTime . getTime ( ) && currentTime . getTime ( ) <= nextUpdate . g...
Checks the validity
28,402
private void processKeyUpdateDirective ( String issuer , String ssd ) { try { SignedJWT jwt_signed = SignedJWT . parse ( ssd ) ; String jwt_issuer = ( String ) jwt_signed . getHeader ( ) . getCustomParam ( "ssd_iss" ) ; String ssd_pubKey ; if ( ! jwt_issuer . equals ( issuer ) ) { LOGGER . debug ( "Issuer mismatch. Inv...
SSD Processing Code
28,403
private String ocspResponseToB64 ( OCSPResp ocspResp ) { if ( ocspResp == null ) { return null ; } try { return Base64 . encodeBase64String ( ocspResp . getEncoded ( ) ) ; } catch ( Throwable ex ) { LOGGER . debug ( "Could not convert OCSP Response to Base64" ) ; return null ; } }
OCSP Response Utils
28,404
private void scheduleHeartbeat ( ) { long elapsedSecsSinceLastHeartBeat = System . currentTimeMillis ( ) / 1000 - lastHeartbeatStartTimeInSecs ; long initialDelay = Math . max ( heartBeatIntervalInSecs - elapsedSecsSinceLastHeartBeat , 0 ) ; LOGGER . debug ( "schedule heartbeat task with initial delay of {} seconds" , ...
Schedule the next heartbeat
28,405
public SnowflakeStorageClient createClient ( StageInfo stage , int parallel , RemoteStoreFileEncryptionMaterial encMat ) throws SnowflakeSQLException { logger . debug ( "createClient client type={}" , stage . getStageType ( ) . name ( ) ) ; switch ( stage . getStageType ( ) ) { case S3 : return createS3Client ( stage ....
Creates a storage client based on the value of stageLocationType
28,406
private SnowflakeS3Client createS3Client ( Map stageCredentials , int parallel , RemoteStoreFileEncryptionMaterial encMat , String stageRegion ) throws SnowflakeSQLException { final int S3_TRANSFER_MAX_RETRIES = 3 ; logger . debug ( "createS3Client encryption={}" , ( encMat == null ? "no" : "yes" ) ) ; SnowflakeS3Clien...
Creates a SnowflakeS3ClientObject which encapsulates the Amazon S3 client
28,407
public StorageObjectMetadata createStorageMetadataObj ( StageInfo . StageType stageType ) { switch ( stageType ) { case S3 : return new S3ObjectMetadata ( ) ; case AZURE : return new AzureObjectMetadata ( ) ; default : throw new IllegalArgumentException ( "Unsupported stage type specified: " + stageType . name ( ) ) ; ...
Creates a storage provider specific metadata object accessible via the platform independent interface
28,408
private SnowflakeAzureClient createAzureClient ( StageInfo stage , RemoteStoreFileEncryptionMaterial encMat ) throws SnowflakeSQLException { logger . debug ( "createAzureClient encryption={}" , ( encMat == null ? "no" : "yes" ) ) ; SnowflakeAzureClient azureClient ; try { azureClient = SnowflakeAzureClient . createSnow...
Creates a SnowflakeAzureClientObject which encapsulates the Azure Storage client
28,409
public synchronized static BindUploader newInstance ( SFSession session , String stageDir ) throws BindException { try { Path bindDir = Files . createTempDirectory ( PREFIX ) ; return new BindUploader ( session , stageDir , bindDir ) ; } catch ( IOException ex ) { throw new BindException ( String . format ( "Failed to ...
Create a new BindUploader which will upload to the given stage path Ensure temporary directory for file writing exists
28,410
public void upload ( Map < String , ParameterBindingDTO > bindValues ) throws BindException { if ( ! closed ) { serializeBinds ( bindValues ) ; putBinds ( ) ; } }
Upload the bindValues to stage
28,411
private void serializeBinds ( Map < String , ParameterBindingDTO > bindValues ) throws BindException { List < ColumnTypeDataPair > columns = getColumnValues ( bindValues ) ; List < String [ ] > rows = buildRows ( columns ) ; writeRowsToCSV ( rows ) ; }
Save the binds to disk
28,412
private List < ColumnTypeDataPair > getColumnValues ( Map < String , ParameterBindingDTO > bindValues ) throws BindException { List < ColumnTypeDataPair > columns = new ArrayList < > ( bindValues . size ( ) ) ; for ( int i = 1 ; i <= bindValues . size ( ) ; i ++ ) { String key = Integer . toString ( i ) ; if ( ! bindVa...
Convert bind map to a list of values for each column Perform necessary type casts and invariant checks
28,413
private List < String [ ] > buildRows ( List < ColumnTypeDataPair > columns ) throws BindException { List < String [ ] > rows = new ArrayList < > ( ) ; int numColumns = columns . size ( ) ; if ( columns . get ( 0 ) . data . isEmpty ( ) ) { throw new BindException ( "No binds found in first column" , BindException . Typ...
Transpose a list of columns and their values to a list of rows
28,414
private void writeRowsToCSV ( List < String [ ] > rows ) throws BindException { int numBytes ; int rowNum = 0 ; int fileCount = 0 ; while ( rowNum < rows . size ( ) ) { File file = getFile ( ++ fileCount ) ; try ( OutputStream out = openFile ( file ) ) { numBytes = 0 ; while ( numBytes < fileSize && rowNum < rows . siz...
Write the list of rows to compressed CSV files in the temporary directory
28,415
private OutputStream openFile ( File file ) throws BindException { try { return new GZIPOutputStream ( new FileOutputStream ( file ) ) ; } catch ( IOException ex ) { throw new BindException ( String . format ( "Failed to create output file %s: %s" , file . toString ( ) , ex . getMessage ( ) ) , BindException . Type . S...
Create a new output stream for the given file
28,416
private byte [ ] createCSVRecord ( String [ ] data ) { StringBuilder sb = new StringBuilder ( 1024 ) ; for ( int i = 0 ; i < data . length ; ++ i ) { if ( i > 0 ) { sb . append ( ',' ) ; } sb . append ( SnowflakeType . escapeForCSV ( data [ i ] ) ) ; } sb . append ( '\n' ) ; return sb . toString ( ) . getBytes ( UTF_8 ...
Serialize row to a csv Duplicated from StreamLoader class
28,417
private String getPutStmt ( String bindDir , String stagePath ) { return String . format ( PUT_STMT , bindDir , File . separator , stagePath ) . replaceAll ( "\\\\" , "\\\\\\\\" ) ; }
Build PUT statement string . Handle filesystem differences and escaping backslashes .
28,418
private void putBinds ( ) throws BindException { createStageIfNeeded ( ) ; String putStatement = getPutStmt ( bindDir . toString ( ) , stagePath ) ; for ( int i = 0 ; i < PUT_RETRY_COUNT ; i ++ ) { try { SFStatement statement = new SFStatement ( session ) ; SFBaseResultSet putResult = statement . execute ( putStatement...
Upload binds from local file to stage
28,419
private void createStageIfNeeded ( ) throws BindException { if ( session . getArrayBindStage ( ) != null ) { return ; } synchronized ( session ) { if ( session . getArrayBindStage ( ) == null ) { try { SFStatement statement = new SFStatement ( session ) ; statement . execute ( CREATE_STAGE_STMT , null , null ) ; sessio...
Check whether the session s temporary stage has been created and create it if not .
28,420
public static int arrayBindValueCount ( Map < String , ParameterBindingDTO > bindValues ) { if ( ! isArrayBind ( bindValues ) ) { return 0 ; } else { ParameterBindingDTO bindSample = bindValues . values ( ) . iterator ( ) . next ( ) ; List < String > bindSampleValues = ( List < String > ) bindSample . getValue ( ) ; re...
Compute the number of array bind values in the given bind map
28,421
public static boolean isArrayBind ( Map < String , ParameterBindingDTO > bindValues ) { if ( bindValues == null || bindValues . size ( ) == 0 ) { return false ; } ParameterBindingDTO bindSample = bindValues . values ( ) . iterator ( ) . next ( ) ; return bindSample . getValue ( ) instanceof List ; }
Return whether the bind map uses array binds
28,422
public static StorageObjectSummary createFromS3ObjectSummary ( S3ObjectSummary objSummary ) { return new StorageObjectSummary ( objSummary . getBucketName ( ) , objSummary . getKey ( ) , objSummary . getETag ( ) , objSummary . getSize ( ) ) ; }
Contructs a StorageObjectSummary object from the S3 equivalent S3ObjectSummary
28,423
public static StorageObjectSummary createFromAzureListBlobItem ( ListBlobItem listBlobItem ) throws StorageProviderException { String location , key , md5 ; long size ; try { location = listBlobItem . getContainer ( ) . getName ( ) ; CloudBlob cloudBlob = ( CloudBlob ) listBlobItem ; key = cloudBlob . getName ( ) ; Blo...
Contructs a StorageObjectSummary object from Azure BLOB properties Using factory methods to create these objects since Azure can throw while retrieving the BLOB properties
28,424
private boolean isSnowflakeAuthenticator ( ) { String authenticator = ( String ) connectionPropertiesMap . get ( SFSessionProperty . AUTHENTICATOR ) ; PrivateKey privateKey = ( PrivateKey ) connectionPropertiesMap . get ( SFSessionProperty . PRIVATE_KEY ) ; return ( authenticator == null && privateKey == null ) || Clie...
If authenticator is null and private key is specified jdbc will assume key pair authentication
28,425
boolean isExternalbrowserAuthenticator ( ) { String authenticator = ( String ) connectionPropertiesMap . get ( SFSessionProperty . AUTHENTICATOR ) ; return ClientAuthnDTO . AuthenticatorType . EXTERNALBROWSER . name ( ) . equalsIgnoreCase ( authenticator ) ; }
Returns true If authenticator is EXTERNALBROWSER .
28,426
synchronized void renewSession ( String prevSessionToken ) throws SFException , SnowflakeSQLException { if ( sessionToken != null && ! sessionToken . equals ( prevSessionToken ) ) { logger . debug ( "not renew session because session token has not been updated." ) ; return ; } SessionUtil . LoginInput loginInput = new ...
A helper function to call global service and renew session .
28,427
protected void startHeartbeatForThisSession ( ) { if ( enableHeartbeat && ! Strings . isNullOrEmpty ( masterToken ) ) { logger . debug ( "start heartbeat, master token validity: " + masterTokenValidityInSeconds ) ; HeartbeatBackground . getInstance ( ) . addSession ( this , masterTokenValidityInSeconds , this . heartbe...
Start heartbeat for this session
28,428
protected void stopHeartbeatForThisSession ( ) { if ( enableHeartbeat && ! Strings . isNullOrEmpty ( masterToken ) ) { logger . debug ( "stop heartbeat" ) ; HeartbeatBackground . getInstance ( ) . removeSession ( this ) ; } else { logger . debug ( "heartbeat not enabled for the session" ) ; } }
Stop heartbeat for this session
28,429
protected void heartbeat ( ) throws SFException , SQLException { logger . debug ( " public void heartbeat()" ) ; if ( isClosed ) { return ; } HttpPost postRequest = null ; String requestId = UUID . randomUUID ( ) . toString ( ) ; boolean retry = false ; do { try { URIBuilder uriBuilder ; uriBuilder = new URIBuilder ( (...
Send heartbeat for the session
28,430
void setCurrentObjects ( SessionUtil . LoginInput loginInput , SessionUtil . LoginOutput loginOutput ) { this . sessionToken = loginOutput . sessionToken ; runInternalCommand ( "USE ROLE IDENTIFIER(?)" , loginInput . getRole ( ) ) ; runInternalCommand ( "USE WAREHOUSE IDENTIFIER(?)" , loginInput . getWarehouse ( ) ) ; ...
Sets the current objects if the session is not up to date . It can happen if the session is created by the id token which doesn t carry the current objects .
28,431
private void executeImmediate ( String stmtText ) throws SQLException { try ( final Statement statement = this . createStatement ( ) ) { statement . execute ( stmtText ) ; } }
Execute a statement where the result isn t needed and the statement is closed before this method returns
28,432
public Statement createStatement ( ) throws SQLException { raiseSQLExceptionIfConnectionIsClosed ( ) ; Statement stmt = createStatement ( ResultSet . TYPE_FORWARD_ONLY , ResultSet . CONCUR_READ_ONLY ) ; openStatements . add ( stmt ) ; return stmt ; }
Create a statement
28,433
public void setTransactionIsolation ( int level ) throws SQLException { logger . debug ( "void setTransactionIsolation(int level), level = {}" , level ) ; raiseSQLExceptionIfConnectionIsClosed ( ) ; if ( level == Connection . TRANSACTION_NONE || level == Connection . TRANSACTION_READ_COMMITTED ) { this . transactionIso...
Sets the transaction isolation level .
28,434
public InputStream downloadStream ( String stageName , String sourceFileName , boolean decompress ) throws SQLException { logger . debug ( "download data to stream: stageName={}" + ", sourceFileName={}" , stageName , sourceFileName ) ; if ( Strings . isNullOrEmpty ( stageName ) ) { throw new SnowflakeSQLException ( Sql...
Download file from the given stage and return an input stream
28,435
public static InputStream decryptStream ( InputStream inputStream , String keyBase64 , String ivBase64 , RemoteStoreFileEncryptionMaterial encMat ) throws NoSuchPaddingException , NoSuchAlgorithmException , InvalidKeyException , BadPaddingException , IllegalBlockSizeException , InvalidAlgorithmParameterException { byte...
Decrypt a InputStream
28,436
synchronized void startFlusher ( ) { flusher = Executors . newScheduledThreadPool ( 1 , new ThreadFactory ( ) { public Thread newThread ( Runnable r ) { Thread t = Executors . defaultThreadFactory ( ) . newThread ( r ) ; t . setDaemon ( true ) ; return t ; } } ) ; flusher . scheduleWithFixedDelay ( new QueueFlusher ( )...
Creates and runs a new QueueFlusher thread
28,437
public void dumpLogBuffer ( String identifier ) { final ArrayList < LogRecord > logBufferCopy ; final PrintWriter logDumper ; final OutputStream outStream ; Formatter formatter = this . getFormatter ( ) ; boolean disableCompression = System . getProperty ( DISABLE_DUMP_COMPR_PROP ) != null ; if ( identifier == null ) {...
Dumps the contents of the in - memory log buffer to disk and clears the buffer .
28,438
protected void cleanupSfDumps ( boolean deleteOldest ) { int maxDumpFiles = System . getProperty ( MAX_NUM_DUMP_FILES_PROP ) != null ? Integer . valueOf ( System . getProperty ( MAX_NUM_DUMP_FILES_PROP ) ) : DEFAULT_MAX_DUMP_FILES ; int maxDumpDirSizeMB = System . getProperty ( MAX_SIZE_DUMPS_MB_PROP ) != null ? Intege...
Function to remove old Snowflake Dump files to make room for new ones .
28,439
private synchronized boolean needsToThrottle ( String signature ) { AtomicInteger sigCount ; if ( throttledIncidents . containsKey ( signature ) ) { if ( throttledIncidents . get ( signature ) . plusHours ( THROTTLE_DURATION_HRS ) . compareTo ( DateTime . now ( ) ) <= 0 ) { throttledIncidents . remove ( signature ) ; i...
Checks to see if the reporting of an incident should be throttled due to the number of times the signature has been seen in the last hour
28,440
public void start ( ) { LOGGER . debug ( "Start Loading" ) ; validateParameters ( ) ; if ( _op == null ) { this . abort ( new ConnectionError ( "Loader started with no operation" ) ) ; return ; } initDateFormats ( ) ; initQueues ( ) ; if ( _is_first_start_call ) { try { if ( _startTransaction ) { LOGGER . debug ( "Begi...
Starts the loader
28,441
private void flushQueues ( ) { LOGGER . debug ( "Flush Queues" ) ; try { _queueData . put ( new byte [ 0 ] ) ; _thread . join ( 10000 ) ; if ( _thread . isAlive ( ) ) { _thread . interrupt ( ) ; } } catch ( Exception ex ) { String msg = "Failed to join StreamLoader queue: " + ex . getMessage ( ) ; LOGGER . error ( msg ...
Flushes data by joining PUT and PROCESS queues
28,442
public void resetOperation ( Operation op ) { LOGGER . debug ( "Reset Loader" ) ; if ( op . equals ( _op ) ) { return ; } LOGGER . debug ( "Operation is changing from {} to {}" , _op , op ) ; _op = op ; if ( _stage != null ) { try { queuePut ( _stage ) ; } catch ( InterruptedException ex ) { LOGGER . error ( _stage . g...
If operation changes existing stage needs to be scheduled for processing .
28,443
void overrideCacheFile ( File newCacheFile ) { this . cacheFile = newCacheFile ; this . cacheDir = newCacheFile . getParentFile ( ) ; this . baseCacheFileName = newCacheFile . getName ( ) ; }
Override the cache file .
28,444
JsonNode readCacheFile ( ) { if ( cacheFile == null || ! this . checkCacheLockFile ( ) ) { return null ; } try { if ( ! cacheFile . exists ( ) ) { LOGGER . debug ( "Cache file doesn't exists. File: {}" , cacheFile ) ; return null ; } try ( Reader reader = new InputStreamReader ( new FileInputStream ( cacheFile ) , DEFA...
Reads the cache file .
28,445
private boolean tryLockCacheFile ( ) { int cnt = 0 ; boolean locked = false ; while ( cnt < 100 && ! ( locked = lockCacheFile ( ) ) ) { try { Thread . sleep ( 100 ) ; } catch ( InterruptedException ex ) { } ++ cnt ; } if ( ! locked ) { LOGGER . debug ( "Failed to lock the cache file." ) ; } return locked ; }
Tries to lock the cache file
28,446
private void verifyLocalFilePath ( String localFilePathFromGS ) throws SnowflakeSQLException { if ( command == null ) { logger . error ( "null command" ) ; return ; } if ( command . indexOf ( FILE_PROTOCOL ) < 0 ) { logger . error ( "file:// prefix not found in command: {}" , command ) ; return ; } int localFilePathBeg...
A helper method to verify if the local file path from GS matches what s parsed locally . This is for security purpose as documented in SNOW - 15153 .
28,447
private void uploadStream ( ) throws SnowflakeSQLException { try { threadExecutor = SnowflakeUtil . createDefaultExecutorService ( "sf-stream-upload-worker-" , 1 ) ; RemoteStoreFileEncryptionMaterial encMat = encryptionMaterial . get ( 0 ) ; if ( commandType == CommandType . UPLOAD ) { threadExecutor . submit ( getUplo...
Helper to upload data from a stream
28,448
InputStream downloadStream ( String fileName ) throws SnowflakeSQLException { if ( stageInfo . getStageType ( ) == StageInfo . StageType . LOCAL_FS ) { logger . error ( "downloadStream function doesn't support local file system" ) ; throw new SnowflakeSQLException ( SqlState . INTERNAL_ERROR , ErrorCode . INTERNAL_ERRO...
Download a file from remote and return an input stream
28,449
private void downloadFiles ( ) throws SnowflakeSQLException { try { threadExecutor = SnowflakeUtil . createDefaultExecutorService ( "sf-file-download-worker-" , 1 ) ; for ( String srcFile : sourceFiles ) { FileMetadata fileMetadata = fileMetadataMap . get ( srcFile ) ; if ( fileMetadata . resultStatus != ResultStatus ....
Helper to download files from remote
28,450
private void uploadFiles ( Set < String > fileList , int parallel ) throws SnowflakeSQLException { try { threadExecutor = SnowflakeUtil . createDefaultExecutorService ( "sf-file-upload-worker-" , parallel ) ; for ( String srcFile : fileList ) { FileMetadata fileMetadata = fileMetadataMap . get ( srcFile ) ; if ( fileMe...
This method create a thread pool based on requested number of threads and upload the files using the thread pool .
28,451
static public Set < String > expandFileNames ( String [ ] filePathList ) throws SnowflakeSQLException { Set < String > result = new HashSet < String > ( ) ; Map < String , List < String > > locationToFilePatterns ; locationToFilePatterns = new HashMap < String , List < String > > ( ) ; String cwd = System . getProperty...
process a list of file paths separated by and expand the wildcards if any to generate the list of paths for all files matched by the wildcards
28,452
private FileCompressionType mimeTypeToCompressionType ( String mimeTypeStr ) throws MimeTypeParseException { MimeType mimeType = null ; if ( mimeTypeStr != null ) { mimeType = new MimeType ( mimeTypeStr ) ; } if ( mimeType != null && mimeType . getSubType ( ) != null ) { return FileCompressionType . lookupByMimeSubType...
Derive compression type from mime type
28,453
private String getMimeTypeFromFileExtension ( String srcFile ) { String srcFileLowCase = srcFile . toLowerCase ( ) ; for ( FileCompressionType compressionType : FileCompressionType . values ( ) ) { if ( srcFileLowCase . endsWith ( compressionType . fileExtension ) ) { return compressionType . mimeType + "/" + compressi...
Derive mime type from file extension
28,454
static public remoteLocation extractLocationAndPath ( String stageLocationPath ) { String location = stageLocationPath ; String path = "" ; if ( stageLocationPath . contains ( "/" ) ) { location = stageLocationPath . substring ( 0 , stageLocationPath . indexOf ( "/" ) ) ; path = stageLocationPath . substring ( stageLoc...
A small helper for extracting location name and path from full location path
28,455
public List < SnowflakeColumnMetadata > describeColumns ( ) throws Exception { return SnowflakeUtil . describeFixedViewColumns ( commandType == CommandType . UPLOAD ? ( showEncryptionParameter ? UploadCommandEncryptionFacade . class : UploadCommandFacade . class ) : ( showEncryptionParameter ? DownloadCommandEncryption...
Describe the metadata of a fixed view .
28,456
private void populateStatusRows ( ) { for ( Map . Entry < String , FileMetadata > entry : fileMetadataMap . entrySet ( ) ) { FileMetadata fileMetadata = entry . getValue ( ) ; if ( commandType == CommandType . UPLOAD ) { statusRows . add ( showEncryptionParameter ? new UploadCommandEncryptionFacade ( fileMetadata . src...
Generate status rows for each file
28,457
public void flush ( ) { ObjectMapper mapper = ObjectMapperFactory . getObjectMapper ( ) ; String dtoDump ; URI incidentURI ; try { dtoDump = mapper . writeValueAsString ( new IncidentV2DTO ( this ) ) ; } catch ( JsonProcessingException ex ) { logger . error ( "Incident registration failed, could not map " + "incident r...
Sends incident to GS to log
28,458
private static String [ ] decideCipherSuites ( ) { String sysCipherSuites = System . getProperty ( "https.cipherSuites" ) ; String [ ] cipherSuites = sysCipherSuites != null ? sysCipherSuites . split ( "," ) : ( ( SSLServerSocketFactory ) SSLServerSocketFactory . getDefault ( ) ) . getDefaultCipherSuites ( ) ; if ( log...
Decide cipher suites that will be passed into the SSLConnectionSocketFactory
28,459
public static Telemetry createTelemetry ( Connection conn , int flushSize ) { try { return createTelemetry ( conn . unwrap ( SnowflakeConnectionV1 . class ) . getSfSession ( ) , flushSize ) ; } catch ( SQLException ex ) { logger . debug ( "input connection is not a SnowflakeConnection" ) ; return null ; } }
Initialize the telemetry connector
28,460
public void addLogToBatch ( TelemetryData log ) throws IOException { if ( isClosed ) { throw new IOException ( "Telemetry connector is closed" ) ; } if ( ! isTelemetryEnabled ( ) ) { return ; } synchronized ( locker ) { this . logBatch . add ( log ) ; } if ( this . logBatch . size ( ) >= this . forceFlushSize ) { this ...
Add log to batch to be submitted to telemetry . Send batch if forceFlushSize reached
28,461
public void tryAddLogToBatch ( TelemetryData log ) { try { addLogToBatch ( log ) ; } catch ( IOException ex ) { logger . debug ( "Exception encountered while sending metrics to telemetry endpoint." , ex ) ; } }
Attempt to add log to batch and suppress exceptions thrown in case of failure
28,462
public void close ( ) throws IOException { if ( isClosed ) { throw new IOException ( "Telemetry connector is closed" ) ; } try { this . sendBatch ( ) ; } catch ( IOException e ) { logger . error ( "Send logs failed on closing" , e ) ; } finally { this . isClosed = true ; } }
Close telemetry connector and send any unsubmitted logs
28,463
public boolean sendBatch ( ) throws IOException { if ( isClosed ) { throw new IOException ( "Telemetry connector is closed" ) ; } if ( ! isTelemetryEnabled ( ) ) { return false ; } LinkedList < TelemetryData > tmpList ; synchronized ( locker ) { tmpList = this . logBatch ; this . logBatch = new LinkedList < > ( ) ; } i...
Send all cached logs to server
28,464
static ObjectNode logsToJson ( LinkedList < TelemetryData > telemetryData ) { ObjectNode node = mapper . createObjectNode ( ) ; ArrayNode logs = mapper . createArrayNode ( ) ; for ( TelemetryData data : telemetryData ) { logs . add ( data . toJson ( ) ) ; } node . set ( "logs" , logs ) ; return node ; }
convert a list of log to a JSON object
28,465
public ResultSet executeQuery ( String sql ) throws SQLException { raiseSQLExceptionIfStatementIsClosed ( ) ; return executeQueryInternal ( sql , null ) ; }
Execute SQL query
28,466
ResultSet executeQueryInternal ( String sql , Map < String , ParameterBindingDTO > parameterBindings ) throws SQLException { SFBaseResultSet sfResultSet ; try { sfResultSet = sfStatement . execute ( sql , parameterBindings , SFStatement . CallingMethod . EXECUTE_QUERY ) ; sfResultSet . setSession ( this . connection . ...
Internal method for executing a query with bindings accepted .
28,467
void setParameter ( String name , Object value ) throws Exception { logger . debug ( "public void setParameter" ) ; try { if ( this . sfStatement != null ) { this . sfStatement . addProperty ( name , value ) ; } } catch ( SFException ex ) { throw new SnowflakeSQLException ( ex ) ; } }
Sets a parameter at the statement level . Used for internal testing .
28,468
private static ThreadPoolExecutor createChunkDownloaderExecutorService ( final String threadNamePrefix , final int parallel ) { ThreadFactory threadFactory = new ThreadFactory ( ) { private int threadCount = 1 ; public Thread newThread ( final Runnable r ) { final Thread thread = new Thread ( r ) ; thread . setName ( t...
Create a pool of downloader threads .
28,469
private void startNextDownloaders ( ) throws SnowflakeSQLException { long waitingTime = BASE_WAITING_MS ; while ( nextChunkToDownload - nextChunkToConsume < prefetchSlots && nextChunkToDownload < chunks . size ( ) ) { final SnowflakeResultChunk nextChunk = chunks . get ( nextChunkToDownload ) ; final long neededChunkMe...
Submit download chunk tasks to executor . Number depends on thread and memory limit
28,470
public void releaseAllChunkMemoryUsage ( ) { if ( chunks == null || chunks . size ( ) == 0 ) { return ; } for ( int i = 0 ; i < chunks . size ( ) ; i ++ ) { releaseCurrentMemoryUsage ( i , chunks . get ( i ) . computeNeededChunkMemory ( ) ) ; } }
release all existing chunk memory usage before close
28,471
private void logOutOfMemoryError ( ) { logger . error ( "Dump some crucial information below:\n" + "Total milliseconds waiting for chunks: {},\n" + "Total memory used: {}, Max heap size: {}, total download time: {} millisec,\n" + "total parsing time: {} milliseconds, total chunks: {},\n" + "currentMemoryUsage in Byte: ...
log out of memory error and provide the suggestion to avoid this error
28,472
public Metrics terminate ( ) { if ( ! terminated ) { logger . debug ( "Total milliseconds waiting for chunks: {}, " + "Total memory used: {}, total download time: {} millisec, " + "total parsing time: {} milliseconds, total chunks: {}" , numberMillisWaitingForChunks , Runtime . getRuntime ( ) . totalMemory ( ) , totalM...
terminate the downloader
28,473
public static String maskAWSSecret ( String sql ) { List < SecretDetector . SecretRange > secretRanges = SecretDetector . getAWSSecretPos ( sql ) ; for ( SecretDetector . SecretRange secretRange : secretRanges ) { sql = maskText ( sql , secretRange . beginPos , secretRange . endPos ) ; } return sql ; }
mask AWS secret in the input string
28,474
private void sanityCheckQuery ( String sql ) throws SQLException { if ( sql == null || sql . isEmpty ( ) ) { throw new SnowflakeSQLException ( SqlState . SQL_STATEMENT_NOT_YET_COMPLETE , ErrorCode . INVALID_SQL . getMessageCode ( ) , sql ) ; } }
Sanity check query text
28,475
private SFBaseResultSet executeQuery ( String sql , Map < String , ParameterBindingDTO > parametersBinding , boolean describeOnly , CallingMethod caller ) throws SQLException , SFException { sanityCheckQuery ( sql ) ; String trimmedSql = sql . trim ( ) ; if ( isFileTransfer ( trimmedSql ) ) { logger . debug ( "Executin...
Execute SQL query with an option for describe only
28,476
public SFStatementMetaData describe ( String sql ) throws SFException , SQLException { SFBaseResultSet baseResultSet = executeQuery ( sql , null , true , null ) ; describeJobUUID = baseResultSet . getQueryId ( ) ; return new SFStatementMetaData ( baseResultSet . getMetaData ( ) , baseResultSet . getStatementType ( ) , ...
Describe a statement
28,477
private void setTimeBomb ( ScheduledExecutorService executor ) { class TimeBombTask implements Callable < Void > { private final SFStatement statement ; private TimeBombTask ( SFStatement statement ) { this . statement = statement ; } public Void call ( ) throws SQLException { try { statement . cancel ( ) ; } catch ( S...
Set a time bomb to cancel the outstanding query when timeout is reached .
28,478
private void cancelHelper ( String sql , String mediaType ) throws SnowflakeSQLException , SFException { synchronized ( this ) { if ( isClosed ) { throw new SFException ( ErrorCode . INTERNAL_ERROR , "statement already closed" ) ; } } StmtUtil . StmtInput stmtInput = new StmtUtil . StmtInput ( ) ; stmtInput . setServer...
A helper method to build URL and cancel the SQL for exec
28,479
public boolean getMoreResults ( int current ) throws SQLException { if ( resultSet != null && ( current == Statement . CLOSE_CURRENT_RESULT || current == Statement . CLOSE_ALL_RESULTS ) ) { resultSet . close ( ) ; } resultSet = null ; if ( childResults == null || childResults . isEmpty ( ) ) { return false ; } SFChildR...
Sets the result set to the next one if available .
28,480
public boolean isServiceException404 ( ) { if ( ( Exception ) this instanceof AmazonServiceException ) { AmazonServiceException asEx = ( AmazonServiceException ) ( ( java . lang . Exception ) this ) ; return ( asEx . getStatusCode ( ) == HttpStatus . SC_NOT_FOUND ) ; } return false ; }
Returns true if this is an exception corresponding to a HTTP 404 error returned by the storage provider
28,481
public static String oneLiner ( Throwable thrown ) { StackTraceElement [ ] stack = thrown . getStackTrace ( ) ; String topOfStack = null ; if ( stack . length > 0 ) { topOfStack = " at " + stack [ 0 ] ; } return thrown . toString ( ) + topOfStack ; }
Produce a one line description of the throwable suitable for error message and log printing .
28,482
public static void dumpVmMetrics ( String incidentId ) { PrintWriter writer = null ; try { String dumpFile = EventUtil . getDumpPathPrefix ( ) + "/" + INC_DUMP_FILE_NAME + incidentId + INC_DUMP_FILE_EXT ; final OutputStream outStream = new GZIPOutputStream ( new FileOutputStream ( dumpFile ) ) ; writer = new PrintWrite...
Dumps JVM metrics for this process .
28,483
public static Throwable generateIncidentV2WithException ( SFSession session , Throwable exc , String jobId , String requestId ) { new Incident ( session , exc , jobId , requestId ) . trigger ( ) ; return exc ; }
Makes a V2 incident object and triggers ir effectively reporting the given exception to GS and possibly to crashmanager
28,484
public static String getUTCNow ( ) { SimpleDateFormat dateFormatGmt = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ) ; dateFormatGmt . setTimeZone ( TimeZone . getTimeZone ( "GMT" ) ) ; return dateFormatGmt . format ( new Date ( ) ) ; }
Get current time in UTC in the following format
28,485
public void renew ( Map stageCredentials ) throws SnowflakeSQLException { stageInfo . setCredentials ( stageCredentials ) ; setupAzureClient ( stageInfo , encMat ) ; }
Re - creates the encapsulated storage client with a fresh access token
28,486
public StorageObjectMetadata getObjectMetadata ( String remoteStorageLocation , String prefix ) throws StorageProviderException { AzureObjectMetadata azureObjectMetadata = null ; try { CloudBlobContainer container = azStorageClient . getContainerReference ( remoteStorageLocation ) ; CloudBlob blob = container . getBloc...
Returns the metadata properties for a remote storage object
28,487
public void download ( SFSession connection , String command , String localLocation , String destFileName , int parallelism , String remoteStorageLocation , String stageFilePath , String stageRegion ) throws SnowflakeSQLException { int retryCount = 0 ; do { try { String localFilePath = localLocation + localFileSep + de...
Download a file from remote storage .
28,488
private static void handleAzureException ( Exception ex , int retryCount , String operation , SFSession connection , String command , SnowflakeAzureClient azClient ) throws SnowflakeSQLException { if ( ex . getCause ( ) instanceof InvalidKeyException ) { SnowflakeFileTransferAgent . throwJCEMissingError ( operation , e...
Handles exceptions thrown by Azure Storage It will retry transient errors as defined by the Azure Client retry policy It will re - create the client if the SAS token has expired and re - try
28,489
public void addDigestMetadata ( StorageObjectMetadata meta , String digest ) { if ( ! SnowflakeUtil . isBlank ( digest ) ) { meta . addUserMetadata ( "sfcdigest" , digest ) ; } }
Adds digest metadata to the StorageObjectMetadata object
28,490
private static long initMemoryLimit ( final ResultOutput resultOutput ) { long memoryLimit = SessionUtil . DEFAULT_CLIENT_MEMORY_LIMIT * 1024 * 1024 ; if ( resultOutput . parameters . get ( CLIENT_MEMORY_LIMIT ) != null ) { memoryLimit = ( int ) resultOutput . parameters . get ( CLIENT_MEMORY_LIMIT ) * 1024L * 1024L ; ...
initialize memory limit in bytes
28,491
static private Object effectiveParamValue ( Map < String , Object > parameters , String paramName ) { String upper = paramName . toUpperCase ( ) ; Object value = parameters . get ( upper ) ; if ( value != null ) { return value ; } value = defaultParameters . get ( upper ) ; if ( value != null ) { return value ; } logge...
Returns the effective parameter value using the value explicitly provided in parameters or the default if absent
28,492
static private SnowflakeDateTimeFormat specializedFormatter ( Map < String , Object > parameters , String id , String param , String defaultFormat ) { String sqlFormat = SnowflakeDateTimeFormat . effectiveSpecializedTimestampFormat ( ( String ) effectiveParamValue ( parameters , param ) , defaultFormat ) ; SnowflakeDat...
Helper function building a formatter for a specialized timestamp type . Note that it will be based on either the param value if set or the default format provided .
28,493
static public Timestamp adjustTimestamp ( Timestamp timestamp ) { long milliToAdjust = ResultUtil . msDiffJulianToGregorian ( timestamp ) ; if ( milliToAdjust != 0 ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "adjust timestamp by {} days" , milliToAdjust / 86400000 ) ; } Timestamp newTimestamp = new Timest...
Adjust timestamp for dates before 1582 - 10 - 05
28,494
static public long msDiffJulianToGregorian ( java . util . Date date ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( date ) ; int year = cal . get ( Calendar . YEAR ) ; int month = cal . get ( Calendar . MONTH ) ; int dayOfMonth = cal . get ( Calendar . DAY_OF_MONTH ) ; if ( date . getTime ( ) < - 12220...
For dates before 1582 - 10 - 05 calculate the number of millis to adjust .
28,495
static public String getSFTimeAsString ( SFTime sft , int scale , SnowflakeDateTimeFormat timeFormatter ) { return timeFormatter . format ( sft , scale ) ; }
Convert a time value into a string
28,496
static public String getSFTimestampAsString ( SFTimestamp sfTS , int columnType , int scale , SnowflakeDateTimeFormat timestampNTZFormatter , SnowflakeDateTimeFormat timestampLTZFormatter , SnowflakeDateTimeFormat timestampTZFormatter , SFSession session ) throws SFException { SnowflakeDateTimeFormat formatter ; if ( c...
Convert a SFTimestamp to a string value .
28,497
static public String getDateAsString ( Date date , SnowflakeDateTimeFormat dateFormatter ) { return dateFormatter . format ( date , timeZoneUTC ) ; }
Convert a date value into a string
28,498
static public Date adjustDate ( Date date ) { long milliToAdjust = ResultUtil . msDiffJulianToGregorian ( date ) ; if ( milliToAdjust != 0 ) { return new Date ( date . getTime ( ) + milliToAdjust ) ; } else { return date ; } }
Adjust date for before 1582 - 10 - 05
28,499
static public Date getDate ( String str , TimeZone tz , SFSession session ) throws SFException { try { long milliSecsSinceEpoch = Long . valueOf ( str ) * 86400000 ; SFTimestamp tsInUTC = SFTimestamp . fromDate ( new Date ( milliSecsSinceEpoch ) , 0 , TimeZone . getTimeZone ( "UTC" ) ) ; SFTimestamp tsInClientTZ = tsIn...
Convert a date internal object to a Date object in specified timezone .