repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
Jasig/uPortal
uPortal-portlets/src/main/java/org/apereo/portal/portlets/directory/DirectoryPortletController.java
DirectoryPortletController.searchDirectory
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; }
java
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; }
[ "protected", "List", "<", "IPersonAttributes", ">", "searchDirectory", "(", "String", "query", ",", "PortletRequest", "request", ")", "{", "final", "Map", "<", "String", ",", "Object", ">", "queryAttributes", "=", "new", "HashMap", "<>", "(", ")", ";", "for"...
Search the directory for people matching the search query. Search results will be scoped to the permissions of the user performing the search. @param query @param request @return
[ "Search", "the", "directory", "for", "people", "matching", "the", "search", "query", ".", "Search", "results", "will", "be", "scoped", "to", "the", "permissions", "of", "the", "user", "performing", "the", "search", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/directory/DirectoryPortletController.java#L228-L250
train
Jasig/uPortal
uPortal-portlets/src/main/java/org/apereo/portal/portlets/directory/DirectoryPortletController.java
DirectoryPortletController.isMobile
protected boolean isMobile(PortletRequest request) { final String themeName = request.getProperty(IPortletRenderer.THEME_NAME_PROPERTY); return "UniversalityMobile".equals(themeName); }
java
protected boolean isMobile(PortletRequest request) { final String themeName = request.getProperty(IPortletRenderer.THEME_NAME_PROPERTY); return "UniversalityMobile".equals(themeName); }
[ "protected", "boolean", "isMobile", "(", "PortletRequest", "request", ")", "{", "final", "String", "themeName", "=", "request", ".", "getProperty", "(", "IPortletRenderer", ".", "THEME_NAME_PROPERTY", ")", ";", "return", "\"UniversalityMobile\"", ".", "equals", "(",...
Determine if this should be a mobile view. @param request @return
[ "Determine", "if", "this", "should", "be", "a", "mobile", "view", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/directory/DirectoryPortletController.java#L258-L261
train
Jasig/uPortal
uPortal-web/src/main/java/org/apereo/portal/portlet/dao/trans/TransientPortletEntityDao.java
TransientPortletEntityDao.unwrapEntity
protected IPortletEntity unwrapEntity(IPortletEntity portletEntity) { if (portletEntity instanceof TransientPortletEntity) { return ((TransientPortletEntity) portletEntity).getDelegatePortletEntity(); } return portletEntity; }
java
protected IPortletEntity unwrapEntity(IPortletEntity portletEntity) { if (portletEntity instanceof TransientPortletEntity) { return ((TransientPortletEntity) portletEntity).getDelegatePortletEntity(); } return portletEntity; }
[ "protected", "IPortletEntity", "unwrapEntity", "(", "IPortletEntity", "portletEntity", ")", "{", "if", "(", "portletEntity", "instanceof", "TransientPortletEntity", ")", "{", "return", "(", "(", "TransientPortletEntity", ")", "portletEntity", ")", ".", "getDelegatePortl...
Returns the unwrapped entity if it is an instance of TransientPortletEntity. If not the original entity is returned.
[ "Returns", "the", "unwrapped", "entity", "if", "it", "is", "an", "instance", "of", "TransientPortletEntity", ".", "If", "not", "the", "original", "entity", "is", "returned", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-web/src/main/java/org/apereo/portal/portlet/dao/trans/TransientPortletEntityDao.java#L175-L181
train
Jasig/uPortal
uPortal-web/src/main/java/org/apereo/portal/portlet/dao/trans/TransientPortletEntityDao.java
TransientPortletEntityDao.wrapEntity
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; }
java
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; }
[ "protected", "IPortletEntity", "wrapEntity", "(", "IPortletEntity", "portletEntity", ")", "{", "if", "(", "portletEntity", "==", "null", ")", "{", "return", "null", ";", "}", "final", "String", "persistentLayoutNodeId", "=", "portletEntity", ".", "getLayoutNodeId", ...
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.
[ "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"...
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-web/src/main/java/org/apereo/portal/portlet/dao/trans/TransientPortletEntityDao.java#L188-L210
train
Jasig/uPortal
uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/jsp/Util.java
Util.isValidUrl
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; }
java
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; }
[ "public", "static", "boolean", "isValidUrl", "(", "String", "url", ")", "{", "HttpURLConnection", "huc", "=", "null", ";", "boolean", "isValid", "=", "false", ";", "try", "{", "URL", "u", "=", "new", "URL", "(", "url", ")", ";", "huc", "=", "(", "Htt...
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. @param url - A string representing a url @return True if URL is valid according to included definition
[ "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"...
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/jsp/Util.java#L83-L111
train
Jasig/uPortal
uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/IncludeExcludeUtils.java
IncludeExcludeUtils.included
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)); }
java
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)); }
[ "public", "static", "<", "T", ">", "boolean", "included", "(", "T", "value", ",", "Collection", "<", "?", "extends", "T", ">", "includes", ",", "Collection", "<", "?", "extends", "T", ">", "excludes", ")", "{", "return", "(", "includes", ".", "isEmpty"...
Determines if the specified value is included based on the contents of the include and exclude collections. <p>Returns true if one of the following is true: <br> includes is empty && excludes is empty<br> includes contains value<br> includes is empty and excludes does not contain value<br> @param value Value to test @param includes Included values @param excludes Excluded values @return true if it should be included
[ "Determines", "if", "the", "specified", "value", "is", "included", "based", "on", "the", "contents", "of", "the", "include", "and", "exclude", "collections", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/IncludeExcludeUtils.java#L37-L42
train
Jasig/uPortal
uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/BasePersonManager.java
BasePersonManager.init
@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); }
java
@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); }
[ "@", "EventListener", "public", "void", "init", "(", "ContextRefreshedEvent", "event", ")", "{", "idTokenFactory", "=", "context", ".", "getBean", "(", "IdTokenFactory", ".", "class", ")", ";", "// Make sure we have a guestUsernameSelectors collection & sort it", "if", ...
To avoid circular reference issues, this bean obtains its dependencies when the context finishes starting.
[ "To", "avoid", "circular", "reference", "issues", "this", "bean", "obtains", "its", "dependencies", "when", "the", "context", "finishes", "starting", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/BasePersonManager.java#L60-L69
train
Jasig/uPortal
uPortal-rendering/src/main/java/org/apereo/portal/portlet/container/PortletResourceResponseContextImpl.java
PortletResourceResponseContextImpl.handleResourceHeader
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; }
java
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; }
[ "protected", "boolean", "handleResourceHeader", "(", "String", "key", ",", "String", "value", ")", "{", "if", "(", "ResourceResponse", ".", "HTTP_STATUS_CODE", ".", "equals", "(", "key", ")", ")", "{", "this", ".", "portletResourceOutputHandler", ".", "setStatus...
Handles resource response specific headers. Returns true if the header was consumed by this method and requires no further processing @return
[ "Handles", "resource", "response", "specific", "headers", ".", "Returns", "true", "if", "the", "header", "was", "consumed", "by", "this", "method", "and", "requires", "no", "further", "processing" ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-rendering/src/main/java/org/apereo/portal/portlet/container/PortletResourceResponseContextImpl.java#L112-L141
train
Jasig/uPortal
uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/LPAResetParameter.java
LPAResetParameter.perform
@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); }
java
@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); }
[ "@", "Override", "public", "void", "perform", "(", ")", "throws", "PortalException", "{", "// push the change into the PLF", "if", "(", "nodeId", ".", "startsWith", "(", "Constants", ".", "FRAGMENT_ID_USER_PREFIX", ")", ")", "{", "// remove the parm edit", "ParameterE...
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.
[ "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", ...
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/LPAResetParameter.java#L43-L52
train
Jasig/uPortal
uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/RDBMPermissionImpl.java
RDBMPermissionImpl.add
@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); } }
java
@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); } }
[ "@", "Override", "public", "void", "add", "(", "IPermission", "perm", ")", "throws", "AuthorizationException", "{", "Connection", "conn", "=", "null", ";", "int", "rc", "=", "0", ";", "try", "{", "conn", "=", "RDBMServices", ".", "getConnection", "(", ")",...
Add the IPermission to the store. @param perm org.apereo.portal.security.IPermission @exception AuthorizationException - wraps an Exception specific to the store.
[ "Add", "the", "IPermission", "to", "the", "store", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/RDBMPermissionImpl.java#L104-L130
train
Jasig/uPortal
uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/RDBMPermissionImpl.java
RDBMPermissionImpl.delete
@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); } } }
java
@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); } } }
[ "@", "Override", "public", "void", "delete", "(", "IPermission", "[", "]", "perms", ")", "throws", "AuthorizationException", "{", "if", "(", "perms", ".", "length", ">", "0", ")", "{", "try", "{", "primDelete", "(", "perms", ")", ";", "}", "catch", "("...
Delete the IPermissions from the store. @param perms org.apereo.portal.security.IPermission[] @exception AuthorizationException - wraps an Exception specific to the store.
[ "Delete", "the", "IPermissions", "from", "the", "store", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/RDBMPermissionImpl.java#L137-L148
train
Jasig/uPortal
uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/RDBMPermissionImpl.java
RDBMPermissionImpl.delete
@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); } }
java
@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); } }
[ "@", "Override", "public", "void", "delete", "(", "IPermission", "perm", ")", "throws", "AuthorizationException", "{", "Connection", "conn", "=", "null", ";", "try", "{", "conn", "=", "RDBMServices", ".", "getConnection", "(", ")", ";", "String", "sQuery", "...
Delete a single IPermission from the store. @param perm org.apereo.portal.security.IPermission @exception AuthorizationException - wraps an Exception specific to the store.
[ "Delete", "a", "single", "IPermission", "from", "the", "store", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/RDBMPermissionImpl.java#L155-L174
train
Jasig/uPortal
uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/RDBMPermissionImpl.java
RDBMPermissionImpl.getPrincipalType
private int getPrincipalType(String principalString) { return Integer.parseInt( principalString.substring(0, principalString.indexOf(PRINCIPAL_SEPARATOR))); }
java
private int getPrincipalType(String principalString) { return Integer.parseInt( principalString.substring(0, principalString.indexOf(PRINCIPAL_SEPARATOR))); }
[ "private", "int", "getPrincipalType", "(", "String", "principalString", ")", "{", "return", "Integer", ".", "parseInt", "(", "principalString", ".", "substring", "(", "0", ",", "principalString", ".", "indexOf", "(", "PRINCIPAL_SEPARATOR", ")", ")", ")", ";", ...
Returns the principal type portion of the principal. @return int @param principalString
[ "Returns", "the", "principal", "type", "portion", "of", "the", "principal", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/RDBMPermissionImpl.java#L283-L286
train
Jasig/uPortal
uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/RDBMPermissionImpl.java
RDBMPermissionImpl.primDelete
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(); }
java
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(); }
[ "private", "int", "primDelete", "(", "IPermission", "perm", ",", "PreparedStatement", "ps", ")", "throws", "Exception", "{", "ps", ".", "clearParameters", "(", ")", ";", "ps", ".", "setString", "(", "1", ",", "perm", ".", "getOwner", "(", ")", ")", ";", ...
Set the params on the PreparedStatement and execute the delete. @param perm org.apereo.portal.security.IPermission @param ps java.sql.PreparedStatement - the PreparedStatement for deleting a Permission row. @return int - the return code from the PreparedStatement @exception Exception
[ "Set", "the", "params", "on", "the", "PreparedStatement", "and", "execute", "the", "delete", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/RDBMPermissionImpl.java#L498-L508
train
Jasig/uPortal
uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/RDBMPermissionImpl.java
RDBMPermissionImpl.primUpdate
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(); }
java
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(); }
[ "private", "int", "primUpdate", "(", "IPermission", "perm", ",", "PreparedStatement", "ps", ")", "throws", "Exception", "{", "java", ".", "sql", ".", "Timestamp", "ts", "=", "null", ";", "// UPDATE COLUMNS:", "ps", ".", "clearParameters", "(", ")", ";", "// ...
Set the params on the PreparedStatement and execute the update. @param perm org.apereo.portal.security.IPermission @param ps java.sql.PreparedStatement - the PreparedStatement for updating a Permission row. @return int - the return code from the PreparedStatement @exception Exception
[ "Set", "the", "params", "on", "the", "PreparedStatement", "and", "execute", "the", "update", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/RDBMPermissionImpl.java#L554-L589
train
Jasig/uPortal
uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/RDBMPermissionImpl.java
RDBMPermissionImpl.select
@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()])); }
java
@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()])); }
[ "@", "Override", "public", "IPermission", "[", "]", "select", "(", "String", "owner", ",", "String", "principal", ",", "String", "activity", ",", "String", "target", ",", "String", "type", ")", "throws", "AuthorizationException", "{", "Connection", "conn", "="...
Select the Permissions from the store. @param owner String - the Permission owner @param principal String - the Permission principal @param activity String - the Permission activity @exception AuthorizationException - wraps an Exception specific to the store.
[ "Select", "the", "Permissions", "from", "the", "store", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/RDBMPermissionImpl.java#L689-L759
train
Jasig/uPortal
uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/RDBMPermissionImpl.java
RDBMPermissionImpl.update
@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); } }
java
@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); } }
[ "@", "Override", "public", "void", "update", "(", "IPermission", "perm", ")", "throws", "AuthorizationException", "{", "Connection", "conn", "=", "null", ";", "try", "{", "conn", "=", "RDBMServices", ".", "getConnection", "(", ")", ";", "String", "sQuery", "...
Update a single IPermission in the store. @param perm org.apereo.portal.security.IPermission @exception AuthorizationException - wraps an Exception specific to the store.
[ "Update", "a", "single", "IPermission", "in", "the", "store", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-core/src/main/java/org/apereo/portal/security/provider/RDBMPermissionImpl.java#L783-L803
train
Jasig/uPortal
uPortal-web/src/main/java/org/apereo/portal/portlet/rendering/PortletEventCoordinatationService.java
PortletEventCoordinatationService.getPortletEventQueue
@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; } }
java
@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; } }
[ "@", "Override", "public", "PortletEventQueue", "getPortletEventQueue", "(", "HttpServletRequest", "request", ")", "{", "request", "=", "this", ".", "portalRequestUtils", ".", "getOriginalPortalRequest", "(", "request", ")", ";", "synchronized", "(", "PortalWebUtils", ...
Returns a request scoped PortletEventQueue used to track events to process and events to dispatch
[ "Returns", "a", "request", "scoped", "PortletEventQueue", "used", "to", "track", "events", "to", "process", "and", "events", "to", "dispatch" ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-web/src/main/java/org/apereo/portal/portlet/rendering/PortletEventCoordinatationService.java#L155-L168
train
Jasig/uPortal
uPortal-spring/src/main/java/org/apereo/portal/spring/web/flow/PortalWebFlowUtilsImpl.java
PortalWebFlowUtilsImpl.getServletRequestFromExternalContext
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"); } }
java
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"); } }
[ "protected", "HttpServletRequest", "getServletRequestFromExternalContext", "(", "ExternalContext", "externalContext", ")", "{", "Object", "request", "=", "externalContext", ".", "getNativeRequest", "(", ")", ";", "if", "(", "request", "instanceof", "PortletRequest", ")", ...
Get the HttpServletRequest associated with the supplied ExternalContext. @param externalContext @return
[ "Get", "the", "HttpServletRequest", "associated", "with", "the", "supplied", "ExternalContext", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-spring/src/main/java/org/apereo/portal/spring/web/flow/PortalWebFlowUtilsImpl.java#L73-L89
train
Jasig/uPortal
uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/TransientUserLayoutManagerWrapper.java
TransientUserLayoutManagerWrapper.getChannelDefinition
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; }
java
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; }
[ "protected", "IPortletDefinition", "getChannelDefinition", "(", "String", "subId", ")", "throws", "PortalException", "{", "IPortletDefinition", "chanDef", "=", "mChanMap", ".", "get", "(", "subId", ")", ";", "if", "(", "null", "==", "chanDef", ")", "{", "String"...
Given a subscribe Id, return a ChannelDefinition. @param subId the subscribe id for the ChannelDefinition. @return a <code>ChannelDefinition</code>
[ "Given", "a", "subscribe", "Id", "return", "a", "ChannelDefinition", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/TransientUserLayoutManagerWrapper.java#L317-L339
train
Jasig/uPortal
uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/TransientUserLayoutManagerWrapper.java
TransientUserLayoutManagerWrapper.getSubscribeId
@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; }
java
@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; }
[ "@", "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",...
Given an functional name, return its subscribe id. @param fname the functional name to lookup @return the fname's subscribe id.
[ "Given", "an", "functional", "name", "return", "its", "subscribe", "id", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/TransientUserLayoutManagerWrapper.java#L361-L397
train
Jasig/uPortal
uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/TransientUserLayoutManagerWrapper.java
TransientUserLayoutManagerWrapper.getTransientNode
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); } }
java
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); } }
[ "private", "IUserLayoutChannelDescription", "getTransientNode", "(", "String", "nodeId", ")", "throws", "PortalException", "{", "// get fname from subscribe id", "final", "String", "fname", "=", "getFname", "(", "nodeId", ")", ";", "if", "(", "null", "==", "fname", ...
Return an IUserLayoutChannelDescription by way of nodeId @param nodeId the node (subscribe) id to get the channel for. @return a <code>IUserLayoutNodeDescription</code>
[ "Return", "an", "IUserLayoutChannelDescription", "by", "way", "of", "nodeId" ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/TransientUserLayoutManagerWrapper.java#L427-L450
train
Jasig/uPortal
uPortal-events/src/main/java/org/apereo/portal/events/tincan/providers/DefaultTinCanAPIProvider.java
DefaultTinCanAPIProvider.sendEvent
@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; }
java
@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; }
[ "@", "Override", "public", "boolean", "sendEvent", "(", "LrsStatement", "statement", ")", "{", "if", "(", "!", "isEnabled", "(", ")", ")", "{", "return", "false", ";", "}", "ResponseEntity", "<", "Object", ">", "response", "=", "sendRequest", "(", "STATEME...
Actually send an event to the provider. @param statement the LRS statement to send.
[ "Actually", "send", "an", "event", "to", "the", "provider", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-events/src/main/java/org/apereo/portal/events/tincan/providers/DefaultTinCanAPIProvider.java#L299-L317
train
Jasig/uPortal
uPortal-events/src/main/java/org/apereo/portal/events/tincan/providers/DefaultTinCanAPIProvider.java
DefaultTinCanAPIProvider.loadConfig
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("/*$", ""); }
java
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("/*$", ""); }
[ "protected", "void", "loadConfig", "(", ")", "{", "if", "(", "!", "isEnabled", "(", ")", ")", "{", "return", ";", "}", "final", "String", "urlProp", "=", "format", "(", "PROPERTY_FORMAT", ",", "id", ",", "\"url\"", ")", ";", "LRSUrl", "=", "propertyRes...
Read the LRS config. <p>"url" is the only required property. If not set, will disable this LRS provider. <p>Rather than asking installations to write a lot of XML, this pushes most of the configuration out to portal.properties. It reads dynamically named properties based on the "id" of this LRS provider. This is similar to the way that the TinCan configuration is handled for Sakai.
[ "Read", "the", "LRS", "config", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-events/src/main/java/org/apereo/portal/events/tincan/providers/DefaultTinCanAPIProvider.java#L332-L366
train
Jasig/uPortal
uPortal-events/src/main/java/org/apereo/portal/events/tincan/providers/DefaultTinCanAPIProvider.java
DefaultTinCanAPIProvider.sendRequest
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; }
java
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; }
[ "protected", "<", "T", ">", "ResponseEntity", "<", "T", ">", "sendRequest", "(", "String", "pathFragment", ",", "HttpMethod", "method", ",", "List", "<", "?", "extends", "NameValuePair", ">", "getParams", ",", "Object", "postData", ",", "Class", "<", "T", ...
Send a request to the LRS. @param pathFragment the URL. Should be relative to the xAPI API root @param method the HTTP method @param getParams the set of GET params @param postData the post data. @param returnType the type of object to expect in the response @param <T> The type of object to expect in the response @return The response object.
[ "Send", "a", "request", "to", "the", "LRS", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-events/src/main/java/org/apereo/portal/events/tincan/providers/DefaultTinCanAPIProvider.java#L379-L399
train
Jasig/uPortal
uPortal-events/src/main/java/org/apereo/portal/events/tincan/providers/DefaultTinCanAPIProvider.java
DefaultTinCanAPIProvider.buildRequestURI
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); } }
java
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); } }
[ "private", "URI", "buildRequestURI", "(", "String", "pathFragment", ",", "List", "<", "?", "extends", "NameValuePair", ">", "params", ")", "{", "try", "{", "String", "queryString", "=", "\"\"", ";", "if", "(", "params", "!=", "null", "&&", "!", "params", ...
Build a URI for the REST request. <p>Note: this converts to URI instead of using a string because the activities/state API requires you to pass JSON as a GET parameter. The {...} confuses the RestTemplate path parameter handling. By converting to URI, I skip that. @param pathFragment The path fragment relative to the LRS REST base URL @param params The list of GET parameters to encode. May be null. @return The full URI to the LMS REST endpoint
[ "Build", "a", "URI", "for", "the", "REST", "request", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-events/src/main/java/org/apereo/portal/events/tincan/providers/DefaultTinCanAPIProvider.java#L412-L424
train
Jasig/uPortal
uPortal-events/src/main/java/org/apereo/portal/events/aggr/portletexec/JpaPortletExecutionAggregationDao.java
JpaPortletExecutionAggregationDao.bindAggregationSpecificKeyParameters
@Override protected void bindAggregationSpecificKeyParameters( TypedQuery<PortletExecutionAggregationImpl> query, Set<PortletExecutionAggregationKey> keys) { query.setParameter(this.portletMappingParameter, extractAggregatePortletMappings(keys)); query.setParameter(this.executionTypeParameter, extractExecutionTypes(keys)); }
java
@Override protected void bindAggregationSpecificKeyParameters( TypedQuery<PortletExecutionAggregationImpl> query, Set<PortletExecutionAggregationKey> keys) { query.setParameter(this.portletMappingParameter, extractAggregatePortletMappings(keys)); query.setParameter(this.executionTypeParameter, extractExecutionTypes(keys)); }
[ "@", "Override", "protected", "void", "bindAggregationSpecificKeyParameters", "(", "TypedQuery", "<", "PortletExecutionAggregationImpl", ">", "query", ",", "Set", "<", "PortletExecutionAggregationKey", ">", "keys", ")", "{", "query", ".", "setParameter", "(", "this", ...
The execution type is obtained from the first PortletExecutionAggregationKey.
[ "The", "execution", "type", "is", "obtained", "from", "the", "first", "PortletExecutionAggregationKey", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-events/src/main/java/org/apereo/portal/events/aggr/portletexec/JpaPortletExecutionAggregationDao.java#L84-L90
train
Jasig/uPortal
uPortal-rdbm/src/main/java/org/apereo/portal/jpa/OpenEntityManagerAspect.java
OpenEntityManagerAspect.getTransactionalEntityManager
protected EntityManager getTransactionalEntityManager(EntityManagerFactory emf) throws IllegalStateException { Assert.state(emf != null, "No EntityManagerFactory specified"); return EntityManagerFactoryUtils.getTransactionalEntityManager(emf); }
java
protected EntityManager getTransactionalEntityManager(EntityManagerFactory emf) throws IllegalStateException { Assert.state(emf != null, "No EntityManagerFactory specified"); return EntityManagerFactoryUtils.getTransactionalEntityManager(emf); }
[ "protected", "EntityManager", "getTransactionalEntityManager", "(", "EntityManagerFactory", "emf", ")", "throws", "IllegalStateException", "{", "Assert", ".", "state", "(", "emf", "!=", "null", ",", "\"No EntityManagerFactory specified\"", ")", ";", "return", "EntityManag...
Obtain the transactional EntityManager for this accessor's EntityManagerFactory, if any. @return the transactional EntityManager, or <code>null</code> if none @throws IllegalStateException if this accessor is not configured with an EntityManagerFactory @see EntityManagerFactoryUtils#getTransactionalEntityManager(javax.persistence.EntityManagerFactory) @see EntityManagerFactoryUtils#getTransactionalEntityManager(javax.persistence.EntityManagerFactory, java.util.Map)
[ "Obtain", "the", "transactional", "EntityManager", "for", "this", "accessor", "s", "EntityManagerFactory", "if", "any", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-rdbm/src/main/java/org/apereo/portal/jpa/OpenEntityManagerAspect.java#L99-L103
train
Jasig/uPortal
uPortal-rdbm/src/main/java/org/apereo/portal/jpa/OpenEntityManagerAspect.java
OpenEntityManagerAspect.getEntityManagerFactory
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; }
java
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; }
[ "protected", "EntityManagerFactory", "getEntityManagerFactory", "(", "OpenEntityManager", "openEntityManager", ")", "{", "final", "CacheKey", "key", "=", "this", ".", "createEntityManagerFactoryKey", "(", "openEntityManager", ")", ";", "EntityManagerFactory", "emf", "=", ...
Get the EntityManagerFactory that this filter should use. @return the EntityManagerFactory to use @see #lookupEntityManagerFactory(OpenEntityManager)
[ "Get", "the", "EntityManagerFactory", "that", "this", "filter", "should", "use", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-rdbm/src/main/java/org/apereo/portal/jpa/OpenEntityManagerAspect.java#L111-L119
train
Jasig/uPortal
uPortal-rdbm/src/main/java/org/apereo/portal/jpa/OpenEntityManagerAspect.java
OpenEntityManagerAspect.lookupEntityManagerFactory
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); } }
java
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); } }
[ "protected", "EntityManagerFactory", "lookupEntityManagerFactory", "(", "OpenEntityManager", "openEntityManager", ")", "{", "String", "emfBeanName", "=", "openEntityManager", ".", "name", "(", ")", ";", "String", "puName", "=", "openEntityManager", ".", "unitName", "(",...
Look up the EntityManagerFactory that this filter should use. <p>The default implementation looks for a bean with the specified name in Spring's root application context. @return the EntityManagerFactory to use @see #getEntityManagerFactoryBeanName
[ "Look", "up", "the", "EntityManagerFactory", "that", "this", "filter", "should", "use", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-rdbm/src/main/java/org/apereo/portal/jpa/OpenEntityManagerAspect.java#L130-L146
train
Jasig/uPortal
uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/SmartCache.java
SmartCache.put
@Override public synchronized Object put(Object key, Object value) { ValueWrapper valueWrapper = new ValueWrapper(value); return super.put(key, valueWrapper); }
java
@Override public synchronized Object put(Object key, Object value) { ValueWrapper valueWrapper = new ValueWrapper(value); return super.put(key, valueWrapper); }
[ "@", "Override", "public", "synchronized", "Object", "put", "(", "Object", "key", ",", "Object", "value", ")", "{", "ValueWrapper", "valueWrapper", "=", "new", "ValueWrapper", "(", "value", ")", ";", "return", "super", ".", "put", "(", "key", ",", "valueWr...
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. @param key the key, typically a String @param value the value @return the previous value of the specified key in this hashtable, or null if it did not have one.
[ "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", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/SmartCache.java#L80-L84
train
Jasig/uPortal
uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/SmartCache.java
SmartCache.put
public synchronized Object put(Object key, Object value, long lCacheInterval) { ValueWrapper valueWrapper = new ValueWrapper(value, lCacheInterval); return super.put(key, valueWrapper); }
java
public synchronized Object put(Object key, Object value, long lCacheInterval) { ValueWrapper valueWrapper = new ValueWrapper(value, lCacheInterval); return super.put(key, valueWrapper); }
[ "public", "synchronized", "Object", "put", "(", "Object", "key", ",", "Object", "value", ",", "long", "lCacheInterval", ")", "{", "ValueWrapper", "valueWrapper", "=", "new", "ValueWrapper", "(", "value", ",", "lCacheInterval", ")", ";", "return", "super", ".",...
Add a new value to the cache @param key the key, typically a String @param value the value @param lCacheInterval an expiration timeout value, in seconds, which will override the default cache value just for this item. If a negative timeout value is specified, the value will be cached indefinitely. @return the cached object
[ "Add", "a", "new", "value", "to", "the", "cache" ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/SmartCache.java#L96-L99
train
Jasig/uPortal
uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/SmartCache.java
SmartCache.get
@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; }
java
@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; }
[ "@", "Override", "public", "synchronized", "Object", "get", "(", "Object", "key", ")", "{", "ValueWrapper", "valueWrapper", "=", "(", "ValueWrapper", ")", "super", ".", "get", "(", "key", ")", ";", "if", "(", "valueWrapper", "!=", "null", ")", "{", "// C...
Get an object from the cache. @param key the key, typically a String @return the value to which the key is mapped in this cache; null if the key is not mapped to any value in this cache.
[ "Get", "an", "object", "from", "the", "cache", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/SmartCache.java#L108-L122
train
Jasig/uPortal
uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/SmartCache.java
SmartCache.sweepCache
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); } } }
java
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); } } }
[ "protected", "void", "sweepCache", "(", ")", "{", "for", "(", "Iterator", "keyIterator", "=", "keySet", "(", ")", ".", "iterator", "(", ")", ";", "keyIterator", ".", "hasNext", "(", ")", ";", ")", "{", "Object", "key", "=", "keyIterator", ".", "next", ...
Removes from the cache values which have expired.
[ "Removes", "from", "the", "cache", "values", "which", "have", "expired", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/utils/SmartCache.java#L125-L136
train
Jasig/uPortal
uPortal-security/uPortal-security-mvc/src/main/java/org/apereo/portal/security/filter/CorsFilter.java
CorsFilter.getInitParameter
private String getInitParameter(String name, String defaultValue) { String value = getInitParameter(name); if (value != null) { return value; } return defaultValue; }
java
private String getInitParameter(String name, String defaultValue) { String value = getInitParameter(name); if (value != null) { return value; } return defaultValue; }
[ "private", "String", "getInitParameter", "(", "String", "name", ",", "String", "defaultValue", ")", "{", "String", "value", "=", "getInitParameter", "(", "name", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "return", "value", ";", "}", "return", ...
This method returns the parameter's value if it exists, or defaultValue if not. @param name The parameter's name @param defaultValue The default value to return if the parameter does not exist @return The parameter's value or the default value if the parameter does not exist
[ "This", "method", "returns", "the", "parameter", "s", "value", "if", "it", "exists", "or", "defaultValue", "if", "not", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-mvc/src/main/java/org/apereo/portal/security/filter/CorsFilter.java#L228-L236
train
Jasig/uPortal
uPortal-security/uPortal-security-mvc/src/main/java/org/apereo/portal/security/filter/CorsFilter.java
CorsFilter.getMediaType
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; }
java
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; }
[ "private", "String", "getMediaType", "(", "String", "contentType", ")", "{", "if", "(", "contentType", "==", "null", ")", "{", "return", "null", ";", "}", "String", "result", "=", "contentType", ".", "toLowerCase", "(", "Locale", ".", "ENGLISH", ")", ";", ...
Return the lower case, trimmed value of the media type from the content type.
[ "Return", "the", "lower", "case", "trimmed", "value", "of", "the", "media", "type", "from", "the", "content", "type", "." ]
c1986542abb9acd214268f2df21c6305ad2f262b
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-security/uPortal-security-mvc/src/main/java/org/apereo/portal/security/filter/CorsFilter.java#L671-L682
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/ResultJsonParserV2.java
ResultJsonParserV2.endParsing
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; }
java
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; }
[ "public", "void", "endParsing", "(", ")", "throws", "SnowflakeSQLException", "{", "if", "(", "partialEscapedUnicode", ".", "position", "(", ")", ">", "0", ")", "{", "partialEscapedUnicode", ".", "flip", "(", ")", ";", "continueParsingInternal", "(", "partialEsca...
Check if the chunk has been parsed correctly. After calling this it is safe to acquire the output data
[ "Check", "if", "the", "chunk", "has", "been", "parsed", "correctly", ".", "After", "calling", "this", "it", "is", "safe", "to", "acquire", "the", "output", "data" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/ResultJsonParserV2.java#L72-L89
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/ResultJsonParserV2.java
ResultJsonParserV2.continueParsing
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); }
java
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); }
[ "public", "void", "continueParsing", "(", "ByteBuffer", "in", ")", "throws", "SnowflakeSQLException", "{", "if", "(", "state", "==", "State", ".", "UNINITIALIZED", ")", "{", "throw", "new", "SnowflakeSQLException", "(", "SqlState", ".", "INTERNAL_ERROR", ",", "E...
Continue parsing with the given data @param in readOnly byteBuffer backed by an array (the data to be reed is from position to limit)
[ "Continue", "parsing", "with", "the", "given", "data" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/ResultJsonParserV2.java#L96-L127
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/StmtUtil.java
StmtUtil.cancel
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()); } }
java
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()); } }
[ "public", "static", "void", "cancel", "(", "StmtInput", "stmtInput", ")", "throws", "SFException", ",", "SnowflakeSQLException", "{", "HttpPost", "httpRequest", "=", "null", ";", "AssertUtil", ".", "assertTrue", "(", "stmtInput", ".", "serverUrl", "!=", "null", ...
Cancel a statement identifiable by a request id @param stmtInput input statement @throws SFException if there is an internal exception @throws SnowflakeSQLException if failed to cancel the statement
[ "Cancel", "a", "statement", "identifiable", "by", "a", "request", "id" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/StmtUtil.java#L706-L786
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/StmtUtil.java
StmtUtil.checkStageManageCommand
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('\n') > 0) { trimmedSql = trimmedSql.substring(trimmedSql.indexOf('\n')); 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; } }
java
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('\n') > 0) { trimmedSql = trimmedSql.substring(trimmedSql.indexOf('\n')); 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; } }
[ "static", "public", "SFStatementType", "checkStageManageCommand", "(", "String", "sql", ")", "{", "if", "(", "sql", "==", "null", ")", "{", "return", "null", ";", "}", "String", "trimmedSql", "=", "sql", ".", "trim", "(", ")", ";", "// skip commenting prefix...
A simple function to check if the statement is related to manipulate stage. @param sql a SQL statement/command @return PUT/GET/LIST/RM if statment belongs to one of them, otherwise return NULL
[ "A", "simple", "function", "to", "check", "if", "the", "statement", "is", "related", "to", "manipulate", "stage", "." ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/StmtUtil.java#L795-L867
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/telemetryOOB/TelemetryService.java
TelemetryService.flush
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); } }
java
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); } }
[ "public", "void", "flush", "(", ")", "{", "if", "(", "!", "enabled", ")", "{", "return", ";", "}", "if", "(", "!", "queue", ".", "isEmpty", "(", ")", ")", "{", "// start a new thread to upload without blocking the current thread", "Runnable", "runUpload", "=",...
force to flush events in the queue
[ "force", "to", "flush", "events", "in", "the", "queue" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/telemetryOOB/TelemetryService.java#L352-L364
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/telemetryOOB/TelemetryService.java
TelemetryService.exportQueueToString
public String exportQueueToString() { JSONArray logs = new JSONArray(); while (!queue.isEmpty()) { logs.add(queue.poll()); } return SecretDetector.maskAWSSecret(logs.toString()); }
java
public String exportQueueToString() { JSONArray logs = new JSONArray(); while (!queue.isEmpty()) { logs.add(queue.poll()); } return SecretDetector.maskAWSSecret(logs.toString()); }
[ "public", "String", "exportQueueToString", "(", ")", "{", "JSONArray", "logs", "=", "new", "JSONArray", "(", ")", ";", "while", "(", "!", "queue", ".", "isEmpty", "(", ")", ")", "{", "logs", ".", "add", "(", "queue", ".", "poll", "(", ")", ")", ";"...
convert a list of json objects to a string @return the result json string
[ "convert", "a", "list", "of", "json", "objects", "to", "a", "string" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/telemetryOOB/TelemetryService.java#L371-L379
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/telemetryOOB/TelemetryService.java
TelemetryService.logHttpRequestTelemetryEvent
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); } }
java
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); } }
[ "public", "void", "logHttpRequestTelemetryEvent", "(", "String", "eventName", ",", "HttpRequestBase", "request", ",", "int", "injectSocketTimeout", ",", "AtomicBoolean", "canceling", ",", "boolean", "withoutCookies", ",", "boolean", "includeRetryParameters", ",", "boolean...
log error http response to telemetry
[ "log", "error", "http", "response", "to", "telemetry" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/telemetryOOB/TelemetryService.java#L469-L532
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/SnowflakeResultChunk.java
SnowflakeResultChunk.getCell
public final Object getCell(int rowIdx, int colIdx) { if (resultData != null) { return extractCell(resultData, rowIdx, colIdx); } return data.get(colCount * rowIdx + colIdx); }
java
public final Object getCell(int rowIdx, int colIdx) { if (resultData != null) { return extractCell(resultData, rowIdx, colIdx); } return data.get(colCount * rowIdx + colIdx); }
[ "public", "final", "Object", "getCell", "(", "int", "rowIdx", ",", "int", "colIdx", ")", "{", "if", "(", "resultData", "!=", "null", ")", "{", "return", "extractCell", "(", "resultData", ",", "rowIdx", ",", "colIdx", ")", ";", "}", "return", "data", "....
Creates a String object for the given cell @param rowIdx zero based row @param colIdx zero based column @return String
[ "Creates", "a", "String", "object", "for", "the", "given", "cell" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/SnowflakeResultChunk.java#L140-L147
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/SnowflakeResultChunk.java
SnowflakeResultChunk.ensureRowsComplete
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); } }
java
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); } }
[ "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", "(", "SqlS...
Checks that all data has been added after parsing. @throws SnowflakeSQLException when rows are not all downloaded
[ "Checks", "that", "all", "data", "has", "been", "added", "after", "parsing", "." ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/SnowflakeResultChunk.java#L211-L226
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/HttpUtil.java
HttpUtil.buildHttpClient
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); } }
java
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); } }
[ "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", "De...
Build an Http client using our set of default. @param insecureMode skip OCSP revocation check if true or false. @param ocspCacheFile OCSP response cache file. If null, the default OCSP response file will be used. @return HttpClient object
[ "Build", "an", "Http", "client", "using", "our", "set", "of", "default", "." ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/HttpUtil.java#L98-L181
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/HttpUtil.java
HttpUtil.initHttpClient
public static CloseableHttpClient initHttpClient(boolean insecureMode, File ocspCacheFile) { if (httpClient == null) { synchronized (HttpUtil.class) { if (httpClient == null) { httpClient = buildHttpClient( insecureMode, ocspCacheFile, enableOcspResponseCacheServer()); } } } return httpClient; }
java
public static CloseableHttpClient initHttpClient(boolean insecureMode, File ocspCacheFile) { if (httpClient == null) { synchronized (HttpUtil.class) { if (httpClient == null) { httpClient = buildHttpClient( insecureMode, ocspCacheFile, enableOcspResponseCacheServer()); } } } return httpClient; }
[ "public", "static", "CloseableHttpClient", "initHttpClient", "(", "boolean", "insecureMode", ",", "File", "ocspCacheFile", ")", "{", "if", "(", "httpClient", "==", "null", ")", "{", "synchronized", "(", "HttpUtil", ".", "class", ")", "{", "if", "(", "httpClien...
Accessor for the HTTP client singleton. @param insecureMode skip OCSP revocation check if true. @param ocspCacheFile OCSP response cache file name. if null, the default file will be used. @return HttpClient object shared across all connections
[ "Accessor", "for", "the", "HTTP", "client", "singleton", "." ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/HttpUtil.java#L201-L217
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/HttpUtil.java
HttpUtil.getDefaultRequestConfigWithSocketTimeout
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(); }
java
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(); }
[ "public", "static", "RequestConfig", "getDefaultRequestConfigWithSocketTimeout", "(", "int", "soTimeoutMs", ",", "boolean", "withoutCookies", ")", "{", "getHttpClient", "(", ")", ";", "final", "String", "cookieSpec", "=", "withoutCookies", "?", "IGNORE_COOKIES", ":", ...
Return a request configuration inheriting from the default request configuration of the shared HttpClient with a different socket timeout. @param soTimeoutMs - custom socket timeout in milli-seconds @param withoutCookies - whether this request should ignore cookies or not @return RequestConfig object
[ "Return", "a", "request", "configuration", "inheriting", "from", "the", "default", "request", "configuration", "of", "the", "shared", "HttpClient", "with", "a", "different", "socket", "timeout", "." ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/HttpUtil.java#L250-L260
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/HttpUtil.java
HttpUtil.executeRequestWithoutCookies
static String executeRequestWithoutCookies(HttpRequestBase httpRequest, int retryTimeout, int injectSocketTimeout, AtomicBoolean canceling) throws SnowflakeSQLException, IOException { return executeRequestInternal( httpRequest, retryTimeout, injectSocketTimeout, canceling, true, false, true); }
java
static String executeRequestWithoutCookies(HttpRequestBase httpRequest, int retryTimeout, int injectSocketTimeout, AtomicBoolean canceling) throws SnowflakeSQLException, IOException { return executeRequestInternal( httpRequest, retryTimeout, injectSocketTimeout, canceling, true, false, true); }
[ "static", "String", "executeRequestWithoutCookies", "(", "HttpRequestBase", "httpRequest", ",", "int", "retryTimeout", ",", "int", "injectSocketTimeout", ",", "AtomicBoolean", "canceling", ")", "throws", "SnowflakeSQLException", ",", "IOException", "{", "return", "execute...
Executes a HTTP request with the cookie spec set to IGNORE_COOKIES @param httpRequest HttpRequestBase @param retryTimeout retry timeout @param injectSocketTimeout injecting socket timeout @param canceling canceling? @return response @throws SnowflakeSQLException if Snowflake error occurs @throws IOException raises if a general IO error occurs
[ "Executes", "a", "HTTP", "request", "with", "the", "cookie", "spec", "set", "to", "IGNORE_COOKIES" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/HttpUtil.java#L319-L333
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/HttpUtil.java
HttpUtil.executeRequest
public static String executeRequest(HttpRequestBase httpRequest, int retryTimeout, int injectSocketTimeout, AtomicBoolean canceling) throws SnowflakeSQLException, IOException { return executeRequest( httpRequest, retryTimeout, injectSocketTimeout, canceling, false); }
java
public static String executeRequest(HttpRequestBase httpRequest, int retryTimeout, int injectSocketTimeout, AtomicBoolean canceling) throws SnowflakeSQLException, IOException { return executeRequest( httpRequest, retryTimeout, injectSocketTimeout, canceling, false); }
[ "public", "static", "String", "executeRequest", "(", "HttpRequestBase", "httpRequest", ",", "int", "retryTimeout", ",", "int", "injectSocketTimeout", ",", "AtomicBoolean", "canceling", ")", "throws", "SnowflakeSQLException", ",", "IOException", "{", "return", "executeRe...
Executes a HTTP request for Snowflake. @param httpRequest HttpRequestBase @param retryTimeout retry timeout @param injectSocketTimeout injecting socket timeout @param canceling canceling? @return response @throws SnowflakeSQLException if Snowflake error occurs @throws IOException raises if a general IO error occurs
[ "Executes", "a", "HTTP", "request", "for", "Snowflake", "." ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/HttpUtil.java#L346-L358
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/HttpUtil.java
HttpUtil.configureCustomProxyProperties
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); } }
java
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); } }
[ "public", "static", "void", "configureCustomProxyProperties", "(", "Map", "<", "SFSessionProperty", ",", "Object", ">", "connectionPropertiesMap", ")", "{", "if", "(", "connectionPropertiesMap", ".", "containsKey", "(", "SFSessionProperty", ".", "USE_PROXY", ")", ")",...
configure custom proxy properties from connectionPropertiesMap
[ "configure", "custom", "proxy", "properties", "from", "connectionPropertiesMap" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/HttpUtil.java#L580-L603
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/SnowflakeUtil.java
SnowflakeUtil.checkErrorAndThrowExceptionSub
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); }
java
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); }
[ "static", "private", "void", "checkErrorAndThrowExceptionSub", "(", "JsonNode", "rootNode", ",", "boolean", "raiseReauthenticateError", ")", "throws", "SnowflakeSQLException", "{", "// no need to throw exception if success", "if", "(", "rootNode", ".", "path", "(", "\"succe...
Check the error in the JSON node and generate an exception based on information extracted from the node. @param rootNode json object contains error information @param raiseReauthenticateError raises SnowflakeReauthenticationRequest if true @throws SnowflakeSQLException the exception get from the error in the json
[ "Check", "the", "error", "in", "the", "JSON", "node", "and", "generate", "an", "exception", "based", "on", "information", "extracted", "from", "the", "node", "." ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/SnowflakeUtil.java#L76-L141
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/AssertUtil.java
AssertUtil.assertTrue
static void assertTrue(boolean condition, String internalErrorMesg) throws SFException { if (!condition) { throw new SFException(ErrorCode.INTERNAL_ERROR, internalErrorMesg); } }
java
static void assertTrue(boolean condition, String internalErrorMesg) throws SFException { if (!condition) { throw new SFException(ErrorCode.INTERNAL_ERROR, internalErrorMesg); } }
[ "static", "void", "assertTrue", "(", "boolean", "condition", ",", "String", "internalErrorMesg", ")", "throws", "SFException", "{", "if", "(", "!", "condition", ")", "{", "throw", "new", "SFException", "(", "ErrorCode", ".", "INTERNAL_ERROR", ",", "internalError...
Assert the condition is true, otherwise throw an internal error exception with the given message. @param condition @param internalErrorMesg @throws SFException
[ "Assert", "the", "condition", "is", "true", "otherwise", "throw", "an", "internal", "error", "exception", "with", "the", "given", "message", "." ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/AssertUtil.java#L22-L29
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/MatDesc.java
MatDesc.parse
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; } }
java
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; } }
[ "public", "static", "MatDesc", "parse", "(", "String", "matdesc", ")", "{", "if", "(", "matdesc", "==", "null", ")", "{", "return", "null", ";", "}", "try", "{", "JsonNode", "jsonNode", "=", "mapper", ".", "readTree", "(", "matdesc", ")", ";", "JsonNod...
Try to parse the material descriptor string. @param matdesc string @return The material description or null
[ "Try", "to", "parse", "the", "material", "descriptor", "string", "." ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/MatDesc.java#L94-L126
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/SnowflakeDatabaseMetaData.java
SnowflakeDatabaseMetaData.applySessionContext
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); }
java
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); }
[ "private", "SFPair", "<", "String", ",", "String", ">", "applySessionContext", "(", "String", "catalog", ",", "String", "schemaPattern", ")", "{", "if", "(", "catalog", "==", "null", "&&", "metadataRequestUseConnectionCtx", ")", "{", "catalog", "=", "session", ...
apply session context when catalog is unspecified
[ "apply", "session", "context", "when", "catalog", "is", "unspecified" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/SnowflakeDatabaseMetaData.java#L1190-L1203
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/SnowflakeDatabaseMetaData.java
SnowflakeDatabaseMetaData.getForeignKeyConstraintProperty
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; }
java
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; }
[ "private", "short", "getForeignKeyConstraintProperty", "(", "String", "property_name", ",", "String", "property", ")", "{", "short", "result", "=", "0", ";", "switch", "(", "property_name", ")", "{", "case", "\"update\"", ":", "case", "\"delete\"", ":", "switch"...
Returns the JDBC standard property string for the property string used in our show constraint commands @param property_name operation type @param property property value @return metdata property value
[ "Returns", "the", "JDBC", "standard", "property", "string", "for", "the", "property", "string", "used", "in", "our", "show", "constraint", "commands" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/SnowflakeDatabaseMetaData.java#L2052-L2093
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/SnowflakeDatabaseMetaData.java
SnowflakeDatabaseMetaData.executeAndReturnEmptyResultIfNotFound
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; }
java
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; }
[ "private", "ResultSet", "executeAndReturnEmptyResultIfNotFound", "(", "Statement", "statement", ",", "String", "sql", ",", "DBMetadataResultSetMetadata", "metadataType", ")", "throws", "SQLException", "{", "ResultSet", "resultSet", ";", "try", "{", "resultSet", "=", "st...
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
[ "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" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/SnowflakeDatabaseMetaData.java#L2813-L2835
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SessionUtil.java
SessionUtil.getAuthenticator
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; }
java
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; }
[ "static", "private", "ClientAuthnDTO", ".", "AuthenticatorType", "getAuthenticator", "(", "LoginInput", "loginInput", ")", "{", "if", "(", "loginInput", ".", "getAuthenticator", "(", ")", "!=", "null", ")", "{", "if", "(", "loginInput", ".", "getAuthenticator", ...
Returns Authenticator type @param loginInput login information @return Authenticator type
[ "Returns", "Authenticator", "type" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtil.java#L171-L208
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SessionUtil.java
SessionUtil.openSession
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); }
java
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); }
[ "static", "public", "LoginOutput", "openSession", "(", "LoginInput", "loginInput", ")", "throws", "SFException", ",", "SnowflakeSQLException", "{", "AssertUtil", ".", "assertTrue", "(", "loginInput", ".", "getServerUrl", "(", ")", "!=", "null", ",", "\"missing serve...
Open a new session @param loginInput login information @return information get after login such as token information @throws SFException if unexpected uri syntax @throws SnowflakeSQLException if failed to establish connection with snowflake
[ "Open", "a", "new", "session" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtil.java#L218-L266
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SessionUtil.java
SessionUtil.issueSession
static public LoginOutput issueSession(LoginInput loginInput) throws SFException, SnowflakeSQLException { return tokenRequest(loginInput, TokenRequestType.ISSUE); }
java
static public LoginOutput issueSession(LoginInput loginInput) throws SFException, SnowflakeSQLException { return tokenRequest(loginInput, TokenRequestType.ISSUE); }
[ "static", "public", "LoginOutput", "issueSession", "(", "LoginInput", "loginInput", ")", "throws", "SFException", ",", "SnowflakeSQLException", "{", "return", "tokenRequest", "(", "loginInput", ",", "TokenRequestType", ".", "ISSUE", ")", ";", "}" ]
Issue a session @param loginInput login information @return login output @throws SFException if unexpected uri information @throws SnowflakeSQLException if failed to renew the session
[ "Issue", "a", "session" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtil.java#L913-L917
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SessionUtil.java
SessionUtil.closeSession
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; } } }
java
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; } } }
[ "static", "public", "void", "closeSession", "(", "LoginInput", "loginInput", ")", "throws", "SFException", ",", "SnowflakeSQLException", "{", "logger", ".", "debug", "(", "\" public void close() throws SFException\"", ")", ";", "// assert the following inputs are valid", "A...
Close a session @param loginInput login information @throws SnowflakeSQLException if failed to close session @throws SFException if failed to close session
[ "Close", "a", "session" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtil.java#L1064-L1133
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SessionUtil.java
SessionUtil.federatedFlowStep3
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; }
java
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; }
[ "private", "static", "String", "federatedFlowStep3", "(", "LoginInput", "loginInput", ",", "String", "tokenUrl", ")", "throws", "SnowflakeSQLException", "{", "String", "oneTimeToken", "=", "\"\"", ";", "try", "{", "URL", "url", "=", "new", "URL", "(", "tokenUrl"...
Query IDP token url to authenticate and retrieve access token @param loginInput @param tokenUrl @return @throws SnowflakeSQLException
[ "Query", "IDP", "token", "url", "to", "authenticate", "and", "retrieve", "access", "token" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtil.java#L1206-L1242
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SessionUtil.java
SessionUtil.federatedFlowStep1
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; }
java
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; }
[ "private", "static", "JsonNode", "federatedFlowStep1", "(", "LoginInput", "loginInput", ")", "throws", "SnowflakeSQLException", "{", "JsonNode", "dataNode", "=", "null", ";", "try", "{", "URIBuilder", "fedUriBuilder", "=", "new", "URIBuilder", "(", "loginInput", "."...
Query Snowflake to obtain IDP token url and IDP SSO url @param loginInput @throws SnowflakeSQLException
[ "Query", "Snowflake", "to", "obtain", "IDP", "token", "url", "and", "IDP", "SSO", "url" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtil.java#L1287-L1341
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SessionUtil.java
SessionUtil.handleFederatedFlowError
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()); }
java
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()); }
[ "private", "static", "void", "handleFederatedFlowError", "(", "LoginInput", "loginInput", ",", "Exception", "ex", ")", "throws", "SnowflakeSQLException", "{", "if", "(", "ex", "instanceof", "IOException", ")", "{", "logger", ".", "error", "(", "\"IOException when au...
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. @param loginInput @param ex @throws SnowflakeSQLException
[ "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", "netw...
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtil.java#L1352-L1371
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SessionUtil.java
SessionUtil.getSamlResponseUsingOkta
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; }
java
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; }
[ "static", "private", "String", "getSamlResponseUsingOkta", "(", "LoginInput", "loginInput", ")", "throws", "SnowflakeSQLException", "{", "JsonNode", "dataNode", "=", "federatedFlowStep1", "(", "loginInput", ")", ";", "String", "tokenUrl", "=", "dataNode", ".", "path",...
FEDERATED FLOW See SNOW-27798 for additional details. @return saml response @throws SnowflakeSQLException
[ "FEDERATED", "FLOW", "See", "SNOW", "-", "27798", "for", "additional", "details", "." ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtil.java#L1380-L1391
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SessionUtil.java
SessionUtil.isPrefixEqual
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; }
java
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; }
[ "static", "boolean", "isPrefixEqual", "(", "String", "aUrlStr", ",", "String", "bUrlStr", ")", "throws", "MalformedURLException", "{", "URL", "aUrl", "=", "new", "URL", "(", "aUrlStr", ")", ";", "URL", "bUrl", "=", "new", "URL", "(", "bUrlStr", ")", ";", ...
Verify if two input urls have the same protocol, host, and port. @param aUrlStr a source URL string @param bUrlStr a target URL string @return true if matched otherwise false @throws MalformedURLException raises if a URL string is not valid.
[ "Verify", "if", "two", "input", "urls", "have", "the", "same", "protocol", "host", "and", "port", "." ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtil.java#L1401-L1422
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SessionUtil.java
SessionUtil.getPostBackUrlFromHTML
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; }
java
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; }
[ "static", "private", "String", "getPostBackUrlFromHTML", "(", "String", "html", ")", "{", "Document", "doc", "=", "Jsoup", ".", "parse", "(", "html", ")", ";", "Elements", "e1", "=", "doc", ".", "getElementsByTag", "(", "\"body\"", ")", ";", "Elements", "e...
Extracts post back url from the HTML returned by the IDP @param html @return
[ "Extracts", "post", "back", "url", "from", "the", "HTML", "returned", "by", "the", "IDP" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtil.java#L1430-L1437
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SessionUtil.java
SessionUtil.getCommonParams
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; }
java
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; }
[ "public", "static", "Map", "<", "String", ",", "Object", ">", "getCommonParams", "(", "JsonNode", "paramsNode", ")", "{", "Map", "<", "String", ",", "Object", ">", "parameters", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "JsonNode", "child",...
Helper function to parse a JsonNode from a GS response containing CommonParameters, emitting an EnumMap of parameters @param paramsNode parameters in JSON form @return map object including key and value pairs
[ "Helper", "function", "to", "parse", "a", "JsonNode", "from", "a", "GS", "response", "containing", "CommonParameters", "emitting", "an", "EnumMap", "of", "parameters" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtil.java#L1446-L1493
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SessionUtilExternalBrowser.java
SessionUtilExternalBrowser.getServerSocket
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()); } }
java
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()); } }
[ "protected", "ServerSocket", "getServerSocket", "(", ")", "throws", "SFException", "{", "try", "{", "return", "new", "ServerSocket", "(", "0", ",", "// free port", "0", ",", "// default number of connections", "InetAddress", ".", "getByName", "(", "\"localhost\"", "...
Gets a free port on localhost @return port number @throws SFException raised if an error occurs.
[ "Gets", "a", "free", "port", "on", "localhost" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtilExternalBrowser.java#L155-L168
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SessionUtilExternalBrowser.java
SessionUtilExternalBrowser.getSSOUrl
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()); } }
java
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()); } }
[ "private", "String", "getSSOUrl", "(", "int", "port", ")", "throws", "SFException", ",", "SnowflakeSQLException", "{", "try", "{", "String", "serverUrl", "=", "loginInput", ".", "getServerUrl", "(", ")", ";", "String", "authenticator", "=", "loginInput", ".", ...
Gets SSO URL and proof key @return SSO URL. @throws SFException if Snowflake error occurs @throws SnowflakeSQLException if Snowflake SQL error occurs
[ "Gets", "SSO", "URL", "and", "proof", "key" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtilExternalBrowser.java#L188-L254
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SessionUtilExternalBrowser.java
SessionUtilExternalBrowser.processSamlToken
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); }
java
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); }
[ "private", "void", "processSamlToken", "(", "String", "[", "]", "rets", ",", "Socket", "socket", ")", "throws", "IOException", ",", "SFException", "{", "String", "targetLine", "=", "null", ";", "String", "userAgent", "=", "null", ";", "boolean", "isPost", "=...
Receives SAML token from Snowflake via web browser @param socket socket @throws IOException if any IO error occurs @throws SFException if a HTTP request from browser is invalid
[ "Receives", "SAML", "token", "from", "Snowflake", "via", "web", "browser" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtilExternalBrowser.java#L418-L492
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SessionUtilExternalBrowser.java
SessionUtilExternalBrowser.returnToBrowser
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(); }
java
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(); }
[ "private", "void", "returnToBrowser", "(", "Socket", "socket", ")", "throws", "IOException", "{", "PrintWriter", "out", "=", "new", "PrintWriter", "(", "socket", ".", "getOutputStream", "(", ")", ",", "true", ")", ";", "List", "<", "String", ">", "content", ...
Output the message to the browser @param socket client socket @throws IOException if any IO error occurs
[ "Output", "the", "message", "to", "the", "browser" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SessionUtilExternalBrowser.java#L527-L567
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/telemetry/TelemetryUtil.java
TelemetryUtil.buildJobData
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()); }
java
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()); }
[ "public", "static", "TelemetryData", "buildJobData", "(", "String", "queryId", ",", "TelemetryField", "field", ",", "long", "value", ")", "{", "ObjectNode", "obj", "=", "mapper", ".", "createObjectNode", "(", ")", ";", "obj", ".", "put", "(", "TYPE", ",", ...
Create a simple TelemetryData instance for Job metrics using given parameters @param queryId the id of the query @param field the field to log (represents the "type" field in telemetry) @param value the value to log for the field @return TelemetryData instance constructed from parameters
[ "Create", "a", "simple", "TelemetryData", "instance", "for", "Job", "metrics", "using", "given", "parameters" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/telemetry/TelemetryUtil.java#L24-L31
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/cloud/storage/SnowflakeS3Client.java
SnowflakeS3Client.download
@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!"); }
java
@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!"); }
[ "@", "Override", "public", "void", "download", "(", "SFSession", "connection", ",", "String", "command", ",", "String", "localLocation", ",", "String", "destFileName", ",", "int", "parallelism", ",", "String", "remoteStorageLocation", ",", "String", "stageFilePath",...
Download a file from S3. @param connection connection object @param command command to download file @param localLocation local file path @param destFileName destination file name @param parallelism number of threads for parallel downloading @param remoteStorageLocation s3 bucket name @param stageFilePath stage file path @param stageRegion region name where the stage persists @throws SnowflakeSQLException if download failed without an exception @throws SnowflakeSQLException if failed to decrypt downloaded file @throws SnowflakeSQLException if file metadata is incomplete
[ "Download", "a", "file", "from", "S3", "." ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/cloud/storage/SnowflakeS3Client.java#L268-L350
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.resetOCSPResponseCacherServerURL
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)); } } }
java
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)); } } }
[ "static", "void", "resetOCSPResponseCacherServerURL", "(", "String", "ocspCacheServerUrl", ")", "{", "if", "(", "ocspCacheServerUrl", "==", "null", "||", "SF_OCSP_RESPONSE_CACHE_SERVER_RETRY_URL_PATTERN", "!=", "null", ")", "{", "return", ";", "}", "SF_OCSP_RESPONSE_CACHE...
Reset OCSP Cache server URL @param ocspCacheServerUrl OCSP Cache server URL
[ "Reset", "OCSP", "Cache", "server", "URL" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L443-L476
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.getTrustManager
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); } }
java
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); } }
[ "private", "X509TrustManager", "getTrustManager", "(", "String", "algorithm", ")", "{", "try", "{", "TrustManagerFactory", "factory", "=", "TrustManagerFactory", ".", "getInstance", "(", "algorithm", ")", ";", "factory", ".", "init", "(", "(", "KeyStore", ")", "...
Get TrustManager for the algorithm. This is mainly used to get the JVM default trust manager and cache all of the root CA. @param algorithm algorithm. @return TrustManager object.
[ "Get", "TrustManager", "for", "the", "algorithm", ".", "This", "is", "mainly", "used", "to", "get", "the", "JVM", "default", "trust", "manager", "and", "cache", "all", "of", "the", "root", "CA", "." ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L486-L525
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.validateRevocationStatus
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; } } }
java
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; } } }
[ "void", "validateRevocationStatus", "(", "X509Certificate", "[", "]", "chain", ",", "String", "peerHost", ")", "throws", "CertificateException", "{", "final", "List", "<", "Certificate", ">", "bcChain", "=", "convertToBouncyCastleCertificate", "(", "chain", ")", ";"...
Certificate Revocation checks @param chain chain of certificates attached. @param peerHost Hostname of the server @throws CertificateException if any certificate validation fails
[ "Certificate", "Revocation", "checks" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L585-L631
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.executeRevocationStatusChecks
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."); } }
java
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."); } }
[ "private", "void", "executeRevocationStatusChecks", "(", "List", "<", "SFPair", "<", "Certificate", ",", "Certificate", ">", ">", "pairIssuerSubjectList", ",", "String", "peerHost", ")", "throws", "CertificateException", "{", "long", "currentTimeSecond", "=", "new", ...
Executes the revocation status checks for all chained certificates @param pairIssuerSubjectList a list of pair of issuer and subject certificates. @throws CertificateException raises if any error occurs.
[ "Executes", "the", "revocation", "status", "checks", "for", "all", "chained", "certificates" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L639-L655
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.encodeCacheKey
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; }
java
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; }
[ "private", "static", "String", "encodeCacheKey", "(", "OcspResponseCacheKey", "ocsp_cache_key", ")", "{", "try", "{", "DigestCalculator", "digest", "=", "new", "SHA1DigestCalculator", "(", ")", ";", "AlgorithmIdentifier", "algo", "=", "digest", ".", "getAlgorithmIdent...
Convert cache key to base64 encoded cert id @param ocsp_cache_key Cache key to encode
[ "Convert", "cache", "key", "to", "base64", "encoded", "cert", "id" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L663-L680
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.isCached
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; }
java
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; }
[ "private", "boolean", "isCached", "(", "List", "<", "SFPair", "<", "Certificate", ",", "Certificate", ">", ">", "pairIssuerSubjectList", ")", "{", "long", "currentTimeSecond", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", "/", "1000L", ";", "bool...
Is OCSP Response cached? @param pairIssuerSubjectList a list of pair of issuer and subject certificates @return true if all of OCSP response are cached else false
[ "Is", "OCSP", "Response", "cached?" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L844-L894
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.CertificateIDToString
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())); }
java
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())); }
[ "private", "static", "String", "CertificateIDToString", "(", "CertificateID", "certificateID", ")", "{", "return", "String", ".", "format", "(", "\"CertID. NameHash: %s, KeyHash: %s, Serial Number: %s\"", ",", "byteToHexString", "(", "certificateID", ".", "getIssuerNameHash",...
CertificateID to string @param certificateID CertificateID @return a string representation of CertificateID
[ "CertificateID", "to", "string" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L903-L911
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.decodeCacheFromJSON
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)); } }
java
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)); } }
[ "private", "static", "SFPair", "<", "OcspResponseCacheKey", ",", "SFPair", "<", "Long", ",", "String", ">", ">", "decodeCacheFromJSON", "(", "Map", ".", "Entry", "<", "String", ",", "JsonNode", ">", "elem", ")", "throws", "IOException", "{", "long", "current...
Decodes OCSP Response Cache key from JSON @param elem A JSON element @return OcspResponseCacheKey object
[ "Decodes", "OCSP", "Response", "Cache", "key", "from", "JSON" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L919-L952
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.encodeCacheToJSON
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; }
java
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; }
[ "private", "static", "ObjectNode", "encodeCacheToJSON", "(", ")", "{", "try", "{", "ObjectNode", "out", "=", "OBJECT_MAPPER", ".", "createObjectNode", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "OcspResponseCacheKey", ",", "SFPair", "<", "Long", ",...
Encode OCSP Response Cache to JSON @return JSON object
[ "Encode", "OCSP", "Response", "Cache", "to", "JSON" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L959-L991
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.validateRevocationStatusMain
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); } }
java
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); } }
[ "private", "void", "validateRevocationStatusMain", "(", "SFPair", "<", "Certificate", ",", "Certificate", ">", "pairIssuerSubject", ",", "String", "ocspRespB64", ")", "throws", "CertificateException", "{", "try", "{", "OCSPResp", "ocspResp", "=", "b64ToOCSPResp", "(",...
Validates the certificate revocation status @param pairIssuerSubject a pair of issuer and subject certificates @param ocspRespB64 Base64 encoded OCSP Response object @throws CertificateException raises if any other error occurs
[ "Validates", "the", "certificate", "revocation", "status" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L1240-L1296
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.validateBasicOcspResponse
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."); }
java
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."); }
[ "private", "void", "validateBasicOcspResponse", "(", "Date", "currentTime", ",", "BasicOCSPResp", "basicOcspResp", ")", "throws", "CertificateEncodingException", "{", "for", "(", "SingleResp", "singleResps", ":", "basicOcspResp", ".", "getResponses", "(", ")", ")", "{...
Validates OCSP Basic OCSP response. @param currentTime the current timestamp. @param basicOcspResp BasicOcspResponse data. @throws CertificateEncodingException raises if any failure occurs.
[ "Validates", "OCSP", "Basic", "OCSP", "response", "." ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L1305-L1355
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.verifySignature
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); } }
java
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); } }
[ "private", "static", "void", "verifySignature", "(", "X509CertificateHolder", "cert", ",", "byte", "[", "]", "sig", ",", "byte", "[", "]", "data", ",", "AlgorithmIdentifier", "idf", ")", "throws", "CertificateException", "{", "try", "{", "String", "algorithm", ...
Verifies the signature of the data @param cert a certificate for public key. @param sig signature in a byte array. @param data data in a byte array. @param idf algorithm identifier object. @throws CertificateException raises if the verification fails.
[ "Verifies", "the", "signature", "of", "the", "data" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L1366-L1397
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.byteToHexString
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); }
java
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); }
[ "private", "static", "String", "byteToHexString", "(", "byte", "[", "]", "bytes", ")", "{", "final", "char", "[", "]", "hexArray", "=", "\"0123456789ABCDEF\"", ".", "toCharArray", "(", ")", ";", "char", "[", "]", "hexChars", "=", "new", "char", "[", "byt...
Converts Byte array to hex string @param bytes a byte array @return a string in hexadecimal code
[ "Converts", "Byte", "array", "to", "hex", "string" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L1405-L1416
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.createRequest
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 certHolder = new X509CertificateHolder(issuer.getEncoded()); CertificateID certId = new CertificateID( digest, certHolder, subject.getSerialNumber().getValue()); gen.addRequest(certId); return gen.build(); } catch (OCSPException | IOException ex) { throw new RuntimeException("Failed to build a OCSPReq."); } }
java
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 certHolder = new X509CertificateHolder(issuer.getEncoded()); CertificateID certId = new CertificateID( digest, certHolder, subject.getSerialNumber().getValue()); gen.addRequest(certId); return gen.build(); } catch (OCSPException | IOException ex) { throw new RuntimeException("Failed to build a OCSPReq."); } }
[ "private", "OCSPReq", "createRequest", "(", "SFPair", "<", "Certificate", ",", "Certificate", ">", "pairIssuerSubject", ")", "{", "Certificate", "issuer", "=", "pairIssuerSubject", ".", "left", ";", "Certificate", "subject", "=", "pairIssuerSubject", ".", "right", ...
Creates a OCSP Request @param pairIssuerSubject a pair of issuer and subject certificates @return OCSPReq object
[ "Creates", "a", "OCSP", "Request" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L1424-L1443
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.convertToBouncyCastleCertificate
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) { throw new RuntimeException("Failed to decode the certificate DER data"); } } return bcChain; }
java
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) { throw new RuntimeException("Failed to decode the certificate DER data"); } } return bcChain; }
[ "private", "List", "<", "Certificate", ">", "convertToBouncyCastleCertificate", "(", "X509Certificate", "[", "]", "chain", ")", "{", "final", "List", "<", "Certificate", ">", "bcChain", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "X509Certificate...
Converts X509Certificate to Bouncy Castle Certificate @param chain an array of X509Certificate @return a list of Bouncy Castle Certificate
[ "Converts", "X509Certificate", "to", "Bouncy", "Castle", "Certificate" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L1452-L1468
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.getPairIssuerSubject
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.getIssuer().equals(bcCert.getSubject())) { continue; // skipping ROOT CA } if (i < len - 1) { pairIssuerSubject.add(SFPair.of(bcChain.get(i + 1), bcChain.get(i))); } else { synchronized (ROOT_CA_LOCK) { // no root CA certificate is attached in the certificate chain, so // getting one from the root CA from JVM. Certificate issuer = ROOT_CA.get(bcCert.getIssuer().hashCode()); if (issuer == null) { throw new RuntimeException("Failed to find the root CA."); } pairIssuerSubject.add(SFPair.of(issuer, bcChain.get(i))); } } } return pairIssuerSubject; }
java
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.getIssuer().equals(bcCert.getSubject())) { continue; // skipping ROOT CA } if (i < len - 1) { pairIssuerSubject.add(SFPair.of(bcChain.get(i + 1), bcChain.get(i))); } else { synchronized (ROOT_CA_LOCK) { // no root CA certificate is attached in the certificate chain, so // getting one from the root CA from JVM. Certificate issuer = ROOT_CA.get(bcCert.getIssuer().hashCode()); if (issuer == null) { throw new RuntimeException("Failed to find the root CA."); } pairIssuerSubject.add(SFPair.of(issuer, bcChain.get(i))); } } } return pairIssuerSubject; }
[ "private", "List", "<", "SFPair", "<", "Certificate", ",", "Certificate", ">", ">", "getPairIssuerSubject", "(", "List", "<", "Certificate", ">", "bcChain", ")", "{", "List", "<", "SFPair", "<", "Certificate", ",", "Certificate", ">", ">", "pairIssuerSubject",...
Creates a pair of Issuer and Subject certificates @param bcChain a list of bouncy castle Certificate @return a list of paif of Issuer and Subject certificates
[ "Creates", "a", "pair", "of", "Issuer", "and", "Subject", "certificates" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L1476-L1507
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.getOcspUrls
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 (Enumeration en = bcExts.oids(); en.hasMoreElements(); ) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) en.nextElement(); Extension bcExt = bcExts.getExtension(oid); if (bcExt.getExtnId() == Extension.authorityInfoAccess) { // OCSP URLS are included in authorityInfoAccess DLSequence seq = (DLSequence) bcExt.getParsedValue(); for (ASN1Encodable asn : seq) { ASN1Encodable[] pairOfAsn = ((DLSequence) asn).toArray(); if (pairOfAsn.length == 2) { ASN1ObjectIdentifier key = (ASN1ObjectIdentifier) pairOfAsn[0]; if (key == OIDocsp) { // ensure OCSP and not CRL GeneralName gn = GeneralName.getInstance(pairOfAsn[1]); ocsp.add(gn.getName().toString()); } } } } } return ocsp; }
java
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 (Enumeration en = bcExts.oids(); en.hasMoreElements(); ) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) en.nextElement(); Extension bcExt = bcExts.getExtension(oid); if (bcExt.getExtnId() == Extension.authorityInfoAccess) { // OCSP URLS are included in authorityInfoAccess DLSequence seq = (DLSequence) bcExt.getParsedValue(); for (ASN1Encodable asn : seq) { ASN1Encodable[] pairOfAsn = ((DLSequence) asn).toArray(); if (pairOfAsn.length == 2) { ASN1ObjectIdentifier key = (ASN1ObjectIdentifier) pairOfAsn[0]; if (key == OIDocsp) { // ensure OCSP and not CRL GeneralName gn = GeneralName.getInstance(pairOfAsn[1]); ocsp.add(gn.getName().toString()); } } } } } return ocsp; }
[ "private", "Set", "<", "String", ">", "getOcspUrls", "(", "Certificate", "bcCert", ")", "{", "TBSCertificate", "bcTbsCert", "=", "bcCert", ".", "getTBSCertificate", "(", ")", ";", "Extensions", "bcExts", "=", "bcTbsCert", ".", "getExtensions", "(", ")", ";", ...
Gets OCSP URLs associated with the certificate. @param bcCert Bouncy Castle Certificate @return a set of OCSP URLs
[ "Gets", "OCSP", "URLs", "associated", "with", "the", "certificate", "." ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L1515-L1550
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.isValidityRange
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.getTime() + tolerableValidity; }
java
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.getTime() + tolerableValidity; }
[ "private", "static", "boolean", "isValidityRange", "(", "Date", "currentTime", ",", "Date", "thisUpdate", ",", "Date", "nextUpdate", ")", "{", "long", "tolerableValidity", "=", "calculateTolerableVadility", "(", "thisUpdate", ",", "nextUpdate", ")", ";", "return", ...
Checks the validity @param currentTime the current time @param thisUpdate the last update timestamp @param nextUpdate the next update timestamp @return true if valid or false
[ "Checks", "the", "validity" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L1592-L1597
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.processKeyUpdateDirective
private void processKeyUpdateDirective(String issuer, String ssd) { try { /** * Get unverified part of the JWT to extract issuer. * */ //PlainJWT jwt_unverified = PlainJWT.parse(ssd); 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. Invalid SSD"); return; } if (jwt_issuer.equals("dep1")) { ssd_pubKey = ssdManager.getPubKey("dep1"); } else { ssd_pubKey = ssdManager.getPubKey("dep2"); } if (ssd_pubKey == null) { LOGGER.debug("Invalid SSD"); return; } String publicKeyContent = ssd_pubKey.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", ""); KeyFactory kf = KeyFactory.getInstance("RSA"); X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyContent)); RSAPublicKey rsaPubKey = (RSAPublicKey) kf.generatePublic(keySpecX509); /** * Verify signature of the JWT Token */ SignedJWT jwt_token_verified = SignedJWT.parse(ssd); JWSVerifier jwsVerifier = new RSASSAVerifier(rsaPubKey); try { if (jwt_token_verified.verify(jwsVerifier)) { /** * verify nbf time */ long cur_time = System.currentTimeMillis(); Date nbf = jwt_token_verified.getJWTClaimsSet().getNotBeforeTime(); //long nbf = jwt_token_verified.getJWTClaimsSet().getLongClaim("nbf"); //double nbf = jwt_token_verified.getJWTClaimsSet().getDoubleClaim("nbf"); if (cur_time < nbf.getTime()) { LOGGER.debug("The SSD token is not yet valid. Current time less than Not Before Time"); return; } float key_ver = Float.parseFloat(jwt_token_verified.getJWTClaimsSet().getStringClaim("keyVer")); if (key_ver <= ssdManager.getPubKeyVer(jwt_issuer)) { return; } ssdManager.updateKey(jwt_issuer, jwt_token_verified.getJWTClaimsSet().getStringClaim("pubKey"), key_ver); } } catch (Throwable ex) { LOGGER.debug("Failed to verify JWT Token"); throw ex; } } catch (Throwable ex) { LOGGER.debug("Failed to parse JWT Token, aborting"); } }
java
private void processKeyUpdateDirective(String issuer, String ssd) { try { /** * Get unverified part of the JWT to extract issuer. * */ //PlainJWT jwt_unverified = PlainJWT.parse(ssd); 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. Invalid SSD"); return; } if (jwt_issuer.equals("dep1")) { ssd_pubKey = ssdManager.getPubKey("dep1"); } else { ssd_pubKey = ssdManager.getPubKey("dep2"); } if (ssd_pubKey == null) { LOGGER.debug("Invalid SSD"); return; } String publicKeyContent = ssd_pubKey.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", ""); KeyFactory kf = KeyFactory.getInstance("RSA"); X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyContent)); RSAPublicKey rsaPubKey = (RSAPublicKey) kf.generatePublic(keySpecX509); /** * Verify signature of the JWT Token */ SignedJWT jwt_token_verified = SignedJWT.parse(ssd); JWSVerifier jwsVerifier = new RSASSAVerifier(rsaPubKey); try { if (jwt_token_verified.verify(jwsVerifier)) { /** * verify nbf time */ long cur_time = System.currentTimeMillis(); Date nbf = jwt_token_verified.getJWTClaimsSet().getNotBeforeTime(); //long nbf = jwt_token_verified.getJWTClaimsSet().getLongClaim("nbf"); //double nbf = jwt_token_verified.getJWTClaimsSet().getDoubleClaim("nbf"); if (cur_time < nbf.getTime()) { LOGGER.debug("The SSD token is not yet valid. Current time less than Not Before Time"); return; } float key_ver = Float.parseFloat(jwt_token_verified.getJWTClaimsSet().getStringClaim("keyVer")); if (key_ver <= ssdManager.getPubKeyVer(jwt_issuer)) { return; } ssdManager.updateKey(jwt_issuer, jwt_token_verified.getJWTClaimsSet().getStringClaim("pubKey"), key_ver); } } catch (Throwable ex) { LOGGER.debug("Failed to verify JWT Token"); throw ex; } } catch (Throwable ex) { LOGGER.debug("Failed to parse JWT Token, aborting"); } }
[ "private", "void", "processKeyUpdateDirective", "(", "String", "issuer", ",", "String", "ssd", ")", "{", "try", "{", "/**\n * Get unverified part of the JWT to extract issuer.\n *\n */", "//PlainJWT jwt_unverified = PlainJWT.parse(ssd);", "SignedJWT", "jwt_signed", ...
SSD Processing Code
[ "SSD", "Processing", "Code" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L1602-L1683
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFTrustManager.java
SFTrustManager.ocspResponseToB64
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; } }
java
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; } }
[ "private", "String", "ocspResponseToB64", "(", "OCSPResp", "ocspResp", ")", "{", "if", "(", "ocspResp", "==", "null", ")", "{", "return", "null", ";", "}", "try", "{", "return", "Base64", ".", "encodeBase64String", "(", "ocspResp", ".", "getEncoded", "(", ...
OCSP Response Utils
[ "OCSP", "Response", "Utils" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFTrustManager.java#L1794-L1809
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/HeartbeatBackground.java
HeartbeatBackground.scheduleHeartbeat
private void scheduleHeartbeat() { // elapsed time in seconds since the last heartbeat long elapsedSecsSinceLastHeartBeat = System.currentTimeMillis() / 1000 - lastHeartbeatStartTimeInSecs; /* * The initial delay for the new scheduling is 0 if the elapsed * time is more than the heartbeat time interval, otherwise it is the * difference between the heartbeat time interval and the elapsed time. */ long initialDelay = Math.max(heartBeatIntervalInSecs - elapsedSecsSinceLastHeartBeat, 0); LOGGER.debug( "schedule heartbeat task with initial delay of {} seconds", initialDelay); // Creates and executes a periodic action to send heartbeats this.heartbeatFuture = this.scheduler.schedule(this, initialDelay, TimeUnit.SECONDS); }
java
private void scheduleHeartbeat() { // elapsed time in seconds since the last heartbeat long elapsedSecsSinceLastHeartBeat = System.currentTimeMillis() / 1000 - lastHeartbeatStartTimeInSecs; /* * The initial delay for the new scheduling is 0 if the elapsed * time is more than the heartbeat time interval, otherwise it is the * difference between the heartbeat time interval and the elapsed time. */ long initialDelay = Math.max(heartBeatIntervalInSecs - elapsedSecsSinceLastHeartBeat, 0); LOGGER.debug( "schedule heartbeat task with initial delay of {} seconds", initialDelay); // Creates and executes a periodic action to send heartbeats this.heartbeatFuture = this.scheduler.schedule(this, initialDelay, TimeUnit.SECONDS); }
[ "private", "void", "scheduleHeartbeat", "(", ")", "{", "// elapsed time in seconds since the last heartbeat", "long", "elapsedSecsSinceLastHeartBeat", "=", "System", ".", "currentTimeMillis", "(", ")", "/", "1000", "-", "lastHeartbeatStartTimeInSecs", ";", "/*\n * The ini...
Schedule the next heartbeat
[ "Schedule", "the", "next", "heartbeat" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/HeartbeatBackground.java#L175-L196
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/cloud/storage/StorageClientFactory.java
StorageClientFactory.createClient
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.getCredentials(), parallel, encMat, stage.getRegion()); case AZURE: return createAzureClient(stage, encMat); default: // We don't create a storage client for FS_LOCAL, // so we should only find ourselves here if an unsupported // remote storage client type is specified throw new IllegalArgumentException("Unsupported storage client specified: " + stage.getStageType().name()); } }
java
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.getCredentials(), parallel, encMat, stage.getRegion()); case AZURE: return createAzureClient(stage, encMat); default: // We don't create a storage client for FS_LOCAL, // so we should only find ourselves here if an unsupported // remote storage client type is specified throw new IllegalArgumentException("Unsupported storage client specified: " + stage.getStageType().name()); } }
[ "public", "SnowflakeStorageClient", "createClient", "(", "StageInfo", "stage", ",", "int", "parallel", ",", "RemoteStoreFileEncryptionMaterial", "encMat", ")", "throws", "SnowflakeSQLException", "{", "logger", ".", "debug", "(", "\"createClient client type={}\"", ",", "st...
Creates a storage client based on the value of stageLocationType @param stage the stage properties @param parallel the degree of parallelism to be used by the client @param encMat encryption material for the client @return a SnowflakeStorageClient interface to the instance created @throws SnowflakeSQLException if any error occurs
[ "Creates", "a", "storage", "client", "based", "on", "the", "value", "of", "stageLocationType" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/cloud/storage/StorageClientFactory.java#L57-L79
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/cloud/storage/StorageClientFactory.java
StorageClientFactory.createS3Client
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")); SnowflakeS3Client s3Client; ClientConfiguration clientConfig = new ClientConfiguration(); clientConfig.setMaxConnections(parallel + 1); clientConfig.setMaxErrorRetry(S3_TRANSFER_MAX_RETRIES); clientConfig.setDisableSocketProxy(HttpUtil.isSocksProxyDisabled()); logger.debug("s3 client configuration: maxConnection={}, connectionTimeout={}, " + "socketTimeout={}, maxErrorRetry={}", clientConfig.getMaxConnections(), clientConfig.getConnectionTimeout(), clientConfig.getSocketTimeout(), clientConfig.getMaxErrorRetry()); try { s3Client = new SnowflakeS3Client(stageCredentials, clientConfig, encMat, stageRegion); } catch (Exception ex) { logger.debug("Exception creating s3 client", ex); throw ex; } logger.debug("s3 client created"); return s3Client; }
java
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")); SnowflakeS3Client s3Client; ClientConfiguration clientConfig = new ClientConfiguration(); clientConfig.setMaxConnections(parallel + 1); clientConfig.setMaxErrorRetry(S3_TRANSFER_MAX_RETRIES); clientConfig.setDisableSocketProxy(HttpUtil.isSocksProxyDisabled()); logger.debug("s3 client configuration: maxConnection={}, connectionTimeout={}, " + "socketTimeout={}, maxErrorRetry={}", clientConfig.getMaxConnections(), clientConfig.getConnectionTimeout(), clientConfig.getSocketTimeout(), clientConfig.getMaxErrorRetry()); try { s3Client = new SnowflakeS3Client(stageCredentials, clientConfig, encMat, stageRegion); } catch (Exception ex) { logger.debug("Exception creating s3 client", ex); throw ex; } logger.debug("s3 client created"); return s3Client; }
[ "private", "SnowflakeS3Client", "createS3Client", "(", "Map", "stageCredentials", ",", "int", "parallel", ",", "RemoteStoreFileEncryptionMaterial", "encMat", ",", "String", "stageRegion", ")", "throws", "SnowflakeSQLException", "{", "final", "int", "S3_TRANSFER_MAX_RETRIES"...
Creates a SnowflakeS3ClientObject which encapsulates the Amazon S3 client @param stageCredentials Map of stage credential properties @param parallel degree of parallelism @param encMat encryption material for the client @param stageRegion the region where the stage is located @return the SnowflakeS3Client instance created @throws SnowflakeSQLException failure to create the S3 client
[ "Creates", "a", "SnowflakeS3ClientObject", "which", "encapsulates", "the", "Amazon", "S3", "client" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/cloud/storage/StorageClientFactory.java#L92-L128
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/cloud/storage/StorageClientFactory.java
StorageClientFactory.createStorageMetadataObj
public StorageObjectMetadata createStorageMetadataObj(StageInfo.StageType stageType) { switch (stageType) { case S3: return new S3ObjectMetadata(); case AZURE: return new AzureObjectMetadata(); default: // An unsupported remote storage client type was specified // We don't create/implement a storage client for FS_LOCAL, // so we should never end up here while running on local file system throw new IllegalArgumentException("Unsupported stage type specified: " + stageType.name()); } }
java
public StorageObjectMetadata createStorageMetadataObj(StageInfo.StageType stageType) { switch (stageType) { case S3: return new S3ObjectMetadata(); case AZURE: return new AzureObjectMetadata(); default: // An unsupported remote storage client type was specified // We don't create/implement a storage client for FS_LOCAL, // so we should never end up here while running on local file system throw new IllegalArgumentException("Unsupported stage type specified: " + stageType.name()); } }
[ "public", "StorageObjectMetadata", "createStorageMetadataObj", "(", "StageInfo", ".", "StageType", "stageType", ")", "{", "switch", "(", "stageType", ")", "{", "case", "S3", ":", "return", "new", "S3ObjectMetadata", "(", ")", ";", "case", "AZURE", ":", "return",...
Creates a storage provider specific metadata object, accessible via the platform independent interface @param stageType determines the implementation to be created @return the implementation of StorageObjectMetadata
[ "Creates", "a", "storage", "provider", "specific", "metadata", "object", "accessible", "via", "the", "platform", "independent", "interface" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/cloud/storage/StorageClientFactory.java#L137-L154
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/cloud/storage/StorageClientFactory.java
StorageClientFactory.createAzureClient
private SnowflakeAzureClient createAzureClient(StageInfo stage, RemoteStoreFileEncryptionMaterial encMat) throws SnowflakeSQLException { logger.debug("createAzureClient encryption={}", (encMat == null ? "no" : "yes")); //TODO: implement support for encryption SNOW-33042 SnowflakeAzureClient azureClient; try { azureClient = SnowflakeAzureClient.createSnowflakeAzureClient(stage, encMat); } catch (Exception ex) { logger.debug("Exception creating Azure Storage client", ex); throw ex; } logger.debug("Azure Storage client created"); return azureClient; }
java
private SnowflakeAzureClient createAzureClient(StageInfo stage, RemoteStoreFileEncryptionMaterial encMat) throws SnowflakeSQLException { logger.debug("createAzureClient encryption={}", (encMat == null ? "no" : "yes")); //TODO: implement support for encryption SNOW-33042 SnowflakeAzureClient azureClient; try { azureClient = SnowflakeAzureClient.createSnowflakeAzureClient(stage, encMat); } catch (Exception ex) { logger.debug("Exception creating Azure Storage client", ex); throw ex; } logger.debug("Azure Storage client created"); return azureClient; }
[ "private", "SnowflakeAzureClient", "createAzureClient", "(", "StageInfo", "stage", ",", "RemoteStoreFileEncryptionMaterial", "encMat", ")", "throws", "SnowflakeSQLException", "{", "logger", ".", "debug", "(", "\"createAzureClient encryption={}\"", ",", "(", "encMat", "==", ...
Creates a SnowflakeAzureClientObject which encapsulates the Azure Storage client @param stage Stage information @param encMat encryption material for the client @return the SnowflakeS3Client instance created
[ "Creates", "a", "SnowflakeAzureClientObject", "which", "encapsulates", "the", "Azure", "Storage", "client" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/cloud/storage/StorageClientFactory.java#L164-L186
train
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/bind/BindUploader.java
BindUploader.newInstance
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 temporary directory: %s", ex.getMessage()), BindException.Type.OTHER); } }
java
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 temporary directory: %s", ex.getMessage()), BindException.Type.OTHER); } }
[ "public", "synchronized", "static", "BindUploader", "newInstance", "(", "SFSession", "session", ",", "String", "stageDir", ")", "throws", "BindException", "{", "try", "{", "Path", "bindDir", "=", "Files", ".", "createTempDirectory", "(", "PREFIX", ")", ";", "ret...
Create a new BindUploader which will upload to the given stage path Ensure temporary directory for file writing exists @param session the session to use for uploading binds @param stageDir the stage path to upload to @return BindUploader instance @throws BindException if temporary directory could not be created
[ "Create", "a", "new", "BindUploader", "which", "will", "upload", "to", "the", "given", "stage", "path", "Ensure", "temporary", "directory", "for", "file", "writing", "exists" ]
98567b5a57753f29d51446809640b969a099658f
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/bind/BindUploader.java#L174-L187
train