idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
152,000
protected List < IPersonAttributes > searchDirectory ( String query , PortletRequest request ) { final Map < String , Object > queryAttributes = new HashMap < > ( ) ; for ( String attr : directoryQueryAttributes ) { queryAttributes . put ( attr , query ) ; } final List < IPersonAttributes > people ; HttpServletRequest ...
Search the directory for people matching the search query . Search results will be scoped to the permissions of the user performing the search .
152,001
protected boolean isMobile ( PortletRequest request ) { final String themeName = request . getProperty ( IPortletRenderer . THEME_NAME_PROPERTY ) ; return "UniversalityMobile" . equals ( themeName ) ; }
Determine if this should be a mobile view .
152,002
protected IPortletEntity unwrapEntity ( IPortletEntity portletEntity ) { if ( portletEntity instanceof TransientPortletEntity ) { return ( ( TransientPortletEntity ) portletEntity ) . getDelegatePortletEntity ( ) ; } return portletEntity ; }
Returns the unwrapped entity if it is an instance of TransientPortletEntity . If not the original entity is returned .
152,003
protected IPortletEntity wrapEntity ( IPortletEntity portletEntity ) { if ( portletEntity == null ) { return null ; } final String persistentLayoutNodeId = portletEntity . getLayoutNodeId ( ) ; if ( persistentLayoutNodeId . startsWith ( TransientUserLayoutManagerWrapper . SUBSCRIBE_PREFIX ) ) { final IUserLayoutManager...
Adds a TransientPortletEntity wrapper to the portletEntity if it is needed . If the specified entity is transient but no transient subscribe id has been registered for it yet in the transientIdMap null is returned . If no wrapping is needed the original entity is returned .
152,004
public static boolean isValidUrl ( String url ) { HttpURLConnection huc = null ; boolean isValid = false ; try { URL u = new URL ( url ) ; huc = ( HttpURLConnection ) u . openConnection ( ) ; huc . setRequestMethod ( "GET" ) ; huc . connect ( ) ; int response = huc . getResponseCode ( ) ; if ( response != HttpURLConnec...
Tests if a string is a valid URL Will open a connection and make sure that it can connect to the URL it looks for an HTTP status code of 200 on a GET . This is a valid URL .
152,005
public static < T > boolean included ( T value , Collection < ? extends T > includes , Collection < ? extends T > excludes ) { return ( includes . isEmpty ( ) && excludes . isEmpty ( ) ) || includes . contains ( value ) || ( includes . isEmpty ( ) && ! excludes . contains ( value ) ) ; }
Determines if the specified value is included based on the contents of the include and exclude collections .
152,006
public void init ( ContextRefreshedEvent event ) { idTokenFactory = context . getBean ( IdTokenFactory . class ) ; if ( guestUsernameSelectors == null ) { guestUsernameSelectors = Collections . emptyList ( ) ; } Collections . sort ( guestUsernameSelectors ) ; }
To avoid circular reference issues this bean obtains its dependencies when the context finishes starting .
152,007
protected boolean handleResourceHeader ( String key , String value ) { if ( ResourceResponse . HTTP_STATUS_CODE . equals ( key ) ) { this . portletResourceOutputHandler . setStatus ( Integer . parseInt ( value ) ) ; return true ; } if ( "Content-Type" . equals ( key ) ) { final ContentType contentType = ContentType . p...
Handles resource response specific headers . Returns true if the header was consumed by this method and requires no further processing
152,008
public void perform ( ) throws PortalException { if ( nodeId . startsWith ( Constants . FRAGMENT_ID_USER_PREFIX ) ) { ParameterEditManager . removeParmEditDirective ( nodeId , name , person ) ; } LPAChangeParameter . changeParameterChild ( ilfNode , name , fragmentValue ) ; }
Reset the parameter to not override the value specified by a fragment . This is done by removing the parm edit in the PLF and setting the value in the ILF to the passed - in fragment value .
152,009
public void add ( IPermission perm ) throws AuthorizationException { Connection conn = null ; int rc = 0 ; try { conn = RDBMServices . getConnection ( ) ; String sQuery = getInsertPermissionSql ( ) ; PreparedStatement ps = conn . prepareStatement ( sQuery ) ; try { primAdd ( perm , ps ) ; if ( log . isDebugEnabled ( ) ...
Add the IPermission to the store .
152,010
public void delete ( IPermission [ ] perms ) throws AuthorizationException { if ( perms . length > 0 ) { try { primDelete ( perms ) ; } catch ( Exception ex ) { log . error ( "Exception deleting permissions " + Arrays . toString ( perms ) , ex ) ; throw new AuthorizationException ( "Exception deleting permissions " + A...
Delete the IPermissions from the store .
152,011
public void delete ( IPermission perm ) throws AuthorizationException { Connection conn = null ; try { conn = RDBMServices . getConnection ( ) ; String sQuery = getDeletePermissionSql ( ) ; PreparedStatement ps = conn . prepareStatement ( sQuery ) ; try { primDelete ( perm , ps ) ; } finally { ps . close ( ) ; } } catc...
Delete a single IPermission from the store .
152,012
private int getPrincipalType ( String principalString ) { return Integer . parseInt ( principalString . substring ( 0 , principalString . indexOf ( PRINCIPAL_SEPARATOR ) ) ) ; }
Returns the principal type portion of the principal .
152,013
private int primDelete ( IPermission perm , PreparedStatement ps ) throws Exception { ps . clearParameters ( ) ; ps . setString ( 1 , perm . getOwner ( ) ) ; ps . setInt ( 2 , getPrincipalType ( perm ) ) ; ps . setString ( 3 , getPrincipalKey ( perm ) ) ; ps . setString ( 4 , perm . getActivity ( ) ) ; ps . setString (...
Set the params on the PreparedStatement and execute the delete .
152,014
private int primUpdate ( IPermission perm , PreparedStatement ps ) throws Exception { java . sql . Timestamp ts = null ; ps . clearParameters ( ) ; if ( perm . getType ( ) == null ) { ps . setNull ( 1 , Types . VARCHAR ) ; } else { ps . setString ( 1 , perm . getType ( ) ) ; } if ( perm . getEffective ( ) == null ) { p...
Set the params on the PreparedStatement and execute the update .
152,015
public IPermission [ ] select ( String owner , String principal , String activity , String target , String type ) throws AuthorizationException { Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; List < IPermission > perms = new ArrayList < IPermission > ( ) ; String query = getSelectQuery ...
Select the Permissions from the store .
152,016
public void update ( IPermission perm ) throws AuthorizationException { Connection conn = null ; try { conn = RDBMServices . getConnection ( ) ; String sQuery = getUpdatePermissionSql ( ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "RDBMPermissionImpl.update(): " + sQuery ) ; PreparedStatement ps = conn . prepareSt...
Update a single IPermission in the store .
152,017
public PortletEventQueue getPortletEventQueue ( HttpServletRequest request ) { request = this . portalRequestUtils . getOriginalPortalRequest ( request ) ; synchronized ( PortalWebUtils . getRequestAttributeMutex ( request ) ) { PortletEventQueue portletEventQueue = ( PortletEventQueue ) request . getAttribute ( PORTLE...
Returns a request scoped PortletEventQueue used to track events to process and events to dispatch
152,018
protected HttpServletRequest getServletRequestFromExternalContext ( ExternalContext externalContext ) { Object request = externalContext . getNativeRequest ( ) ; if ( request instanceof PortletRequest ) { return portalRequestUtils . getPortletHttpRequest ( ( PortletRequest ) externalContext . getNativeRequest ( ) ) ; }...
Get the HttpServletRequest associated with the supplied ExternalContext .
152,019
protected IPortletDefinition getChannelDefinition ( String subId ) throws PortalException { IPortletDefinition chanDef = mChanMap . get ( subId ) ; if ( null == chanDef ) { String fname = getFname ( subId ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "TransientUserLayoutManagerWrapper>>getChannelDefinition, " + "at...
Given a subscribe Id return a ChannelDefinition .
152,020
public String getSubscribeId ( String fname ) throws PortalException { String subId = mFnameMap . get ( fname ) ; if ( subId == null ) { subId = man . getSubscribeId ( fname ) ; } if ( subId == null ) { try { IPortletDefinition chanDef = PortletDefinitionRegistryLocator . getPortletDefinitionRegistry ( ) . getPortletDe...
Given an functional name return its subscribe id .
152,021
private IUserLayoutChannelDescription getTransientNode ( String nodeId ) throws PortalException { final String fname = getFname ( nodeId ) ; if ( null == fname || fname . equals ( "" ) ) { return null ; } try { IPortletDefinition chanDef = mChanMap . get ( nodeId ) ; if ( null == chanDef ) { chanDef = PortletDefinition...
Return an IUserLayoutChannelDescription by way of nodeId
152,022
public boolean sendEvent ( LrsStatement statement ) { if ( ! isEnabled ( ) ) { return false ; } ResponseEntity < Object > response = sendRequest ( STATEMENTS_REST_ENDPOINT , HttpMethod . POST , null , statement , Object . class ) ; if ( response . getStatusCode ( ) . series ( ) == Series . SUCCESSFUL ) { logger . trace...
Actually send an event to the provider .
152,023
protected void loadConfig ( ) { if ( ! isEnabled ( ) ) { return ; } final String urlProp = format ( PROPERTY_FORMAT , id , "url" ) ; LRSUrl = propertyResolver . getProperty ( urlProp ) ; actorName = propertyResolver . getProperty ( format ( PROPERTY_FORMAT , id , "actor-name" ) , actorName ) ; actorEmail = propertyReso...
Read the LRS config .
152,024
protected < T > ResponseEntity < T > sendRequest ( String pathFragment , HttpMethod method , List < ? extends NameValuePair > getParams , Object postData , Class < T > returnType ) { HttpHeaders headers = new HttpHeaders ( ) ; headers . add ( XAPI_VERSION_HEADER , XAPI_VERSION_VALUE ) ; if ( postData instanceof MultiVa...
Send a request to the LRS .
152,025
private URI buildRequestURI ( String pathFragment , List < ? extends NameValuePair > params ) { try { String queryString = "" ; if ( params != null && ! params . isEmpty ( ) ) { queryString = "?" + URLEncodedUtils . format ( params , "UTF-8" ) ; } URI fullURI = new URI ( LRSUrl + pathFragment + queryString ) ; return f...
Build a URI for the REST request .
152,026
protected void bindAggregationSpecificKeyParameters ( TypedQuery < PortletExecutionAggregationImpl > query , Set < PortletExecutionAggregationKey > keys ) { query . setParameter ( this . portletMappingParameter , extractAggregatePortletMappings ( keys ) ) ; query . setParameter ( this . executionTypeParameter , extract...
The execution type is obtained from the first PortletExecutionAggregationKey .
152,027
protected EntityManager getTransactionalEntityManager ( EntityManagerFactory emf ) throws IllegalStateException { Assert . state ( emf != null , "No EntityManagerFactory specified" ) ; return EntityManagerFactoryUtils . getTransactionalEntityManager ( emf ) ; }
Obtain the transactional EntityManager for this accessor s EntityManagerFactory if any .
152,028
protected EntityManagerFactory getEntityManagerFactory ( OpenEntityManager openEntityManager ) { final CacheKey key = this . createEntityManagerFactoryKey ( openEntityManager ) ; EntityManagerFactory emf = this . entityManagerFactories . get ( key ) ; if ( emf == null ) { emf = this . lookupEntityManagerFactory ( openE...
Get the EntityManagerFactory that this filter should use .
152,029
protected EntityManagerFactory lookupEntityManagerFactory ( OpenEntityManager openEntityManager ) { String emfBeanName = openEntityManager . name ( ) ; String puName = openEntityManager . unitName ( ) ; if ( StringUtils . hasLength ( emfBeanName ) ) { return this . applicationContext . getBean ( emfBeanName , EntityMan...
Look up the EntityManagerFactory that this filter should use .
152,030
public synchronized Object put ( Object key , Object value ) { ValueWrapper valueWrapper = new ValueWrapper ( value ) ; return super . put ( key , valueWrapper ) ; }
Add a new value to the cache . The value will expire in accordance with the cache s expiration timeout value which was set when the cache was created .
152,031
public synchronized Object put ( Object key , Object value , long lCacheInterval ) { ValueWrapper valueWrapper = new ValueWrapper ( value , lCacheInterval ) ; return super . put ( key , valueWrapper ) ; }
Add a new value to the cache
152,032
public synchronized Object get ( Object key ) { ValueWrapper valueWrapper = ( ValueWrapper ) super . get ( key ) ; if ( valueWrapper != null ) { long creationTime = valueWrapper . getCreationTime ( ) ; long cacheInterval = valueWrapper . getCacheInterval ( ) ; long currentTime = System . currentTimeMillis ( ) ; if ( ca...
Get an object from the cache .
152,033
protected void sweepCache ( ) { for ( Iterator keyIterator = keySet ( ) . iterator ( ) ; keyIterator . hasNext ( ) ; ) { Object key = keyIterator . next ( ) ; ValueWrapper valueWrapper = ( ValueWrapper ) super . get ( key ) ; long creationTime = valueWrapper . getCreationTime ( ) ; long cacheInterval = valueWrapper . g...
Removes from the cache values which have expired .
152,034
private String getInitParameter ( String name , String defaultValue ) { String value = getInitParameter ( name ) ; if ( value != null ) { return value ; } return defaultValue ; }
This method returns the parameter s value if it exists or defaultValue if not .
152,035
private String getMediaType ( String contentType ) { if ( contentType == null ) { return null ; } String result = contentType . toLowerCase ( Locale . ENGLISH ) ; int firstSemiColonIndex = result . indexOf ( ';' ) ; if ( firstSemiColonIndex > - 1 ) { result = result . substring ( 0 , firstSemiColonIndex ) ; } result = ...
Return the lower case trimmed value of the media type from the content type .
152,036
public void endParsing ( ) throws SnowflakeSQLException { if ( partialEscapedUnicode . position ( ) > 0 ) { partialEscapedUnicode . flip ( ) ; continueParsingInternal ( partialEscapedUnicode , true ) ; partialEscapedUnicode . clear ( ) ; } if ( state != State . ROW_FINISHED ) { throw new SnowflakeSQLException ( SqlStat...
Check if the chunk has been parsed correctly . After calling this it is safe to acquire the output data
152,037
public void continueParsing ( ByteBuffer in ) throws SnowflakeSQLException { if ( state == State . UNINITIALIZED ) { throw new SnowflakeSQLException ( SqlState . INTERNAL_ERROR , ErrorCode . INTERNAL_ERROR . getMessageCode ( ) , "Json parser hasn't been initialized!" ) ; } if ( partialEscapedUnicode . position ( ) > 0 ...
Continue parsing with the given data
152,038
public static void cancel ( StmtInput stmtInput ) throws SFException , SnowflakeSQLException { HttpPost httpRequest = null ; AssertUtil . assertTrue ( stmtInput . serverUrl != null , "Missing server url for statement execution" ) ; AssertUtil . assertTrue ( stmtInput . sql != null , "Missing sql for statement execution...
Cancel a statement identifiable by a request id
152,039
static public SFStatementType checkStageManageCommand ( String sql ) { if ( sql == null ) { return null ; } String trimmedSql = sql . trim ( ) ; while ( trimmedSql . startsWith ( "//" ) ) { logger . debug ( "skipping // comments in: \n{}" , trimmedSql ) ; if ( trimmedSql . indexOf ( '\n' ) > 0 ) { trimmedSql = trimmedS...
A simple function to check if the statement is related to manipulate stage .
152,040
public void flush ( ) { if ( ! enabled ) { return ; } if ( ! queue . isEmpty ( ) ) { Runnable runUpload = new TelemetryUploader ( this , exportQueueToString ( ) ) ; uploader . execute ( runUpload ) ; } }
force to flush events in the queue
152,041
public String exportQueueToString ( ) { JSONArray logs = new JSONArray ( ) ; while ( ! queue . isEmpty ( ) ) { logs . add ( queue . poll ( ) ) ; } return SecretDetector . maskAWSSecret ( logs . toString ( ) ) ; }
convert a list of json objects to a string
152,042
public void logHttpRequestTelemetryEvent ( String eventName , HttpRequestBase request , int injectSocketTimeout , AtomicBoolean canceling , boolean withoutCookies , boolean includeRetryParameters , boolean includeRequestGuid , CloseableHttpResponse response , final Exception savedEx , String breakRetryReason , long ret...
log error http response to telemetry
152,043
public final Object getCell ( int rowIdx , int colIdx ) { if ( resultData != null ) { return extractCell ( resultData , rowIdx , colIdx ) ; } return data . get ( colCount * rowIdx + colIdx ) ; }
Creates a String object for the given cell
152,044
public final void ensureRowsComplete ( ) throws SnowflakeSQLException { if ( rowCount != currentRow ) { throw new SnowflakeSQLException ( SqlState . INTERNAL_ERROR , ErrorCode . INTERNAL_ERROR . getMessageCode ( ) , "Exception: expected " + rowCount + " rows and received " + currentRow ) ; } }
Checks that all data has been added after parsing .
152,045
static CloseableHttpClient buildHttpClient ( boolean insecureMode , File ocspCacheFile , boolean useOcspCacheServer ) { DefaultRequestConfig = RequestConfig . custom ( ) . setConnectTimeout ( DEFAULT_CONNECTION_TIMEOUT ) . setConnectionRequestTimeout ( DEFAULT_CONNECTION_TIMEOUT ) . setSocketTimeout ( DEFAULT_HTTP_CLIE...
Build an Http client using our set of default .
152,046
public static CloseableHttpClient initHttpClient ( boolean insecureMode , File ocspCacheFile ) { if ( httpClient == null ) { synchronized ( HttpUtil . class ) { if ( httpClient == null ) { httpClient = buildHttpClient ( insecureMode , ocspCacheFile , enableOcspResponseCacheServer ( ) ) ; } } } return httpClient ; }
Accessor for the HTTP client singleton .
152,047
public static RequestConfig getDefaultRequestConfigWithSocketTimeout ( int soTimeoutMs , boolean withoutCookies ) { getHttpClient ( ) ; final String cookieSpec = withoutCookies ? IGNORE_COOKIES : DEFAULT ; return RequestConfig . copy ( DefaultRequestConfig ) . setSocketTimeout ( soTimeoutMs ) . setCookieSpec ( cookieSp...
Return a request configuration inheriting from the default request configuration of the shared HttpClient with a different socket timeout .
152,048
static String executeRequestWithoutCookies ( HttpRequestBase httpRequest , int retryTimeout , int injectSocketTimeout , AtomicBoolean canceling ) throws SnowflakeSQLException , IOException { return executeRequestInternal ( httpRequest , retryTimeout , injectSocketTimeout , canceling , true , false , true ) ; }
Executes a HTTP request with the cookie spec set to IGNORE_COOKIES
152,049
public static String executeRequest ( HttpRequestBase httpRequest , int retryTimeout , int injectSocketTimeout , AtomicBoolean canceling ) throws SnowflakeSQLException , IOException { return executeRequest ( httpRequest , retryTimeout , injectSocketTimeout , canceling , false ) ; }
Executes a HTTP request for Snowflake .
152,050
public static void configureCustomProxyProperties ( Map < SFSessionProperty , Object > connectionPropertiesMap ) { if ( connectionPropertiesMap . containsKey ( SFSessionProperty . USE_PROXY ) ) { useProxy = ( boolean ) connectionPropertiesMap . get ( SFSessionProperty . USE_PROXY ) ; } if ( useProxy ) { proxyHost = ( S...
configure custom proxy properties from connectionPropertiesMap
152,051
static private void checkErrorAndThrowExceptionSub ( JsonNode rootNode , boolean raiseReauthenticateError ) throws SnowflakeSQLException { if ( rootNode . path ( "success" ) . asBoolean ( ) ) { return ; } String errorMessage ; String sqlState ; int errorCode ; String queryId = "unknown" ; if ( ! rootNode . path ( "data...
Check the error in the JSON node and generate an exception based on information extracted from the node .
152,052
static void assertTrue ( boolean condition , String internalErrorMesg ) throws SFException { if ( ! condition ) { throw new SFException ( ErrorCode . INTERNAL_ERROR , internalErrorMesg ) ; } }
Assert the condition is true otherwise throw an internal error exception with the given message .
152,053
public static MatDesc parse ( String matdesc ) { if ( matdesc == null ) { return null ; } try { JsonNode jsonNode = mapper . readTree ( matdesc ) ; JsonNode queryIdNode = jsonNode . path ( QUERY_ID ) ; if ( queryIdNode . isMissingNode ( ) || queryIdNode . isNull ( ) ) { return null ; } JsonNode smkIdNode = jsonNode . p...
Try to parse the material descriptor string .
152,054
private SFPair < String , String > applySessionContext ( String catalog , String schemaPattern ) { if ( catalog == null && metadataRequestUseConnectionCtx ) { catalog = session . getDatabase ( ) ; if ( schemaPattern == null ) { schemaPattern = session . getSchema ( ) ; } } return SFPair . of ( catalog , schemaPattern )...
apply session context when catalog is unspecified
152,055
private short getForeignKeyConstraintProperty ( String property_name , String property ) { short result = 0 ; switch ( property_name ) { case "update" : case "delete" : switch ( property ) { case "NO ACTION" : result = importedKeyNoAction ; break ; case "CASCADE" : result = importedKeyCascade ; break ; case "SET NULL" ...
Returns the JDBC standard property string for the property string used in our show constraint commands
152,056
private ResultSet executeAndReturnEmptyResultIfNotFound ( Statement statement , String sql , DBMetadataResultSetMetadata metadataType ) throws SQLException { ResultSet resultSet ; try { resultSet = statement . executeQuery ( sql ) ; } catch ( SnowflakeSQLException e ) { if ( e . getSQLState ( ) . equals ( SqlState . NO...
A small helper function to execute show command to get metadata And if object does not exist return an empty result set instead of throwing a SnowflakeSQLException
152,057
static private ClientAuthnDTO . AuthenticatorType getAuthenticator ( LoginInput loginInput ) { if ( loginInput . getAuthenticator ( ) != null ) { if ( loginInput . getAuthenticator ( ) . equalsIgnoreCase ( ClientAuthnDTO . AuthenticatorType . EXTERNALBROWSER . name ( ) ) ) { return ClientAuthnDTO . AuthenticatorType . ...
Returns Authenticator type
152,058
static public LoginOutput openSession ( LoginInput loginInput ) throws SFException , SnowflakeSQLException { AssertUtil . assertTrue ( loginInput . getServerUrl ( ) != null , "missing server URL for opening session" ) ; AssertUtil . assertTrue ( loginInput . getAppId ( ) != null , "missing app id for opening session" )...
Open a new session
152,059
static public LoginOutput issueSession ( LoginInput loginInput ) throws SFException , SnowflakeSQLException { return tokenRequest ( loginInput , TokenRequestType . ISSUE ) ; }
Issue a session
152,060
static public void closeSession ( LoginInput loginInput ) throws SFException , SnowflakeSQLException { logger . debug ( " public void close() throws SFException" ) ; AssertUtil . assertTrue ( loginInput . getServerUrl ( ) != null , "missing server URL for closing session" ) ; AssertUtil . assertTrue ( loginInput . getS...
Close a session
152,061
private static String federatedFlowStep3 ( LoginInput loginInput , String tokenUrl ) throws SnowflakeSQLException { String oneTimeToken = "" ; try { URL url = new URL ( tokenUrl ) ; URI tokenUri = url . toURI ( ) ; final HttpPost postRequest = new HttpPost ( tokenUri ) ; StringEntity params = new StringEntity ( "{\"use...
Query IDP token url to authenticate and retrieve access token
152,062
private static JsonNode federatedFlowStep1 ( LoginInput loginInput ) throws SnowflakeSQLException { JsonNode dataNode = null ; try { URIBuilder fedUriBuilder = new URIBuilder ( loginInput . getServerUrl ( ) ) ; fedUriBuilder . setPath ( SF_PATH_AUTHENTICATOR_REQUEST ) ; URI fedUrlUri = fedUriBuilder . build ( ) ; Map <...
Query Snowflake to obtain IDP token url and IDP SSO url
152,063
private static void handleFederatedFlowError ( LoginInput loginInput , Exception ex ) throws SnowflakeSQLException { if ( ex instanceof IOException ) { logger . error ( "IOException when authenticating with " + loginInput . getAuthenticator ( ) , ex ) ; throw new SnowflakeSQLException ( ex , SqlState . IO_ERROR , Error...
Logs an error generated during the federated authentication flow and re - throws it as a SnowflakeSQLException . Note that we seperate IOExceptions since those tend to be network related .
152,064
static private String getSamlResponseUsingOkta ( LoginInput loginInput ) throws SnowflakeSQLException { JsonNode dataNode = federatedFlowStep1 ( loginInput ) ; String tokenUrl = dataNode . path ( "tokenUrl" ) . asText ( ) ; String ssoUrl = dataNode . path ( "ssoUrl" ) . asText ( ) ; federatedFlowStep2 ( loginInput , to...
FEDERATED FLOW See SNOW - 27798 for additional details .
152,065
static boolean isPrefixEqual ( String aUrlStr , String bUrlStr ) throws MalformedURLException { URL aUrl = new URL ( aUrlStr ) ; URL bUrl = new URL ( bUrlStr ) ; int aPort = aUrl . getPort ( ) ; int bPort = bUrl . getPort ( ) ; if ( aPort == - 1 && "https" . equals ( aUrl . getProtocol ( ) ) ) { aPort = 443 ; } if ( bP...
Verify if two input urls have the same protocol host and port .
152,066
static private String getPostBackUrlFromHTML ( String html ) { Document doc = Jsoup . parse ( html ) ; Elements e1 = doc . getElementsByTag ( "body" ) ; Elements e2 = e1 . get ( 0 ) . getElementsByTag ( "form" ) ; String postBackUrl = e2 . first ( ) . attr ( "action" ) ; return postBackUrl ; }
Extracts post back url from the HTML returned by the IDP
152,067
public static Map < String , Object > getCommonParams ( JsonNode paramsNode ) { Map < String , Object > parameters = new HashMap < > ( ) ; for ( JsonNode child : paramsNode ) { if ( ! child . hasNonNull ( "name" ) ) { logger . error ( "Common Parameter JsonNode encountered with " + "no parameter name!" ) ; continue ; }...
Helper function to parse a JsonNode from a GS response containing CommonParameters emitting an EnumMap of parameters
152,068
protected ServerSocket getServerSocket ( ) throws SFException { try { return new ServerSocket ( 0 , 0 , InetAddress . getByName ( "localhost" ) ) ; } catch ( IOException ex ) { throw new SFException ( ex , ErrorCode . NETWORK_ERROR , ex . getMessage ( ) ) ; } }
Gets a free port on localhost
152,069
private String getSSOUrl ( int port ) throws SFException , SnowflakeSQLException { try { String serverUrl = loginInput . getServerUrl ( ) ; String authenticator = loginInput . getAuthenticator ( ) ; URIBuilder fedUriBuilder = new URIBuilder ( serverUrl ) ; fedUriBuilder . setPath ( SessionUtil . SF_PATH_AUTHENTICATOR_R...
Gets SSO URL and proof key
152,070
private void processSamlToken ( String [ ] rets , Socket socket ) throws IOException , SFException { String targetLine = null ; String userAgent = null ; boolean isPost = false ; for ( String line : rets ) { if ( line . length ( ) > PREFIX_GET . length ( ) && line . substring ( 0 , PREFIX_GET . length ( ) ) . equalsIgn...
Receives SAML token from Snowflake via web browser
152,071
private void returnToBrowser ( Socket socket ) throws IOException { PrintWriter out = new PrintWriter ( socket . getOutputStream ( ) , true ) ; List < String > content = new ArrayList < > ( ) ; content . add ( "HTTP/1.0 200 OK" ) ; content . add ( "Content-Type: text/html" ) ; String responseText ; if ( this . origin !...
Output the message to the browser
152,072
public static TelemetryData buildJobData ( String queryId , TelemetryField field , long value ) { ObjectNode obj = mapper . createObjectNode ( ) ; obj . put ( TYPE , field . toString ( ) ) ; obj . put ( QUERY_ID , queryId ) ; obj . put ( VALUE , value ) ; return new TelemetryData ( obj , System . currentTimeMillis ( ) ...
Create a simple TelemetryData instance for Job metrics using given parameters
152,073
public void download ( SFSession connection , String command , String localLocation , String destFileName , int parallelism , String remoteStorageLocation , String stageFilePath , String stageRegion ) throws SnowflakeSQLException { TransferManager tx = null ; int retryCount = 0 ; do { try { File localFile = new File ( ...
Download a file from S3 .
152,074
static void resetOCSPResponseCacherServerURL ( String ocspCacheServerUrl ) { if ( ocspCacheServerUrl == null || SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN != null ) { return ; } SF_OCSP_RESPONSE_CACHE_SERVER_URL = ocspCacheServerUrl ; if ( ! SF_OCSP_RESPONSE_CACHE_SERVER_URL . startsWith ( DEFAULT_OCSP_CACHE_HOST ...
Reset OCSP Cache server URL
152,075
private X509TrustManager getTrustManager ( String algorithm ) { try { TrustManagerFactory factory = TrustManagerFactory . getInstance ( algorithm ) ; factory . init ( ( KeyStore ) null ) ; X509TrustManager ret = null ; for ( TrustManager tm : factory . getTrustManagers ( ) ) { if ( tm instanceof X509TrustManager ) { re...
Get TrustManager for the algorithm . This is mainly used to get the JVM default trust manager and cache all of the root CA .
152,076
void validateRevocationStatus ( X509Certificate [ ] chain , String peerHost ) throws CertificateException { final List < Certificate > bcChain = convertToBouncyCastleCertificate ( chain ) ; final List < SFPair < Certificate , Certificate > > pairIssuerSubjectList = getPairIssuerSubject ( bcChain ) ; if ( peerHost . sta...
Certificate Revocation checks
152,077
private void executeRevocationStatusChecks ( List < SFPair < Certificate , Certificate > > pairIssuerSubjectList , String peerHost ) throws CertificateException { long currentTimeSecond = new Date ( ) . getTime ( ) / 1000L ; try { for ( SFPair < Certificate , Certificate > pairIssuerSubject : pairIssuerSubjectList ) { ...
Executes the revocation status checks for all chained certificates
152,078
private static String encodeCacheKey ( OcspResponseCacheKey ocsp_cache_key ) { try { DigestCalculator digest = new SHA1DigestCalculator ( ) ; AlgorithmIdentifier algo = digest . getAlgorithmIdentifier ( ) ; ASN1OctetString nameHash = ASN1OctetString . getInstance ( ocsp_cache_key . nameHash ) ; ASN1OctetString keyHash ...
Convert cache key to base64 encoded cert id
152,079
private boolean isCached ( List < SFPair < Certificate , Certificate > > pairIssuerSubjectList ) { long currentTimeSecond = new Date ( ) . getTime ( ) / 1000L ; boolean isCached = true ; try { for ( SFPair < Certificate , Certificate > pairIssuerSubject : pairIssuerSubjectList ) { OCSPReq req = createRequest ( pairIssu...
Is OCSP Response cached?
152,080
private static String CertificateIDToString ( CertificateID certificateID ) { return String . format ( "CertID. NameHash: %s, KeyHash: %s, Serial Number: %s" , byteToHexString ( certificateID . getIssuerNameHash ( ) ) , byteToHexString ( certificateID . getIssuerKeyHash ( ) ) , MessageFormat . format ( "{0,number,#}" ,...
CertificateID to string
152,081
private static SFPair < OcspResponseCacheKey , SFPair < Long , String > > decodeCacheFromJSON ( Map . Entry < String , JsonNode > elem ) throws IOException { long currentTimeSecond = new Date ( ) . getTime ( ) / 1000 ; byte [ ] certIdDer = Base64 . decodeBase64 ( elem . getKey ( ) ) ; DLSequence rawCertId = ( DLSequenc...
Decodes OCSP Response Cache key from JSON
152,082
private static ObjectNode encodeCacheToJSON ( ) { try { ObjectNode out = OBJECT_MAPPER . createObjectNode ( ) ; for ( Map . Entry < OcspResponseCacheKey , SFPair < Long , String > > elem : OCSP_RESPONSE_CACHE . entrySet ( ) ) { OcspResponseCacheKey key = elem . getKey ( ) ; SFPair < Long , String > value0 = elem . getV...
Encode OCSP Response Cache to JSON
152,083
private void validateRevocationStatusMain ( SFPair < Certificate , Certificate > pairIssuerSubject , String ocspRespB64 ) throws CertificateException { try { OCSPResp ocspResp = b64ToOCSPResp ( ocspRespB64 ) ; Date currentTime = new Date ( ) ; BasicOCSPResp basicOcspResp = ( BasicOCSPResp ) ( ocspResp . getResponseObje...
Validates the certificate revocation status
152,084
private void validateBasicOcspResponse ( Date currentTime , BasicOCSPResp basicOcspResp ) throws CertificateEncodingException { for ( SingleResp singleResps : basicOcspResp . getResponses ( ) ) { Date thisUpdate = singleResps . getThisUpdate ( ) ; Date nextUpdate = singleResps . getNextUpdate ( ) ; LOGGER . debug ( "Cu...
Validates OCSP Basic OCSP response .
152,085
private static void verifySignature ( X509CertificateHolder cert , byte [ ] sig , byte [ ] data , AlgorithmIdentifier idf ) throws CertificateException { try { String algorithm = SIGNATURE_OID_TO_STRING . get ( idf . getAlgorithm ( ) ) ; if ( algorithm == null ) { throw new NoSuchAlgorithmException ( String . format ( ...
Verifies the signature of the data
152,086
private static String byteToHexString ( byte [ ] bytes ) { final char [ ] hexArray = "0123456789ABCDEF" . toCharArray ( ) ; char [ ] hexChars = new char [ bytes . length * 2 ] ; for ( int j = 0 ; j < bytes . length ; j ++ ) { int v = bytes [ j ] & 0xFF ; hexChars [ j * 2 ] = hexArray [ v >>> 4 ] ; hexChars [ j * 2 + 1 ...
Converts Byte array to hex string
152,087
private OCSPReq createRequest ( SFPair < Certificate , Certificate > pairIssuerSubject ) { Certificate issuer = pairIssuerSubject . left ; Certificate subject = pairIssuerSubject . right ; OCSPReqBuilder gen = new OCSPReqBuilder ( ) ; try { DigestCalculator digest = new SHA1DigestCalculator ( ) ; X509CertificateHolder ...
Creates a OCSP Request
152,088
private List < Certificate > convertToBouncyCastleCertificate ( X509Certificate [ ] chain ) { final List < Certificate > bcChain = new ArrayList < > ( ) ; for ( X509Certificate cert : chain ) { try { bcChain . add ( Certificate . getInstance ( cert . getEncoded ( ) ) ) ; } catch ( CertificateEncodingException ex ) { th...
Converts X509Certificate to Bouncy Castle Certificate
152,089
private List < SFPair < Certificate , Certificate > > getPairIssuerSubject ( List < Certificate > bcChain ) { List < SFPair < Certificate , Certificate > > pairIssuerSubject = new ArrayList < > ( ) ; for ( int i = 0 , len = bcChain . size ( ) ; i < len ; ++ i ) { Certificate bcCert = bcChain . get ( i ) ; if ( bcCert ....
Creates a pair of Issuer and Subject certificates
152,090
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 .
152,091
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
152,092
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
152,093
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
152,094
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
152,095
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
152,096
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
152,097
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
152,098
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
152,099
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