idx
int64 0
165k
| question
stringlengths 73
4.15k
| target
stringlengths 5
918
| len_question
int64 21
890
| len_target
int64 3
255
|
|---|---|---|---|---|
151,700
|
private static boolean registerMissingProperty ( String name ) { final boolean previouslyReported = ! PropertiesManager . missingProperties . add ( name ) ; if ( ! previouslyReported && log . isInfoEnabled ( ) ) { log . info ( "Property [" + name + "] was requested but not found." ) ; } return previouslyReported ; }
|
Registers that a given property was sought but not found . Currently adds the property to the set of missing properties and logs if this is the first time the property has been requested .
| 73
| 36
|
151,701
|
public static String getProperty ( String name , String defaultValue ) { if ( PropertiesManager . props == null ) loadProps ( ) ; String returnValue = defaultValue ; try { returnValue = getProperty ( name ) ; } catch ( MissingPropertyException mpe ) { // Do nothing, since we have already recorded and logged the missing property. } return returnValue ; }
|
Get the value of the property with the given name . If the named property is not found returns the supplied default value . This error handling behavior makes this method attractive for use in static initializers .
| 78
| 39
|
151,702
|
public static boolean getPropertyAsBoolean ( final String name , final boolean defaultValue ) { if ( PropertiesManager . props == null ) loadProps ( ) ; boolean returnValue = defaultValue ; try { returnValue = getPropertyAsBoolean ( name ) ; } catch ( MissingPropertyException mpe ) { // do nothing, since we already logged the missing property } return returnValue ; }
|
Get a property as a boolean specifying a default value . If for any reason we are unable to lookup the desired property this method returns the supplied default value . This error handling behavior makes this method suitable for calling from static initializers .
| 82
| 46
|
151,703
|
public static byte getPropertyAsByte ( final String name , final byte defaultValue ) { if ( PropertiesManager . props == null ) loadProps ( ) ; byte returnValue = defaultValue ; try { returnValue = getPropertyAsByte ( name ) ; } catch ( Throwable t ) { log . error ( "Could not retrieve or parse as byte property [" + name + "], defaulting to [" + defaultValue + "]" , t ) ; } return returnValue ; }
|
Get the value of the given property as a byte specifying a fallback default value . If for any reason we are unable to lookup the desired property this method returns the supplied default value . This error handling behavior makes this method suitable for calling from static initializers .
| 100
| 52
|
151,704
|
public static Version parseVersion ( String versionString ) { final Matcher versionMatcher = VERSION_PATTERN . matcher ( versionString ) ; if ( ! versionMatcher . matches ( ) ) { return null ; } final int major = Integer . parseInt ( versionMatcher . group ( 1 ) ) ; final int minor = Integer . parseInt ( versionMatcher . group ( 2 ) ) ; final int patch = Integer . parseInt ( versionMatcher . group ( 3 ) ) ; final String local = versionMatcher . group ( 4 ) ; if ( local != null ) { return new SimpleVersion ( major , minor , patch , Integer . valueOf ( local ) ) ; } return new SimpleVersion ( major , minor , patch ) ; }
|
Parse a version string into a Version object if the string doesn t match the pattern null is returned .
| 159
| 21
|
151,705
|
public static Version . Field getMostSpecificMatchingField ( Version v1 , Version v2 ) { if ( v1 . getMajor ( ) != v2 . getMajor ( ) ) { return null ; } if ( v1 . getMinor ( ) != v2 . getMinor ( ) ) { return Version . Field . MAJOR ; } if ( v1 . getPatch ( ) != v2 . getPatch ( ) ) { return Version . Field . MINOR ; } final Integer l1 = v1 . getLocal ( ) ; final Integer l2 = v2 . getLocal ( ) ; if ( l1 != l2 && ( l1 == null || l2 == null || ! l1 . equals ( l2 ) ) ) { return Version . Field . PATCH ; } return Version . Field . LOCAL ; }
|
Determine how much of two versions match . Returns null if the versions do not match at all .
| 176
| 21
|
151,706
|
public UrlStringBuilder setParameter ( String name , String ... values ) { this . setParameter ( name , values != null ? Arrays . asList ( values ) : null ) ; return this ; }
|
Sets a URL parameter replacing any existing parameter with the same name .
| 43
| 14
|
151,707
|
public UrlStringBuilder addParameter ( String name , String ... values ) { this . addParameter ( name , values != null ? Arrays . asList ( values ) : null ) ; return this ; }
|
Adds to a URL parameter if a parameter with the same name already exists its values are added to
| 43
| 19
|
151,708
|
public UrlStringBuilder setParameters ( String namespace , Map < String , List < String > > parameters ) { for ( final String name : parameters . keySet ( ) ) { Validate . notNull ( name , "parameter map cannot contain any null keys" ) ; } this . parameters . clear ( ) ; this . addParameters ( namespace , parameters ) ; return this ; }
|
Removes all existing parameters and sets the contents of the specified Map as the parameters .
| 80
| 17
|
151,709
|
public UrlStringBuilder setPath ( String ... elements ) { Validate . noNullElements ( elements , "elements cannot be null" ) ; this . path . clear ( ) ; this . addPath ( elements ) ; return this ; }
|
Removes any existing path elements and sets the provided elements as the path
| 52
| 14
|
151,710
|
public UrlStringBuilder addPath ( String element ) { Validate . notNull ( element , "element cannot be null" ) ; this . path . add ( element ) ; return this ; }
|
Adds a single element to the path .
| 41
| 8
|
151,711
|
public UrlStringBuilder addPath ( String ... elements ) { Validate . noNullElements ( elements , "elements cannot be null" ) ; for ( final String element : elements ) { this . path . add ( element ) ; } return this ; }
|
Adds the provided elements to the path
| 55
| 7
|
151,712
|
@ SuppressWarnings ( "unchecked" ) protected Map < String , IPortletPreference > getSessionPreferences ( IPortletEntityId portletEntityId , HttpServletRequest httpServletRequest ) { final HttpSession session = httpServletRequest . getSession ( ) ; final Map < IPortletEntityId , Map < String , IPortletPreference > > portletPreferences ; // Sync on the session to ensure the Map isn't in the process of being created synchronized ( session ) { portletPreferences = ( Map < IPortletEntityId , Map < String , IPortletPreference > > ) session . getAttribute ( PORTLET_PREFERENCES_MAP_ATTRIBUTE ) ; } if ( portletPreferences == null ) { return null ; } return portletPreferences . get ( portletEntityId ) ; }
|
Gets the session - stored list of IPortletPreferences for the specified request and IPortletEntityId .
| 190
| 24
|
151,713
|
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 ; // get an authorization principal for the current requesting user HttpServletRequest servletRequest = portalRequestUtils . getPortletHttpRequest ( request ) ; IPerson currentUser = personManager . getPerson ( servletRequest ) ; // get the set of people matching the search query people = this . lookupHelper . searchForPeople ( currentUser , queryAttributes ) ; log . debug ( "Directory portlet search outcome:\n\tqueryAttributes=" + queryAttributes + "\n\tsearchResult=" + people ) ; return people ; }
|
Search the directory for people matching the search query . Search results will be scoped to the permissions of the user performing the search .
| 182
| 26
|
151,714
|
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 .
| 53
| 11
|
151,715
|
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 .
| 62
| 26
|
151,716
|
protected IPortletEntity wrapEntity ( IPortletEntity portletEntity ) { if ( portletEntity == null ) { return null ; } final String persistentLayoutNodeId = portletEntity . getLayoutNodeId ( ) ; if ( persistentLayoutNodeId . startsWith ( TransientUserLayoutManagerWrapper . SUBSCRIBE_PREFIX ) ) { final IUserLayoutManager userLayoutManager = this . getUserLayoutManager ( ) ; if ( userLayoutManager == null ) { this . logger . warn ( "Could not find IUserLayoutManager when trying to wrap transient portlet entity: " + portletEntity ) ; return portletEntity ; } final IPortletDefinition portletDefinition = portletEntity . getPortletDefinition ( ) ; final String fname = portletDefinition . getFName ( ) ; final String layoutNodeId = userLayoutManager . getSubscribeId ( fname ) ; return new TransientPortletEntity ( portletEntity , layoutNodeId ) ; } return portletEntity ; }
|
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 .
| 218
| 55
|
151,717
|
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 != HttpURLConnection . HTTP_OK ) { throw new IOException ( String . format ( "URL %s did not return a valid response code while attempting to connect. Expected: %d. Received: %d" , url , HttpURLConnection . HTTP_OK , response ) ) ; } isValid = true ; } catch ( IOException e ) { logger . warn ( "A problem happened while trying to verify url: {} Error Message: {}" , url , e . getMessage ( ) ) ; } finally { if ( huc != null ) { huc . disconnect ( ) ; } ; } return isValid ; }
|
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 .
| 221
| 42
|
151,718
|
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 .
| 70
| 20
|
151,719
|
@ EventListener public void init ( ContextRefreshedEvent event ) { idTokenFactory = context . getBean ( IdTokenFactory . class ) ; // Make sure we have a guestUsernameSelectors collection & sort it if ( guestUsernameSelectors == null ) { guestUsernameSelectors = Collections . emptyList ( ) ; } Collections . sort ( guestUsernameSelectors ) ; }
|
To avoid circular reference issues this bean obtains its dependencies when the context finishes starting .
| 84
| 17
|
151,720
|
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 . parse ( value ) ; final Charset charset = contentType . getCharset ( ) ; if ( charset != null ) { this . portletResourceOutputHandler . setCharacterEncoding ( charset . name ( ) ) ; } this . portletResourceOutputHandler . setContentType ( contentType . getMimeType ( ) ) ; return true ; } if ( "Content-Length" . equals ( key ) ) { this . portletResourceOutputHandler . setContentLength ( Integer . parseInt ( value ) ) ; return true ; } if ( "Content-Language" . equals ( key ) ) { final HeaderElement [ ] parts = BasicHeaderValueParser . parseElements ( value , null ) ; if ( parts . length > 0 ) { final String localeStr = parts [ 0 ] . getValue ( ) ; final Locale locale = LocaleUtils . toLocale ( localeStr ) ; this . portletResourceOutputHandler . setLocale ( locale ) ; return true ; } } return false ; }
|
Handles resource response specific headers . Returns true if the header was consumed by this method and requires no further processing
| 298
| 22
|
151,721
|
@ Override public void perform ( ) throws PortalException { // push the change into the PLF if ( nodeId . startsWith ( Constants . FRAGMENT_ID_USER_PREFIX ) ) { // remove the parm edit ParameterEditManager . removeParmEditDirective ( nodeId , name , person ) ; } // push the fragment value into the ILF 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 .
| 101
| 43
|
151,722
|
@ Override 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 ( ) ) log . debug ( "RDBMPermissionImpl.add(): " + ps ) ; rc = ps . executeUpdate ( ) ; if ( rc != 1 ) { throw new AuthorizationException ( "Problem adding Permission " + perm ) ; } } finally { ps . close ( ) ; } } catch ( Exception ex ) { log . error ( "Exception adding permission [" + perm + "]" , ex ) ; throw new AuthorizationException ( "Problem adding Permission " + perm ) ; } finally { RDBMServices . releaseConnection ( conn ) ; } }
|
Add the IPermission to the store .
| 206
| 9
|
151,723
|
@ Override 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 " + Arrays . toString ( perms ) , ex ) ; } } }
|
Delete the IPermissions from the store .
| 95
| 9
|
151,724
|
@ Override 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 ( ) ; } } catch ( Exception ex ) { log . error ( "Exception deleting permission [" + perm + "]" , ex ) ; throw new AuthorizationException ( "Problem deleting Permission " + perm , ex ) ; } finally { RDBMServices . releaseConnection ( conn ) ; } }
|
Delete a single IPermission from the store .
| 142
| 10
|
151,725
|
private int getPrincipalType ( String principalString ) { return Integer . parseInt ( principalString . substring ( 0 , principalString . indexOf ( PRINCIPAL_SEPARATOR ) ) ) ; }
|
Returns the principal type portion of the principal .
| 45
| 9
|
151,726
|
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 ( 5 , perm . getTarget ( ) ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "RDBMPermissionImpl.primDelete(): " + ps ) ; return ps . executeUpdate ( ) ; }
|
Set the params on the PreparedStatement and execute the delete .
| 141
| 13
|
151,727
|
private int primUpdate ( IPermission perm , PreparedStatement ps ) throws Exception { java . sql . Timestamp ts = null ; // UPDATE COLUMNS: ps . clearParameters ( ) ; // TYPE: if ( perm . getType ( ) == null ) { ps . setNull ( 1 , Types . VARCHAR ) ; } else { ps . setString ( 1 , perm . getType ( ) ) ; } // EFFECTIVE: if ( perm . getEffective ( ) == null ) { ps . setNull ( 2 , Types . TIMESTAMP ) ; } else { ts = new java . sql . Timestamp ( perm . getEffective ( ) . getTime ( ) ) ; ps . setTimestamp ( 2 , ts ) ; } // EXPIRES: if ( perm . getExpires ( ) == null ) { ps . setNull ( 3 , Types . TIMESTAMP ) ; } else { ts = new java . sql . Timestamp ( perm . getExpires ( ) . getTime ( ) ) ; ps . setTimestamp ( 3 , ts ) ; } // WHERE COLUMNS: ps . setString ( 4 , perm . getOwner ( ) ) ; ps . setInt ( 5 , getPrincipalType ( perm ) ) ; ps . setString ( 6 , getPrincipalKey ( perm ) ) ; ps . setString ( 7 , perm . getActivity ( ) ) ; ps . setString ( 8 , perm . getTarget ( ) ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "RDBMPermissionImpl.primUpdate(): " + ps ) ; return ps . executeUpdate ( ) ; }
|
Set the params on the PreparedStatement and execute the update .
| 351
| 13
|
151,728
|
@ Override 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 ( owner , principal , activity , target , type ) ; try { conn = RDBMServices . getConnection ( ) ; stmt = conn . prepareStatement ( query ) ; prepareSelectQuery ( stmt , owner , principal , activity , target , type ) ; try { rs = stmt . executeQuery ( ) ; try { while ( rs . next ( ) ) { perms . add ( instanceFromResultSet ( rs ) ) ; } } finally { rs . close ( ) ; } } finally { stmt . close ( ) ; } } catch ( SQLException sqle ) { log . error ( "Problem retrieving permissions" , sqle ) ; throw new AuthorizationException ( "Problem retrieving Permissions [" + sqle . getMessage ( ) + "] for query=[" + query + "] for owner=[" + owner + "] and principal=[" + principal + "] and activity=[" + activity + "] and target=[" + target + "] and type=[" + type + "]" , sqle ) ; } finally { RDBMServices . releaseConnection ( conn ) ; } if ( log . isTraceEnabled ( ) ) { log . trace ( "RDBMPermissionImpl.select(): [" + query + "] for owner=[" + owner + "] and principal=[" + principal + "] and activity=[" + activity + "] and target=[" + target + "] and type=[" + type + "] returned permissions [" + perms + "]" ) ; } return ( ( IPermission [ ] ) perms . toArray ( new IPermission [ perms . size ( ) ] ) ) ; }
|
Select the Permissions from the store .
| 432
| 8
|
151,729
|
@ Override 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 . prepareStatement ( sQuery ) ; try { primUpdate ( perm , ps ) ; } finally { ps . close ( ) ; } } catch ( Exception ex ) { log . error ( "Exception updating permission [" + perm + "]" , ex ) ; throw new AuthorizationException ( "Problem updating Permission " + perm ) ; } finally { RDBMServices . releaseConnection ( conn ) ; } }
|
Update a single IPermission in the store .
| 170
| 10
|
151,730
|
@ Override public PortletEventQueue getPortletEventQueue ( HttpServletRequest request ) { request = this . portalRequestUtils . getOriginalPortalRequest ( request ) ; synchronized ( PortalWebUtils . getRequestAttributeMutex ( request ) ) { PortletEventQueue portletEventQueue = ( PortletEventQueue ) request . getAttribute ( PORTLET_EVENT_QUEUE ) ; if ( portletEventQueue == null ) { portletEventQueue = new PortletEventQueue ( ) ; request . setAttribute ( PORTLET_EVENT_QUEUE , portletEventQueue ) ; } return portletEventQueue ; } }
|
Returns a request scoped PortletEventQueue used to track events to process and events to dispatch
| 143
| 19
|
151,731
|
protected HttpServletRequest getServletRequestFromExternalContext ( ExternalContext externalContext ) { Object request = externalContext . getNativeRequest ( ) ; if ( request instanceof PortletRequest ) { return portalRequestUtils . getPortletHttpRequest ( ( PortletRequest ) externalContext . getNativeRequest ( ) ) ; } else if ( request instanceof HttpServletRequest ) { return ( HttpServletRequest ) request ; } // give up and throw an error else { throw new IllegalArgumentException ( "Unable to recognize the native request associated with the supplied external context" ) ; } }
|
Get the HttpServletRequest associated with the supplied ExternalContext .
| 129
| 14
|
151,732
|
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, " + "attempting to get a channel definition using functional name: " + fname ) ; try { chanDef = PortletDefinitionRegistryLocator . getPortletDefinitionRegistry ( ) . getPortletDefinitionByFname ( fname ) ; } catch ( Exception e ) { throw new PortalException ( "Failed to get channel information " + "for subscribeId: " + subId ) ; } mChanMap . put ( subId , chanDef ) ; } return chanDef ; }
|
Given a subscribe Id return a ChannelDefinition .
| 193
| 9
|
151,733
|
@ Override public String getSubscribeId ( String fname ) throws PortalException { // see if a given subscribe id is already in the map String subId = mFnameMap . get ( fname ) ; if ( subId == null ) { // see if a given subscribe id is already in the layout subId = man . getSubscribeId ( fname ) ; } // obtain a description of the transient channel and // assign a new transient channel id if ( subId == null ) { try { IPortletDefinition chanDef = PortletDefinitionRegistryLocator . getPortletDefinitionRegistry ( ) . getPortletDefinitionByFname ( fname ) ; if ( chanDef != null ) { // assign a new id subId = getNextSubscribeId ( ) ; mFnameMap . put ( fname , subId ) ; mSubIdMap . put ( subId , fname ) ; mChanMap . put ( subId , chanDef ) ; } } catch ( Exception e ) { log . error ( "TransientUserLayoutManagerWrapper::getSubscribeId() : " + "an exception encountered while trying to obtain " + "ChannelDefinition for fname \"" + fname + "\" : " + e ) ; subId = null ; } } return subId ; }
|
Given an functional name return its subscribe id .
| 277
| 9
|
151,734
|
private IUserLayoutChannelDescription getTransientNode ( String nodeId ) throws PortalException { // get fname from subscribe id final String fname = getFname ( nodeId ) ; if ( null == fname || fname . equals ( "" ) ) { return null ; } try { // check cache first IPortletDefinition chanDef = mChanMap . get ( nodeId ) ; if ( null == chanDef ) { chanDef = PortletDefinitionRegistryLocator . getPortletDefinitionRegistry ( ) . getPortletDefinitionByFname ( fname ) ; mChanMap . put ( nodeId , chanDef ) ; } return createUserLayoutChannelDescription ( nodeId , chanDef ) ; } catch ( Exception e ) { throw new PortalException ( "Failed to obtain channel definition using fname: " + fname ) ; } }
|
Return an IUserLayoutChannelDescription by way of nodeId
| 186
| 12
|
151,735
|
@ Override 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 ( "LRS provider successfully sent to {}, statement: {}" , LRSUrl , statement ) ; } else { logger . error ( "LRS provider failed to send to {}, statement: {}" , LRSUrl , statement ) ; logger . error ( "- Response: {}" , response ) ; return false ; } return true ; }
|
Actually send an event to the provider .
| 160
| 8
|
151,736
|
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 = propertyResolver . getProperty ( format ( PROPERTY_FORMAT , id , "actor-email" ) , actorEmail ) ; activityId = propertyResolver . getProperty ( format ( PROPERTY_FORMAT , id , "activity-id" ) , activityId ) ; stateId = propertyResolver . getProperty ( format ( PROPERTY_FORMAT , id , "state-id" ) , stateId ) ; formEncodeActivityData = propertyResolver . getProperty ( format ( PROPERTY_FORMAT , id , "form-encode-activity-data" ) , Boolean . class , formEncodeActivityData ) ; activitiesFormParamName = propertyResolver . getProperty ( format ( PROPERTY_FORMAT , id , "activity-form-param-name" ) , activitiesFormParamName ) ; if ( StringUtils . isEmpty ( LRSUrl ) ) { logger . error ( "Disabling TinCan API interface. Property {} not set!" , urlProp ) ; enabled = false ; return ; } // strip trailing '/' if included LRSUrl = LRSUrl . replaceAll ( "/*$" , "" ) ; }
|
Read the LRS config .
| 340
| 6
|
151,737
|
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 ) ; // make multipart data is handled correctly. if ( postData instanceof MultiValueMap ) { headers . setContentType ( MediaType . MULTIPART_FORM_DATA ) ; } URI fullURI = buildRequestURI ( pathFragment , getParams ) ; HttpEntity < ? > entity = new HttpEntity <> ( postData , headers ) ; ResponseEntity < T > response = restTemplate . exchange ( fullURI , method , entity , returnType ) ; return response ; }
|
Send a request to the LRS .
| 186
| 8
|
151,738
|
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 fullURI ; } catch ( URISyntaxException e ) { throw new RuntimeException ( "Error creating request URI" , e ) ; } }
|
Build a URI for the REST request .
| 122
| 8
|
151,739
|
@ Override protected void bindAggregationSpecificKeyParameters ( TypedQuery < PortletExecutionAggregationImpl > query , Set < PortletExecutionAggregationKey > keys ) { query . setParameter ( this . portletMappingParameter , extractAggregatePortletMappings ( keys ) ) ; query . setParameter ( this . executionTypeParameter , extractExecutionTypes ( keys ) ) ; }
|
The execution type is obtained from the first PortletExecutionAggregationKey .
| 85
| 16
|
151,740
|
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 .
| 59
| 18
|
151,741
|
protected EntityManagerFactory getEntityManagerFactory ( OpenEntityManager openEntityManager ) { final CacheKey key = this . createEntityManagerFactoryKey ( openEntityManager ) ; EntityManagerFactory emf = this . entityManagerFactories . get ( key ) ; if ( emf == null ) { emf = this . lookupEntityManagerFactory ( openEntityManager ) ; this . entityManagerFactories . put ( key , emf ) ; } return emf ; }
|
Get the EntityManagerFactory that this filter should use .
| 97
| 11
|
151,742
|
protected EntityManagerFactory lookupEntityManagerFactory ( OpenEntityManager openEntityManager ) { String emfBeanName = openEntityManager . name ( ) ; String puName = openEntityManager . unitName ( ) ; if ( StringUtils . hasLength ( emfBeanName ) ) { return this . applicationContext . getBean ( emfBeanName , EntityManagerFactory . class ) ; } else if ( ! StringUtils . hasLength ( puName ) && this . applicationContext . containsBean ( OpenEntityManagerInViewFilter . DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME ) ) { return this . applicationContext . getBean ( OpenEntityManagerInViewFilter . DEFAULT_ENTITY_MANAGER_FACTORY_BEAN_NAME , EntityManagerFactory . class ) ; } else { // Includes fallback search for single EntityManagerFactory bean by type. return EntityManagerFactoryUtils . findEntityManagerFactory ( this . applicationContext , puName ) ; } }
|
Look up the EntityManagerFactory that this filter should use .
| 221
| 12
|
151,743
|
@ Override 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 .
| 43
| 30
|
151,744
|
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
| 51
| 7
|
151,745
|
@ Override public synchronized Object get ( Object key ) { ValueWrapper valueWrapper = ( ValueWrapper ) super . get ( key ) ; if ( valueWrapper != null ) { // Check if value has expired long creationTime = valueWrapper . getCreationTime ( ) ; long cacheInterval = valueWrapper . getCacheInterval ( ) ; long currentTime = System . currentTimeMillis ( ) ; if ( cacheInterval >= 0 && creationTime + cacheInterval < currentTime ) { remove ( key ) ; return null ; } return valueWrapper . getValue ( ) ; } else return null ; }
|
Get an object from the cache .
| 134
| 7
|
151,746
|
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 . getCacheInterval ( ) ; long currentTime = System . currentTimeMillis ( ) ; if ( cacheInterval >= 0 && creationTime + cacheInterval < currentTime ) { remove ( key ) ; } } }
|
Removes from the cache values which have expired .
| 133
| 10
|
151,747
|
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 .
| 40
| 16
|
151,748
|
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 = result . trim ( ) ; return result ; }
|
Return the lower case trimmed value of the media type from the content type .
| 101
| 15
|
151,749
|
public void endParsing ( ) throws SnowflakeSQLException { if ( partialEscapedUnicode . position ( ) > 0 ) { partialEscapedUnicode . flip ( ) ; continueParsingInternal ( partialEscapedUnicode , true ) ; partialEscapedUnicode . clear ( ) ; } if ( state != State . ROW_FINISHED ) { throw new SnowflakeSQLException ( SqlState . INTERNAL_ERROR , ErrorCode . INTERNAL_ERROR . getMessageCode ( ) , "SFResultJsonParser2Failed: Chunk is truncated!" ) ; } currentColumn = 0 ; state = State . UNINITIALIZED ; }
|
Check if the chunk has been parsed correctly . After calling this it is safe to acquire the output data
| 157
| 20
|
151,750
|
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 stopped during a \\u, continue here if ( partialEscapedUnicode . position ( ) > 0 ) { int lenToCopy = Math . min ( 12 - partialEscapedUnicode . position ( ) , in . remaining ( ) ) ; if ( lenToCopy > partialEscapedUnicode . remaining ( ) ) { resizePartialEscapedUnicode ( lenToCopy ) ; } partialEscapedUnicode . put ( in . array ( ) , in . arrayOffset ( ) + in . position ( ) , lenToCopy ) ; in . position ( in . position ( ) + lenToCopy ) ; if ( partialEscapedUnicode . position ( ) < 12 ) { // Not enough data to parse escaped unicode return ; } ByteBuffer toBeParsed = partialEscapedUnicode . duplicate ( ) ; toBeParsed . flip ( ) ; continueParsingInternal ( toBeParsed , false ) ; partialEscapedUnicode . clear ( ) ; } continueParsingInternal ( in , false ) ; }
|
Continue parsing with the given data
| 313
| 6
|
151,751
|
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" ) ; AssertUtil . assertTrue ( stmtInput . mediaType != null , "Missing media type for statement execution" ) ; AssertUtil . assertTrue ( stmtInput . requestId != null , "Missing request id for statement execution" ) ; AssertUtil . assertTrue ( stmtInput . sessionToken != null , "Missing session token for statement execution" ) ; try { URIBuilder uriBuilder = new URIBuilder ( stmtInput . serverUrl ) ; logger . debug ( "Aborting query: {}" , stmtInput . sql ) ; uriBuilder . setPath ( SF_PATH_ABORT_REQUEST_V1 ) ; uriBuilder . addParameter ( SF_QUERY_REQUEST_ID , UUID . randomUUID ( ) . toString ( ) ) ; httpRequest = new HttpPost ( uriBuilder . build ( ) ) ; /* * The JSON input has two fields: sqlText and requestId */ Map sqlJsonBody = new HashMap < String , Object > ( ) ; sqlJsonBody . put ( "sqlText" , stmtInput . sql ) ; sqlJsonBody . put ( "requestId" , stmtInput . requestId ) ; String json = mapper . writeValueAsString ( sqlJsonBody ) ; logger . debug ( "JSON for cancel request: {}" , json ) ; StringEntity input = new StringEntity ( json , Charset . forName ( "UTF-8" ) ) ; input . setContentType ( "application/json" ) ; httpRequest . setEntity ( input ) ; httpRequest . addHeader ( "accept" , stmtInput . mediaType ) ; httpRequest . setHeader ( SF_HEADER_AUTHORIZATION , SF_HEADER_SNOWFLAKE_AUTHTYPE + " " + SF_HEADER_TOKEN_TAG + "=\"" + stmtInput . sessionToken + "\"" ) ; setServiceNameHeader ( stmtInput , httpRequest ) ; String jsonString = HttpUtil . executeRequest ( httpRequest , SF_CANCELING_RETRY_TIMEOUT_IN_MILLIS , 0 , null ) ; // trace the response if requested logger . debug ( "Json response: {}" , jsonString ) ; JsonNode rootNode = null ; rootNode = mapper . readTree ( jsonString ) ; // raise server side error as an exception if any SnowflakeUtil . checkErrorAndThrowException ( rootNode ) ; } catch ( URISyntaxException | IOException ex ) { logger . error ( "Exception encountered when canceling " + httpRequest , ex ) ; // raise internal exception if this is not a snowflake exception throw new SFException ( ex , ErrorCode . INTERNAL_ERROR , ex . getLocalizedMessage ( ) ) ; } }
|
Cancel a statement identifiable by a request id
| 697
| 9
|
151,752
|
static public SFStatementType checkStageManageCommand ( String sql ) { if ( sql == null ) { return null ; } String trimmedSql = sql . trim ( ) ; // skip commenting prefixed with // while ( trimmedSql . startsWith ( "//" ) ) { logger . debug ( "skipping // comments in: \n{}" , trimmedSql ) ; if ( trimmedSql . indexOf ( ' ' ) > 0 ) { trimmedSql = trimmedSql . substring ( trimmedSql . indexOf ( ' ' ) ) ; trimmedSql = trimmedSql . trim ( ) ; } else { break ; } logger . debug ( "New sql after skipping // comments: \n{}" , trimmedSql ) ; } // skip commenting enclosed with /* */ while ( trimmedSql . startsWith ( "/*" ) ) { logger . debug ( "skipping /* */ comments in: \n{}" , trimmedSql ) ; if ( trimmedSql . indexOf ( "*/" ) > 0 ) { trimmedSql = trimmedSql . substring ( trimmedSql . indexOf ( "*/" ) + 2 ) ; trimmedSql = trimmedSql . trim ( ) ; } else { break ; } logger . debug ( "New sql after skipping /* */ comments: \n{}" , trimmedSql ) ; } trimmedSql = trimmedSql . toLowerCase ( ) ; if ( trimmedSql . startsWith ( "put " ) ) { return SFStatementType . PUT ; } else if ( trimmedSql . startsWith ( "get " ) ) { return SFStatementType . GET ; } else if ( trimmedSql . startsWith ( "ls " ) || trimmedSql . startsWith ( "list " ) ) { return SFStatementType . LIST ; } else if ( trimmedSql . startsWith ( "rm " ) || trimmedSql . startsWith ( "remove " ) ) { return SFStatementType . REMOVE ; } else { return null ; } }
|
A simple function to check if the statement is related to manipulate stage .
| 432
| 14
|
151,753
|
public void flush ( ) { if ( ! enabled ) { return ; } if ( ! queue . isEmpty ( ) ) { // start a new thread to upload without blocking the current thread Runnable runUpload = new TelemetryUploader ( this , exportQueueToString ( ) ) ; uploader . execute ( runUpload ) ; } }
|
force to flush events in the queue
| 71
| 7
|
151,754
|
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
| 62
| 10
|
151,755
|
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 retryTimeout , int retryCount , String sqlState , int errorCode ) { if ( enabled ) { TelemetryEvent . LogBuilder logBuilder = new TelemetryEvent . LogBuilder ( ) ; JSONObject value = new JSONObject ( ) ; value . put ( "request" , request . toString ( ) ) ; value . put ( "retryTimeout" , retryTimeout ) ; value . put ( "injectSocketTimeout" , injectSocketTimeout ) ; value . put ( "canceling" , canceling == null ? "null" : canceling . get ( ) ) ; value . put ( "withoutCookies" , withoutCookies ) ; value . put ( "includeRetryParameters" , includeRetryParameters ) ; value . put ( "includeRequestGuid" , includeRequestGuid ) ; value . put ( "breakRetryReason" , breakRetryReason ) ; value . put ( "retryTimeout" , retryTimeout ) ; value . put ( "retryCount" , retryCount ) ; value . put ( "sqlState" , sqlState ) ; value . put ( "errorCode" , errorCode ) ; int responseStatusCode = - 1 ; if ( response != null ) { value . put ( "response" , response . toString ( ) ) ; value . put ( "responseStatusLine" , response . getStatusLine ( ) . toString ( ) ) ; if ( response . getStatusLine ( ) != null ) { responseStatusCode = response . getStatusLine ( ) . getStatusCode ( ) ; value . put ( "responseStatusCode" , responseStatusCode ) ; } } else { value . put ( "response" , null ) ; } if ( savedEx != null ) { value . put ( "exceptionMessage" , savedEx . getLocalizedMessage ( ) ) ; StringWriter sw = new StringWriter ( ) ; savedEx . printStackTrace ( new PrintWriter ( sw ) ) ; value . put ( "exceptionStackTrace" , sw . toString ( ) ) ; } TelemetryEvent log = logBuilder . withName ( eventName ) . withValue ( value ) . withTag ( "sqlState" , sqlState ) . withTag ( "errorCode" , errorCode ) . withTag ( "responseStatusCode" , responseStatusCode ) . build ( ) ; this . add ( log ) ; } }
|
log error http response to telemetry
| 578
| 7
|
151,756
|
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
| 60
| 9
|
151,757
|
public final void ensureRowsComplete ( ) throws SnowflakeSQLException { // Check that all the rows have been decoded, raise an error if not 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 .
| 99
| 11
|
151,758
|
static CloseableHttpClient buildHttpClient ( boolean insecureMode , File ocspCacheFile , boolean useOcspCacheServer ) { // set timeout so that we don't wait forever. // Setup the default configuration for all requests on this client DefaultRequestConfig = RequestConfig . custom ( ) . setConnectTimeout ( DEFAULT_CONNECTION_TIMEOUT ) . setConnectionRequestTimeout ( DEFAULT_CONNECTION_TIMEOUT ) . setSocketTimeout ( DEFAULT_HTTP_CLIENT_SOCKET_TIMEOUT ) . build ( ) ; TrustManager [ ] trustManagers = null ; if ( ! insecureMode ) { // A custom TrustManager is required only if insecureMode is disabled, // which is by default in the production. insecureMode can be enabled // 1) OCSP service is down for reasons, 2) PowerMock test tht doesn't // care OCSP checks. TrustManager [ ] tm = { new SFTrustManager ( ocspCacheFile , useOcspCacheServer ) } ; trustManagers = tm ; } try { Registry < ConnectionSocketFactory > registry = RegistryBuilder . < ConnectionSocketFactory > create ( ) . register ( "https" , new SFSSLConnectionSocketFactory ( trustManagers , socksProxyDisabled ) ) . register ( "http" , new SFConnectionSocketFactory ( ) ) . build ( ) ; // Build a connection manager with enough connections connectionManager = new PoolingHttpClientConnectionManager ( registry ) ; connectionManager . setMaxTotal ( DEFAULT_MAX_CONNECTIONS ) ; connectionManager . setDefaultMaxPerRoute ( DEFAULT_MAX_CONNECTIONS_PER_ROUTE ) ; if ( useProxy ) { // use the custom proxy properties HttpHost proxy = new HttpHost ( proxyHost , proxyPort ) ; Credentials credentials = new UsernamePasswordCredentials ( proxyUser , proxyPassword ) ; AuthScope authScope = new AuthScope ( proxyHost , proxyPort ) ; CredentialsProvider credentialsProvider = new BasicCredentialsProvider ( ) ; credentialsProvider . setCredentials ( authScope , credentials ) ; SdkProxyRoutePlanner sdkProxyRoutePlanner = new SdkProxyRoutePlanner ( proxyHost , proxyPort , nonProxyHosts ) ; httpClient = HttpClientBuilder . create ( ) . setDefaultRequestConfig ( DefaultRequestConfig ) . setConnectionManager ( connectionManager ) // Support JVM proxy settings . useSystemProperties ( ) . setRedirectStrategy ( new DefaultRedirectStrategy ( ) ) . setUserAgent ( "-" ) // needed for Okta . disableCookieManagement ( ) // SNOW-39748 . setProxy ( proxy ) . setDefaultCredentialsProvider ( credentialsProvider ) . setRoutePlanner ( sdkProxyRoutePlanner ) . build ( ) ; } else { httpClient = HttpClientBuilder . create ( ) . setDefaultRequestConfig ( DefaultRequestConfig ) . setConnectionManager ( connectionManager ) // Support JVM proxy settings . useSystemProperties ( ) . setRedirectStrategy ( new DefaultRedirectStrategy ( ) ) . setUserAgent ( "-" ) // needed for Okta . disableCookieManagement ( ) // SNOW-39748 . build ( ) ; } return httpClient ; } catch ( NoSuchAlgorithmException | KeyManagementException ex ) { throw new SSLInitializationException ( ex . getMessage ( ) , ex ) ; } }
|
Build an Http client using our set of default .
| 731
| 11
|
151,759
|
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 .
| 83
| 9
|
151,760
|
public static RequestConfig getDefaultRequestConfigWithSocketTimeout ( int soTimeoutMs , boolean withoutCookies ) { getHttpClient ( ) ; final String cookieSpec = withoutCookies ? IGNORE_COOKIES : DEFAULT ; return RequestConfig . copy ( DefaultRequestConfig ) . setSocketTimeout ( soTimeoutMs ) . setCookieSpec ( cookieSpec ) . build ( ) ; }
|
Return a request configuration inheriting from the default request configuration of the shared HttpClient with a different socket timeout .
| 82
| 23
|
151,761
|
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
| 70
| 17
|
151,762
|
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 .
| 63
| 9
|
151,763
|
public static void configureCustomProxyProperties ( Map < SFSessionProperty , Object > connectionPropertiesMap ) { if ( connectionPropertiesMap . containsKey ( SFSessionProperty . USE_PROXY ) ) { useProxy = ( boolean ) connectionPropertiesMap . get ( SFSessionProperty . USE_PROXY ) ; } if ( useProxy ) { proxyHost = ( String ) connectionPropertiesMap . get ( SFSessionProperty . PROXY_HOST ) ; proxyPort = Integer . parseInt ( connectionPropertiesMap . get ( SFSessionProperty . PROXY_PORT ) . toString ( ) ) ; proxyUser = ( String ) connectionPropertiesMap . get ( SFSessionProperty . PROXY_USER ) ; proxyPassword = ( String ) connectionPropertiesMap . get ( SFSessionProperty . PROXY_PASSWORD ) ; nonProxyHosts = ( String ) connectionPropertiesMap . get ( SFSessionProperty . NON_PROXY_HOSTS ) ; } }
|
configure custom proxy properties from connectionPropertiesMap
| 216
| 10
|
151,764
|
static private void checkErrorAndThrowExceptionSub ( JsonNode rootNode , boolean raiseReauthenticateError ) throws SnowflakeSQLException { // no need to throw exception if success if ( rootNode . path ( "success" ) . asBoolean ( ) ) { return ; } String errorMessage ; String sqlState ; int errorCode ; String queryId = "unknown" ; // if we have sqlstate in data, it's a sql error if ( ! rootNode . path ( "data" ) . path ( "sqlState" ) . isMissingNode ( ) ) { sqlState = rootNode . path ( "data" ) . path ( "sqlState" ) . asText ( ) ; errorCode = rootNode . path ( "data" ) . path ( "errorCode" ) . asInt ( ) ; queryId = rootNode . path ( "data" ) . path ( "queryId" ) . asText ( ) ; errorMessage = rootNode . path ( "message" ) . asText ( ) ; } else { sqlState = SqlState . INTERNAL_ERROR ; // use internal error sql state // check if there is an error code in the envelope if ( ! rootNode . path ( "code" ) . isMissingNode ( ) ) { errorCode = rootNode . path ( "code" ) . asInt ( ) ; errorMessage = rootNode . path ( "message" ) . asText ( ) ; } else { errorCode = ErrorCode . INTERNAL_ERROR . getMessageCode ( ) ; errorMessage = "no_error_code_from_server" ; try { PrintWriter writer = new PrintWriter ( "output.json" , "UTF-8" ) ; writer . print ( rootNode . toString ( ) ) ; } catch ( Exception ex ) { logger . debug ( "{}" , ex ) ; } } } if ( raiseReauthenticateError ) { switch ( errorCode ) { case ID_TOKEN_EXPIRED_GS_CODE : case SESSION_NOT_EXIST_GS_CODE : case MASTER_TOKEN_NOTFOUND : case MASTER_EXPIRED_GS_CODE : case MASTER_TOKEN_INVALID_GS_CODE : throw new SnowflakeReauthenticationRequest ( queryId , errorMessage , sqlState , errorCode ) ; } } throw new SnowflakeSQLException ( queryId , errorMessage , sqlState , errorCode ) ; }
|
Check the error in the JSON node and generate an exception based on information extracted from the node .
| 531
| 19
|
151,765
|
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 .
| 48
| 17
|
151,766
|
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 . path ( SMK_ID ) ; if ( smkIdNode . isMissingNode ( ) || smkIdNode . isNull ( ) ) { return null ; } String queryId = queryIdNode . asText ( ) ; long smkId = smkIdNode . asLong ( ) ; JsonNode keySizeNode = jsonNode . path ( KEY_SIZE ) ; if ( ! keySizeNode . isMissingNode ( ) && ! keySizeNode . isNull ( ) ) { return new MatDesc ( smkId , queryId , keySizeNode . asInt ( ) ) ; } return new MatDesc ( smkId , queryId ) ; } catch ( Exception ex ) { return null ; } }
|
Try to parse the material descriptor string .
| 249
| 8
|
151,767
|
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
| 79
| 7
|
151,768
|
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" : result = importedKeySetNull ; break ; case "SET DEFAULT" : result = importedKeySetDefault ; break ; case "RESTRICT" : result = importedKeyRestrict ; break ; } case "deferrability" : switch ( property ) { case "INITIALLY DEFERRED" : result = importedKeyInitiallyDeferred ; break ; case "INITIALLY IMMEDIATE" : result = importedKeyInitiallyImmediate ; break ; case "NOT DEFERRABLE" : result = importedKeyNotDeferrable ; break ; } } return result ; }
|
Returns the JDBC standard property string for the property string used in our show constraint commands
| 206
| 17
|
151,769
|
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_DATA ) || e . getSQLState ( ) . equals ( SqlState . BASE_TABLE_OR_VIEW_NOT_FOUND ) ) { return SnowflakeDatabaseMetaDataResultSet . getEmptyResultSet ( metadataType , statement ) ; } else { throw e ; } } return resultSet ; }
|
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
| 148
| 33
|
151,770
|
static private ClientAuthnDTO . AuthenticatorType getAuthenticator ( LoginInput loginInput ) { if ( loginInput . getAuthenticator ( ) != null ) { if ( loginInput . getAuthenticator ( ) . equalsIgnoreCase ( ClientAuthnDTO . AuthenticatorType . EXTERNALBROWSER . name ( ) ) ) { // SAML 2.0 compliant service/application return ClientAuthnDTO . AuthenticatorType . EXTERNALBROWSER ; } else if ( loginInput . getAuthenticator ( ) . equalsIgnoreCase ( ClientAuthnDTO . AuthenticatorType . OAUTH . name ( ) ) ) { // OAuth Authentication return ClientAuthnDTO . AuthenticatorType . OAUTH ; } else if ( loginInput . getAuthenticator ( ) . equalsIgnoreCase ( ClientAuthnDTO . AuthenticatorType . SNOWFLAKE_JWT . name ( ) ) ) { return ClientAuthnDTO . AuthenticatorType . SNOWFLAKE_JWT ; } else if ( ! loginInput . getAuthenticator ( ) . equalsIgnoreCase ( ClientAuthnDTO . AuthenticatorType . SNOWFLAKE . name ( ) ) ) { // OKTA authenticator v1. This will be deprecated once externalbrowser // is in production. return ClientAuthnDTO . AuthenticatorType . OKTA ; } } // authenticator is null, then jdbc will decide authenticator depends on // if privateKey is specified or not. If yes, authenticator type will be // SNOWFLAKE_JWT, otherwise it will use SNOWFLAKE. return loginInput . getPrivateKey ( ) != null ? ClientAuthnDTO . AuthenticatorType . SNOWFLAKE_JWT : ClientAuthnDTO . AuthenticatorType . SNOWFLAKE ; }
|
Returns Authenticator type
| 400
| 4
|
151,771
|
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" ) ; AssertUtil . assertTrue ( loginInput . getLoginTimeout ( ) >= 0 , "negative login timeout for opening session" ) ; final ClientAuthnDTO . AuthenticatorType authenticator = getAuthenticator ( loginInput ) ; if ( ! authenticator . equals ( ClientAuthnDTO . AuthenticatorType . OAUTH ) ) { // OAuth does not require a username AssertUtil . assertTrue ( loginInput . getUserName ( ) != null , "missing user name for opening session" ) ; } if ( authenticator . equals ( ClientAuthnDTO . AuthenticatorType . EXTERNALBROWSER ) ) { // force to set the flag. loginInput . sessionParameters . put ( CLIENT_STORE_TEMPORARY_CREDENTIAL , true ) ; } else { // TODO: patch for now. We should update mergeProperteis // to normalize all parameters using STRING_PARAMS, INT_PARAMS and // BOOLEAN_PARAMS. Object value = loginInput . sessionParameters . get ( CLIENT_STORE_TEMPORARY_CREDENTIAL ) ; if ( value != null ) { loginInput . sessionParameters . put ( CLIENT_STORE_TEMPORARY_CREDENTIAL , asBoolean ( value ) ) ; } } boolean isClientStoreTemporaryCredential = asBoolean ( loginInput . sessionParameters . get ( CLIENT_STORE_TEMPORARY_CREDENTIAL ) ) ; LoginOutput loginOutput ; if ( isClientStoreTemporaryCredential && ( loginOutput = readTemporaryCredential ( loginInput ) ) != null ) { return loginOutput ; } return newSession ( loginInput ) ; }
|
Open a new session
| 454
| 4
|
151,772
|
static public LoginOutput issueSession ( LoginInput loginInput ) throws SFException , SnowflakeSQLException { return tokenRequest ( loginInput , TokenRequestType . ISSUE ) ; }
|
Issue a session
| 40
| 3
|
151,773
|
static public void closeSession ( LoginInput loginInput ) throws SFException , SnowflakeSQLException { logger . debug ( " public void close() throws SFException" ) ; // assert the following inputs are valid AssertUtil . assertTrue ( loginInput . getServerUrl ( ) != null , "missing server URL for closing session" ) ; AssertUtil . assertTrue ( loginInput . getSessionToken ( ) != null , "missing session token for closing session" ) ; AssertUtil . assertTrue ( loginInput . getLoginTimeout ( ) >= 0 , "missing login timeout for closing session" ) ; HttpPost postRequest = null ; try { URIBuilder uriBuilder ; uriBuilder = new URIBuilder ( loginInput . getServerUrl ( ) ) ; uriBuilder . addParameter ( SF_QUERY_SESSION_DELETE , "true" ) ; uriBuilder . addParameter ( SFSession . SF_QUERY_REQUEST_ID , UUID . randomUUID ( ) . toString ( ) ) ; uriBuilder . setPath ( SF_PATH_SESSION ) ; postRequest = new HttpPost ( uriBuilder . build ( ) ) ; postRequest . setHeader ( SF_HEADER_AUTHORIZATION , SF_HEADER_SNOWFLAKE_AUTHTYPE + " " + SF_HEADER_TOKEN_TAG + "=\"" + loginInput . getSessionToken ( ) + "\"" ) ; setServiceNameHeader ( loginInput , postRequest ) ; String theString = HttpUtil . executeRequest ( postRequest , loginInput . getLoginTimeout ( ) , 0 , null ) ; JsonNode rootNode ; logger . debug ( "connection close response: {}" , theString ) ; rootNode = mapper . readTree ( theString ) ; SnowflakeUtil . checkErrorAndThrowException ( rootNode ) ; } catch ( URISyntaxException ex ) { throw new RuntimeException ( "unexpected URI syntax exception" , ex ) ; } catch ( IOException ex ) { logger . error ( "unexpected IO exception for: " + postRequest , ex ) ; } catch ( SnowflakeSQLException ex ) { // ignore session expiration exception if ( ex . getErrorCode ( ) != Constants . SESSION_EXPIRED_GS_CODE ) { throw ex ; } } }
|
Close a session
| 516
| 3
|
151,774
|
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 ( "{\"username\":\"" + loginInput . getUserName ( ) + "\",\"password\":\"" + loginInput . getPassword ( ) + "\"}" ) ; postRequest . setEntity ( params ) ; HeaderGroup headers = new HeaderGroup ( ) ; headers . addHeader ( new BasicHeader ( HttpHeaders . ACCEPT , "application/json" ) ) ; headers . addHeader ( new BasicHeader ( HttpHeaders . CONTENT_TYPE , "application/json" ) ) ; postRequest . setHeaders ( headers . getAllHeaders ( ) ) ; final String idpResponse = HttpUtil . executeRequestWithoutCookies ( postRequest , loginInput . getLoginTimeout ( ) , 0 , null ) ; logger . debug ( "user is authenticated against {}." , loginInput . getAuthenticator ( ) ) ; // session token is in the data field of the returned json response final JsonNode jsonNode = mapper . readTree ( idpResponse ) ; oneTimeToken = jsonNode . get ( "cookieToken" ) . asText ( ) ; } catch ( IOException | URISyntaxException ex ) { handleFederatedFlowError ( loginInput , ex ) ; } return oneTimeToken ; }
|
Query IDP token url to authenticate and retrieve access token
| 350
| 12
|
151,775
|
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 < String , Object > data = new HashMap <> ( ) ; data . put ( ClientAuthnParameter . ACCOUNT_NAME . name ( ) , loginInput . getAccountName ( ) ) ; data . put ( ClientAuthnParameter . AUTHENTICATOR . name ( ) , loginInput . getAuthenticator ( ) ) ; data . put ( ClientAuthnParameter . CLIENT_APP_ID . name ( ) , loginInput . getAppId ( ) ) ; data . put ( ClientAuthnParameter . CLIENT_APP_VERSION . name ( ) , loginInput . getAppVersion ( ) ) ; ClientAuthnDTO authnData = new ClientAuthnDTO ( ) ; authnData . setData ( data ) ; String json = mapper . writeValueAsString ( authnData ) ; // attach the login info json body to the post request StringEntity input = new StringEntity ( json , Charset . forName ( "UTF-8" ) ) ; input . setContentType ( "application/json" ) ; HttpPost postRequest = new HttpPost ( fedUrlUri ) ; postRequest . setEntity ( input ) ; postRequest . addHeader ( "accept" , "application/json" ) ; final String gsResponse = HttpUtil . executeRequest ( postRequest , loginInput . getLoginTimeout ( ) , 0 , null ) ; logger . debug ( "authenticator-request response: {}" , gsResponse ) ; JsonNode jsonNode = mapper . readTree ( gsResponse ) ; // check the success field first if ( ! jsonNode . path ( "success" ) . asBoolean ( ) ) { logger . debug ( "response = {}" , gsResponse ) ; String errorCode = jsonNode . path ( "code" ) . asText ( ) ; throw new SnowflakeSQLException ( SqlState . SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION , ErrorCode . CONNECTION_ERROR . getMessageCode ( ) , errorCode , jsonNode . path ( "message" ) . asText ( ) ) ; } // session token is in the data field of the returned json response dataNode = jsonNode . path ( "data" ) ; } catch ( IOException | URISyntaxException ex ) { handleFederatedFlowError ( loginInput , ex ) ; } return dataNode ; }
|
Query Snowflake to obtain IDP token url and IDP SSO url
| 616
| 15
|
151,776
|
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 , ErrorCode . NETWORK_ERROR . getMessageCode ( ) , "Exception encountered when opening connection: " + ex . getMessage ( ) ) ; } logger . error ( "Exception when authenticating with " + loginInput . getAuthenticator ( ) , ex ) ; throw new SnowflakeSQLException ( ex , SqlState . SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION , ErrorCode . CONNECTION_ERROR . getMessageCode ( ) , ErrorCode . CONNECTION_ERROR . getMessageCode ( ) , ex . getMessage ( ) ) ; }
|
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 .
| 213
| 42
|
151,777
|
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 , tokenUrl , ssoUrl ) ; final String oneTimeToken = federatedFlowStep3 ( loginInput , tokenUrl ) ; final String responseHtml = federatedFlowStep4 ( loginInput , ssoUrl , oneTimeToken ) ; return responseHtml ; }
|
FEDERATED FLOW See SNOW - 27798 for additional details .
| 149
| 16
|
151,778
|
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 ( ) ) ) { // default port number for HTTPS aPort = 443 ; } if ( bPort == - 1 && "https" . equals ( bUrl . getProtocol ( ) ) ) { // default port number for HTTPS bPort = 443 ; } // no default port number for HTTP is supported. return aUrl . getHost ( ) . equalsIgnoreCase ( bUrl . getHost ( ) ) && aUrl . getProtocol ( ) . equalsIgnoreCase ( bUrl . getProtocol ( ) ) && aPort == bPort ; }
|
Verify if two input urls have the same protocol host and port .
| 212
| 15
|
151,779
|
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
| 92
| 14
|
151,780
|
public static Map < String , Object > getCommonParams ( JsonNode paramsNode ) { Map < String , Object > parameters = new HashMap <> ( ) ; for ( JsonNode child : paramsNode ) { // If there isn't a name then the response from GS must be erroneous. if ( ! child . hasNonNull ( "name" ) ) { logger . error ( "Common Parameter JsonNode encountered with " + "no parameter name!" ) ; continue ; } // Look up the parameter based on the "name" attribute of the node. String paramName = child . path ( "name" ) . asText ( ) ; // What type of value is it and what's the value? if ( ! child . hasNonNull ( "value" ) ) { logger . debug ( "No value found for Common Parameter {}" , child . path ( "name" ) . asText ( ) ) ; continue ; } if ( STRING_PARAMS . contains ( paramName . toUpperCase ( ) ) ) { parameters . put ( paramName , child . path ( "value" ) . asText ( ) ) ; } else if ( INT_PARAMS . contains ( paramName . toUpperCase ( ) ) ) { parameters . put ( paramName , child . path ( "value" ) . asInt ( ) ) ; } else if ( BOOLEAN_PARAMS . contains ( paramName . toUpperCase ( ) ) ) { parameters . put ( paramName , child . path ( "value" ) . asBoolean ( ) ) ; } else { logger . debug ( "Unknown Common Parameter: {}" , paramName ) ; } logger . debug ( "Parameter {}: {}" , paramName , child . path ( "value" ) . asText ( ) ) ; } return parameters ; }
|
Helper function to parse a JsonNode from a GS response containing CommonParameters emitting an EnumMap of parameters
| 391
| 22
|
151,781
|
protected ServerSocket getServerSocket ( ) throws SFException { try { return new ServerSocket ( 0 , // free port 0 , // default number of connections InetAddress . getByName ( "localhost" ) ) ; } catch ( IOException ex ) { throw new SFException ( ex , ErrorCode . NETWORK_ERROR , ex . getMessage ( ) ) ; } }
|
Gets a free port on localhost
| 77
| 8
|
151,782
|
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_REQUEST ) ; URI fedUrlUri = fedUriBuilder . build ( ) ; HttpPost postRequest = this . handlers . build ( fedUrlUri ) ; ClientAuthnDTO authnData = new ClientAuthnDTO ( ) ; Map < String , Object > data = new HashMap <> ( ) ; data . put ( ClientAuthnParameter . AUTHENTICATOR . name ( ) , authenticator ) ; data . put ( ClientAuthnParameter . ACCOUNT_NAME . name ( ) , loginInput . getAccountName ( ) ) ; data . put ( ClientAuthnParameter . LOGIN_NAME . name ( ) , loginInput . getUserName ( ) ) ; data . put ( ClientAuthnParameter . BROWSER_MODE_REDIRECT_PORT . name ( ) , Integer . toString ( port ) ) ; data . put ( ClientAuthnParameter . CLIENT_APP_ID . name ( ) , loginInput . getAppId ( ) ) ; data . put ( ClientAuthnParameter . CLIENT_APP_VERSION . name ( ) , loginInput . getAppVersion ( ) ) ; authnData . setData ( data ) ; String json = mapper . writeValueAsString ( authnData ) ; // attach the login info json body to the post request StringEntity input = new StringEntity ( json , Charset . forName ( "UTF-8" ) ) ; input . setContentType ( "application/json" ) ; postRequest . setEntity ( input ) ; postRequest . addHeader ( "accept" , "application/json" ) ; String theString = HttpUtil . executeRequest ( postRequest , loginInput . getLoginTimeout ( ) , 0 , null ) ; logger . debug ( "authenticator-request response: {}" , theString ) ; // general method, same as with data binding JsonNode jsonNode = mapper . readTree ( theString ) ; // check the success field first if ( ! jsonNode . path ( "success" ) . asBoolean ( ) ) { logger . debug ( "response = {}" , theString ) ; String errorCode = jsonNode . path ( "code" ) . asText ( ) ; throw new SnowflakeSQLException ( SqlState . SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION , new Integer ( errorCode ) , jsonNode . path ( "message" ) . asText ( ) ) ; } JsonNode dataNode = jsonNode . path ( "data" ) ; // session token is in the data field of the returned json response this . proofKey = dataNode . path ( "proofKey" ) . asText ( ) ; return dataNode . path ( "ssoUrl" ) . asText ( ) ; } catch ( IOException | URISyntaxException ex ) { throw new SFException ( ex , ErrorCode . NETWORK_ERROR , ex . getMessage ( ) ) ; } }
|
Gets SSO URL and proof key
| 726
| 8
|
151,783
|
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 ( ) ) . equalsIgnoreCase ( PREFIX_GET ) ) { targetLine = line ; } else if ( line . length ( ) > PREFIX_POST . length ( ) && line . substring ( 0 , PREFIX_POST . length ( ) ) . equalsIgnoreCase ( PREFIX_POST ) ) { targetLine = rets [ rets . length - 1 ] ; isPost = true ; } else if ( line . length ( ) > PREFIX_USER_AGENT . length ( ) && line . substring ( 0 , PREFIX_USER_AGENT . length ( ) ) . equalsIgnoreCase ( PREFIX_USER_AGENT ) ) { userAgent = line ; } } if ( targetLine == null ) { throw new SFException ( ErrorCode . NETWORK_ERROR , "Invalid HTTP request. No token is given from the browser." ) ; } if ( userAgent != null ) { logger . debug ( "{}" , userAgent ) ; } try { // attempt to get JSON response extractJsonTokenFromPostRequest ( targetLine ) ; } catch ( IOException ex ) { String parameters = isPost ? extractTokenFromPostRequest ( targetLine ) : extractTokenFromGetRequest ( targetLine ) ; try { URI inputParameter = new URI ( parameters ) ; for ( NameValuePair urlParam : URLEncodedUtils . parse ( inputParameter , UTF8_CHARSET ) ) { if ( "token" . equals ( urlParam . getName ( ) ) ) { this . token = urlParam . getValue ( ) ; break ; } } } catch ( URISyntaxException ex0 ) { throw new SFException ( ErrorCode . NETWORK_ERROR , String . format ( "Invalid HTTP request. No token is given from the browser. %s, err: %s" , targetLine , ex0 ) ) ; } } if ( this . token == null ) { throw new SFException ( ErrorCode . NETWORK_ERROR , String . format ( "Invalid HTTP request. No token is given from the browser: %s" , targetLine ) ) ; } returnToBrowser ( socket ) ; }
|
Receives SAML token from Snowflake via web browser
| 534
| 12
|
151,784
|
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 != null ) { content . add ( String . format ( "Access-Control-Allow-Origin: %s" , this . origin ) ) ; content . add ( "Vary: Accept-Encoding, Origin" ) ; Map < String , Object > data = new HashMap <> ( ) ; data . put ( "consent" , this . consentCacheIdToken ) ; responseText = mapper . writeValueAsString ( data ) ; } else { responseText = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"/>" + "<title>SAML Response for Snowflake</title></head>" + "<body>Your identity was confirmed and propagated to " + "Snowflake JDBC driver. You can close this window now and go back " + "where you started from.</body></html>" ; } content . add ( String . format ( "Content-Length: %s" , responseText . length ( ) ) ) ; content . add ( "" ) ; content . add ( responseText ) ; for ( int i = 0 ; i < content . size ( ) ; ++ i ) { if ( i > 0 ) { out . print ( "\r\n" ) ; } out . print ( content . get ( i ) ) ; } out . flush ( ) ; }
|
Output the message to the browser
| 366
| 6
|
151,785
|
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
| 91
| 13
|
151,786
|
@ Override 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 ( localLocation + localFileSep + destFileName ) ; logger . debug ( "Creating executor service for transfer" + "manager with {} threads" , parallelism ) ; // download file from s3 tx = new TransferManager ( amazonClient , SnowflakeUtil . createDefaultExecutorService ( "s3-transfer-manager-downloader-" , parallelism ) ) ; Download myDownload = tx . download ( remoteStorageLocation , stageFilePath , localFile ) ; // Pull object metadata from S3 ObjectMetadata meta = amazonClient . getObjectMetadata ( remoteStorageLocation , stageFilePath ) ; Map < String , String > metaMap = meta . getUserMetadata ( ) ; String key = metaMap . get ( AMZ_KEY ) ; String iv = metaMap . get ( AMZ_IV ) ; myDownload . waitForCompletion ( ) ; if ( this . isEncrypting ( ) && this . getEncryptionKeySize ( ) < 256 ) { if ( key == null || iv == null ) { throw new SnowflakeSQLException ( SqlState . INTERNAL_ERROR , ErrorCode . INTERNAL_ERROR . getMessageCode ( ) , "File metadata incomplete" ) ; } // Decrypt file try { EncryptionProvider . decrypt ( localFile , key , iv , this . encMat ) ; } catch ( Exception ex ) { logger . error ( "Error decrypting file" , ex ) ; throw ex ; } } return ; } catch ( Exception ex ) { handleS3Exception ( ex , ++ retryCount , "download" , connection , command , this ) ; } finally { if ( tx != null ) { tx . shutdownNow ( false ) ; } } } while ( retryCount <= getMaxRetries ( ) ) ; throw new SnowflakeSQLException ( SqlState . INTERNAL_ERROR , ErrorCode . INTERNAL_ERROR . getMessageCode ( ) , "Unexpected: download unsuccessful without exception!" ) ; }
|
Download a file from S3 .
| 504
| 7
|
151,787
|
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 ) ) { try { URL url = new URL ( SF_OCSP_RESPONSE_CACHE_SERVER_URL ) ; if ( url . getPort ( ) > 0 ) { SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN = String . format ( "%s://%s:%d/retry/%s" , url . getProtocol ( ) , url . getHost ( ) , url . getPort ( ) , "%s/%s" ) ; } else { SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN = String . format ( "%s://%s/retry/%s" , url . getProtocol ( ) , url . getHost ( ) , "%s/%s" ) ; } } catch ( IOException e ) { throw new RuntimeException ( String . format ( "Failed to parse SF_OCSP_RESPONSE_CACHE_SERVER_URL: %s" , SF_OCSP_RESPONSE_CACHE_SERVER_URL ) ) ; } } }
|
Reset OCSP Cache server URL
| 384
| 7
|
151,788
|
private X509TrustManager getTrustManager ( String algorithm ) { try { TrustManagerFactory factory = TrustManagerFactory . getInstance ( algorithm ) ; factory . init ( ( KeyStore ) null ) ; X509TrustManager ret = null ; for ( TrustManager tm : factory . getTrustManagers ( ) ) { // Multiple TrustManager may be attached. We just need X509 Trust // Manager here. if ( tm instanceof X509TrustManager ) { ret = ( X509TrustManager ) tm ; break ; } } if ( ret == null ) { return null ; } synchronized ( ROOT_CA_LOCK ) { // cache root CA certificates for later use. if ( ROOT_CA . size ( ) == 0 ) { for ( X509Certificate cert : ret . getAcceptedIssuers ( ) ) { Certificate bcCert = Certificate . getInstance ( cert . getEncoded ( ) ) ; ROOT_CA . put ( bcCert . getSubject ( ) . hashCode ( ) , bcCert ) ; } } } return ret ; } catch ( NoSuchAlgorithmException | KeyStoreException | CertificateEncodingException ex ) { throw new SSLInitializationException ( ex . getMessage ( ) , ex ) ; } }
|
Get TrustManager for the algorithm . This is mainly used to get the JVM default trust manager and cache all of the root CA .
| 261
| 27
|
151,789
|
void validateRevocationStatus ( X509Certificate [ ] chain , String peerHost ) throws CertificateException { final List < Certificate > bcChain = convertToBouncyCastleCertificate ( chain ) ; final List < SFPair < Certificate , Certificate > > pairIssuerSubjectList = getPairIssuerSubject ( bcChain ) ; if ( peerHost . startsWith ( "ocspssd" ) ) { return ; } if ( ocspCacheServer . new_endpoint_enabled ) { ocspCacheServer . resetOCSPResponseCacheServer ( peerHost ) ; } synchronized ( OCSP_RESPONSE_CACHE_LOCK ) { boolean isCached = isCached ( pairIssuerSubjectList ) ; if ( this . useOcspResponseCacheServer && ! isCached ) { if ( ! ocspCacheServer . new_endpoint_enabled ) { LOGGER . debug ( "Downloading OCSP response cache from the server. URL: {}" , SF_OCSP_RESPONSE_CACHE_SERVER_URL ) ; } else { LOGGER . debug ( "Downloading OCSP response cache from the server. URL: {}" , ocspCacheServer . SF_OCSP_RESPONSE_CACHE_SERVER ) ; } readOcspResponseCacheServer ( ) ; // if the cache is downloaded from the server, it should be written // to the file cache at all times. WAS_CACHE_UPDATED = true ; } executeRevocationStatusChecks ( pairIssuerSubjectList , peerHost ) ; if ( WAS_CACHE_UPDATED ) { JsonNode input = encodeCacheToJSON ( ) ; fileCacheManager . writeCacheFile ( input ) ; WAS_CACHE_UPDATED = false ; } } }
|
Certificate Revocation checks
| 395
| 5
|
151,790
|
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 ) { executeOneRevoctionStatusCheck ( pairIssuerSubject , currentTimeSecond , peerHost ) ; } } catch ( IOException ex ) { LOGGER . debug ( "Failed to decode CertID. Ignored." ) ; } }
|
Executes the revocation status checks for all chained certificates
| 126
| 10
|
151,791
|
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 = ASN1OctetString . getInstance ( ocsp_cache_key . keyHash ) ; ASN1Integer snumber = new ASN1Integer ( ocsp_cache_key . serialNumber ) ; CertID cid = new CertID ( algo , nameHash , keyHash , snumber ) ; return Base64 . encodeBase64String ( cid . toASN1Primitive ( ) . getEncoded ( ) ) ; } catch ( Exception ex ) { LOGGER . debug ( "Failed to encode cache key to base64 encoded cert id" ) ; } return null ; }
|
Convert cache key to base64 encoded cert id
| 228
| 10
|
151,792
|
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 ( pairIssuerSubject ) ; CertificateID certificateId = req . getRequestList ( ) [ 0 ] . getCertID ( ) ; LOGGER . debug ( CertificateIDToString ( certificateId ) ) ; CertID cid = certificateId . toASN1Primitive ( ) ; OcspResponseCacheKey k = new OcspResponseCacheKey ( cid . getIssuerNameHash ( ) . getEncoded ( ) , cid . getIssuerKeyHash ( ) . getEncoded ( ) , cid . getSerialNumber ( ) . getValue ( ) ) ; SFPair < Long , String > res = OCSP_RESPONSE_CACHE . get ( k ) ; if ( res == null ) { LOGGER . debug ( "Not all OCSP responses for the certificate is in the cache." ) ; isCached = false ; break ; } else if ( currentTimeSecond - CACHE_EXPIRATION_IN_SECONDS > res . left ) { LOGGER . debug ( "Cache for CertID expired." ) ; isCached = false ; break ; } else { try { validateRevocationStatusMain ( pairIssuerSubject , res . right ) ; } catch ( CertificateException ex ) { LOGGER . debug ( "Cache includes invalid OCSPResponse. " + "Will download the OCSP cache from Snowflake OCSP server" ) ; isCached = false ; } } } } catch ( IOException ex ) { LOGGER . debug ( "Failed to encode CertID." ) ; } return isCached ; }
|
Is OCSP Response cached?
| 418
| 6
|
151,793
|
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 . getSerialNumber ( ) ) ) ; }
|
CertificateID to string
| 103
| 5
|
151,794
|
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 = ( DLSequence ) ASN1ObjectIdentifier . fromByteArray ( certIdDer ) ; ASN1Encodable [ ] rawCertIdArray = rawCertId . toArray ( ) ; byte [ ] issuerNameHashDer = ( ( DEROctetString ) rawCertIdArray [ 1 ] ) . getEncoded ( ) ; byte [ ] issuerKeyHashDer = ( ( DEROctetString ) rawCertIdArray [ 2 ] ) . getEncoded ( ) ; BigInteger serialNumber = ( ( ASN1Integer ) rawCertIdArray [ 3 ] ) . getValue ( ) ; OcspResponseCacheKey k = new OcspResponseCacheKey ( issuerNameHashDer , issuerKeyHashDer , serialNumber ) ; JsonNode ocspRespBase64 = elem . getValue ( ) ; if ( ! ocspRespBase64 . isArray ( ) || ocspRespBase64 . size ( ) != 2 ) { LOGGER . debug ( "Invalid cache file format." ) ; return null ; } long producedAt = ocspRespBase64 . get ( 0 ) . asLong ( ) ; String ocspResp = ocspRespBase64 . get ( 1 ) . asText ( ) ; if ( currentTimeSecond - CACHE_EXPIRATION_IN_SECONDS <= producedAt ) { // add cache return SFPair . of ( k , SFPair . of ( producedAt , ocspResp ) ) ; } else { // delete cache return SFPair . of ( k , SFPair . of ( producedAt , ( String ) null ) ) ; } }
|
Decodes OCSP Response Cache key from JSON
| 445
| 9
|
151,795
|
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 . getValue ( ) ; long currentTimeSecond = value0 . left ; DigestCalculator digest = new SHA1DigestCalculator ( ) ; AlgorithmIdentifier algo = digest . getAlgorithmIdentifier ( ) ; ASN1OctetString nameHash = ASN1OctetString . getInstance ( key . nameHash ) ; ASN1OctetString keyHash = ASN1OctetString . getInstance ( key . keyHash ) ; ASN1Integer serialNumber = new ASN1Integer ( key . serialNumber ) ; CertID cid = new CertID ( algo , nameHash , keyHash , serialNumber ) ; ArrayNode vout = OBJECT_MAPPER . createArrayNode ( ) ; vout . add ( currentTimeSecond ) ; vout . add ( value0 . right ) ; out . set ( Base64 . encodeBase64String ( cid . toASN1Primitive ( ) . getEncoded ( ) ) , vout ) ; } return out ; } catch ( IOException ex ) { LOGGER . debug ( "Failed to encode ASN1 object." ) ; } return null ; }
|
Encode OCSP Response Cache to JSON
| 349
| 8
|
151,796
|
private void validateRevocationStatusMain ( SFPair < Certificate , Certificate > pairIssuerSubject , String ocspRespB64 ) throws CertificateException { try { OCSPResp ocspResp = b64ToOCSPResp ( ocspRespB64 ) ; Date currentTime = new Date ( ) ; BasicOCSPResp basicOcspResp = ( BasicOCSPResp ) ( ocspResp . getResponseObject ( ) ) ; X509CertificateHolder [ ] attachedCerts = basicOcspResp . getCerts ( ) ; X509CertificateHolder signVerifyCert ; if ( attachedCerts . length > 0 ) { LOGGER . debug ( "Certificate is attached for verification. " + "Verifying it by the issuer certificate." ) ; signVerifyCert = attachedCerts [ 0 ] ; if ( currentTime . after ( signVerifyCert . getNotAfter ( ) ) || currentTime . before ( signVerifyCert . getNotBefore ( ) ) ) { throw new OCSPException ( String . format ( "Cert attached to OCSP Response is invalid." + "Current time - %s" + "Certificate not before time - %s" + "Certificate not after time - %s" , currentTime . toString ( ) , signVerifyCert . getNotBefore ( ) . toString ( ) , signVerifyCert . getNotAfter ( ) . toString ( ) ) ) ; } verifySignature ( new X509CertificateHolder ( pairIssuerSubject . left . getEncoded ( ) ) , signVerifyCert . getSignature ( ) , CONVERTER_X509 . getCertificate ( signVerifyCert ) . getTBSCertificate ( ) , signVerifyCert . getSignatureAlgorithm ( ) ) ; LOGGER . debug ( "Verifying OCSP signature by the attached certificate public key." ) ; } else { LOGGER . debug ( "Certificate is NOT attached for verification. " + "Verifying OCSP signature by the issuer public key." ) ; signVerifyCert = new X509CertificateHolder ( pairIssuerSubject . left . getEncoded ( ) ) ; } verifySignature ( signVerifyCert , basicOcspResp . getSignature ( ) , basicOcspResp . getTBSResponseData ( ) , basicOcspResp . getSignatureAlgorithmID ( ) ) ; validateBasicOcspResponse ( currentTime , basicOcspResp ) ; } catch ( IOException | OCSPException ex ) { throw new CertificateEncodingException ( "Failed to check revocation status." , ex ) ; } }
|
Validates the certificate revocation status
| 569
| 6
|
151,797
|
private void validateBasicOcspResponse ( Date currentTime , BasicOCSPResp basicOcspResp ) throws CertificateEncodingException { for ( SingleResp singleResps : basicOcspResp . getResponses ( ) ) { Date thisUpdate = singleResps . getThisUpdate ( ) ; Date nextUpdate = singleResps . getNextUpdate ( ) ; LOGGER . debug ( "Current Time: {}, This Update: {}, Next Update: {}" , currentTime , thisUpdate , nextUpdate ) ; CertificateStatus certStatus = singleResps . getCertStatus ( ) ; if ( certStatus != CertificateStatus . GOOD ) { if ( certStatus instanceof RevokedStatus ) { RevokedStatus status = ( RevokedStatus ) certStatus ; int reason ; try { reason = status . getRevocationReason ( ) ; } catch ( IllegalStateException ex ) { reason = - 1 ; } Date revocationTime = status . getRevocationTime ( ) ; throw new CertificateEncodingException ( String . format ( "The certificate has been revoked. Reason: %d, Time: %s" , reason , DATE_FORMAT_UTC . format ( revocationTime ) ) ) ; } else { // Unknown status throw new CertificateEncodingException ( "Failed to validate the certificate for UNKNOWN reason." ) ; } } if ( ! isValidityRange ( currentTime , thisUpdate , nextUpdate ) ) { throw new CertificateEncodingException ( String . format ( "The validity is out of range: " + "Current Time: %s, This Update: %s, Next Update: %s" , DATE_FORMAT_UTC . format ( currentTime ) , DATE_FORMAT_UTC . format ( thisUpdate ) , DATE_FORMAT_UTC . format ( nextUpdate ) ) ) ; } } LOGGER . debug ( "OK. Verified the certificate revocation status." ) ; }
|
Validates OCSP Basic OCSP response .
| 405
| 9
|
151,798
|
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 ( "Unsupported signature OID. OID: %s" , idf ) ) ; } Signature signer = Signature . getInstance ( algorithm , BouncyCastleProvider . PROVIDER_NAME ) ; X509Certificate c = CONVERTER_X509 . getCertificate ( cert ) ; signer . initVerify ( c . getPublicKey ( ) ) ; signer . update ( data ) ; if ( ! signer . verify ( sig ) ) { throw new CertificateEncodingException ( String . format ( "Failed to verify the signature. Potentially the " + "data was not generated by by the cert, %s" , cert . getSubject ( ) ) ) ; } } catch ( NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | SignatureException ex ) { throw new CertificateEncodingException ( "Failed to verify the signature." , ex ) ; } }
|
Verifies the signature of the data
| 275
| 7
|
151,799
|
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 ] = hexArray [ v & 0x0F ] ; } return new String ( hexChars ) ; }
|
Converts Byte array to hex string
| 134
| 7
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.