idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
28,700
static ClientAssertion buildJwt ( final AsymmetricKeyCredential credential , final String jwtAudience ) throws AuthenticationException { if ( credential == null ) { throw new IllegalArgumentException ( "credential is null" ) ; } final long time = System . currentTimeMillis ( ) ; final JWTClaimsSet claimsSet = new JWTClaimsSet . Builder ( ) . audience ( Collections . singletonList ( jwtAudience ) ) . issuer ( credential . getClientId ( ) ) . jwtID ( UUID . randomUUID ( ) . toString ( ) ) . notBeforeTime ( new Date ( time ) ) . expirationTime ( new Date ( time + AuthenticationConstants . AAD_JWT_TOKEN_LIFETIME_SECONDS * 1000 ) ) . subject ( credential . getClientId ( ) ) . build ( ) ; SignedJWT jwt ; try { JWSHeader . Builder builder = new Builder ( JWSAlgorithm . RS256 ) ; List < Base64 > certs = new ArrayList < Base64 > ( ) ; certs . add ( new Base64 ( credential . getPublicCertificate ( ) ) ) ; builder . x509CertChain ( certs ) ; builder . x509CertThumbprint ( new Base64URL ( credential . getPublicCertificateHash ( ) ) ) ; jwt = new SignedJWT ( builder . build ( ) , claimsSet ) ; final RSASSASigner signer = new RSASSASigner ( credential . getKey ( ) ) ; jwt . sign ( signer ) ; } catch ( final Exception e ) { throw new AuthenticationException ( e ) ; } return new ClientAssertion ( jwt . serialize ( ) ) ; }
Builds JWT object .
378
6
28,701
public static JSONArray fetchDirectoryObjectJSONArray ( JSONObject jsonObject ) throws Exception { JSONArray jsonArray = new JSONArray ( ) ; jsonArray = jsonObject . optJSONObject ( "responseMsg" ) . optJSONArray ( "value" ) ; return jsonArray ; }
This method parses an JSON Array out of a collection of JSON Objects within a string .
59
18
28,702
public static JSONObject fetchDirectoryObjectJSONObject ( JSONObject jsonObject ) throws Exception { JSONObject jObj = new JSONObject ( ) ; jObj = jsonObject . optJSONObject ( "responseMsg" ) ; return jObj ; }
This method parses an JSON Object out of a collection of JSON Objects within a string
50
17
28,703
public static String fetchNextSkiptoken ( JSONObject jsonObject ) throws Exception { String skipToken = "" ; // Parse the skip token out of the string. skipToken = jsonObject . optJSONObject ( "responseMsg" ) . optString ( "odata.nextLink" ) ; if ( ! skipToken . equalsIgnoreCase ( "" ) ) { // Remove the unnecessary prefix from the skip token. int index = skipToken . indexOf ( "$skiptoken=" ) + ( new String ( "$skiptoken=" ) ) . length ( ) ; skipToken = skipToken . substring ( index ) ; } return skipToken ; }
This method parses the skip token from a json formatted string .
138
13
28,704
public static String createJSONString ( HttpServletRequest request , String controller ) throws Exception { JSONObject obj = new JSONObject ( ) ; try { Field [ ] allFields = Class . forName ( "com.microsoft.windowsazure.activedirectory.sdk.graph.models." + controller ) . getDeclaredFields ( ) ; String [ ] allFieldStr = new String [ allFields . length ] ; for ( int i = 0 ; i < allFields . length ; i ++ ) { allFieldStr [ i ] = allFields [ i ] . getName ( ) ; } List < String > allFieldStringList = Arrays . asList ( allFieldStr ) ; Enumeration < String > fields = request . getParameterNames ( ) ; while ( fields . hasMoreElements ( ) ) { String fieldName = fields . nextElement ( ) ; String param = request . getParameter ( fieldName ) ; if ( allFieldStringList . contains ( fieldName ) ) { if ( param == null || param . length ( ) == 0 ) { if ( ! fieldName . equalsIgnoreCase ( "password" ) ) { obj . put ( fieldName , JSONObject . NULL ) ; } } else { if ( fieldName . equalsIgnoreCase ( "password" ) ) { obj . put ( "passwordProfile" , new JSONObject ( "{\"password\": \"" + param + "\"}" ) ) ; } else { obj . put ( fieldName , param ) ; } } } } } catch ( JSONException e ) { e . printStackTrace ( ) ; } catch ( SecurityException e ) { e . printStackTrace ( ) ; } catch ( ClassNotFoundException e ) { e . printStackTrace ( ) ; } return obj . toString ( ) ; }
This method would create a string consisting of a JSON document with all the necessary elements set from the HttpServletRequest request .
391
26
28,705
public static < T > void convertJSONObjectToDirectoryObject ( JSONObject jsonObject , T destObject ) throws Exception { // Get the list of all the field names. Field [ ] fieldList = destObject . getClass ( ) . getDeclaredFields ( ) ; // For all the declared field. for ( int i = 0 ; i < fieldList . length ; i ++ ) { // If the field is of type String, that is // if it is a simple attribute. if ( fieldList [ i ] . getType ( ) . equals ( String . class ) ) { // Invoke the corresponding set method of the destObject using // the argument taken from the jsonObject. destObject . getClass ( ) . getMethod ( String . format ( "set%s" , WordUtils . capitalize ( fieldList [ i ] . getName ( ) ) ) , new Class [ ] { String . class } ) . invoke ( destObject , new Object [ ] { jsonObject . optString ( fieldList [ i ] . getName ( ) ) } ) ; } } }
This is a generic method that copies the simple attribute values from an argument jsonObject to an argument generic object .
227
22
28,706
public String getPublicCertificateHash ( ) throws CertificateEncodingException , NoSuchAlgorithmException { return Base64 . encodeBase64String ( AsymmetricKeyCredential . getHash ( this . publicCertificate . getEncoded ( ) ) ) ; }
Base64 encoded hash of the the public certificate .
56
10
28,707
public boolean isDeviceCodeError ( ) { ErrorObject errorObject = getErrorObject ( ) ; if ( errorObject == null ) { return false ; } String code = errorObject . getCode ( ) ; if ( code == null ) { return false ; } switch ( code ) { case "authorization_pending" : case "slow_down" : case "access_denied" : case "code_expired" : return true ; default : return false ; } }
Checks if is a device code error .
101
9
28,708
private StateData validateState ( HttpSession session , String state ) throws Exception { if ( StringUtils . isNotEmpty ( state ) ) { StateData stateDataInSession = removeStateFromSession ( session , state ) ; if ( stateDataInSession != null ) { return stateDataInSession ; } } throw new Exception ( FAILED_TO_VALIDATE_MESSAGE + "could not validate state" ) ; }
make sure that state is stored in the session delete it from session - should be used only once
94
19
28,709
public String getLdapEncoded ( ) { if ( components . size ( ) == 0 ) { throw new IndexOutOfBoundsException ( "No components in Rdn." ) ; } StringBuffer sb = new StringBuffer ( DEFAULT_BUFFER_SIZE ) ; for ( Iterator iter = components . values ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { LdapRdnComponent component = ( LdapRdnComponent ) iter . next ( ) ; sb . append ( component . encodeLdap ( ) ) ; if ( iter . hasNext ( ) ) { sb . append ( "+" ) ; } } return sb . toString ( ) ; }
Get a properly rfc2253 - encoded String representation of this LdapRdn .
152
19
28,710
public String encodeUrl ( ) { StringBuffer sb = new StringBuffer ( DEFAULT_BUFFER_SIZE ) ; for ( Iterator iter = components . values ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { LdapRdnComponent component = ( LdapRdnComponent ) iter . next ( ) ; sb . append ( component . encodeUrl ( ) ) ; if ( iter . hasNext ( ) ) { sb . append ( "+" ) ; } } return sb . toString ( ) ; }
Get a String representation of this LdapRdn for use in urls .
116
17
28,711
public int compareTo ( Object obj ) { LdapRdn that = ( LdapRdn ) obj ; if ( this . components . size ( ) != that . components . size ( ) ) { return this . components . size ( ) - that . components . size ( ) ; } Set < Map . Entry < String , LdapRdnComponent > > theseEntries = this . components . entrySet ( ) ; for ( Map . Entry < String , LdapRdnComponent > oneEntry : theseEntries ) { LdapRdnComponent thatEntry = that . components . get ( oneEntry . getKey ( ) ) ; if ( thatEntry == null ) { return - 1 ; } int compared = oneEntry . getValue ( ) . compareTo ( thatEntry ) ; if ( compared != 0 ) { return compared ; } } return 0 ; }
Compare this LdapRdn to another object .
185
11
28,712
public LdapRdn immutableLdapRdn ( ) { Map < String , LdapRdnComponent > mapWithImmutableRdns = new LinkedHashMap < String , LdapRdnComponent > ( components . size ( ) ) ; for ( Iterator iterator = components . values ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { LdapRdnComponent rdnComponent = ( LdapRdnComponent ) iterator . next ( ) ; mapWithImmutableRdns . put ( rdnComponent . getKey ( ) , rdnComponent . immutableLdapRdnComponent ( ) ) ; } Map < String , LdapRdnComponent > unmodifiableMapOfImmutableRdns = Collections . unmodifiableMap ( mapWithImmutableRdns ) ; LdapRdn immutableRdn = new LdapRdn ( ) ; immutableRdn . components = unmodifiableMapOfImmutableRdns ; return immutableRdn ; }
Create an immutable copy of this instance . It will not be possible to add or remove components or modify the keys and values of these components .
220
28
28,713
void doCloseConnection ( DirContext context , ContextSource contextSource ) throws javax . naming . NamingException { DirContextHolder transactionContextHolder = ( DirContextHolder ) TransactionSynchronizationManager . getResource ( contextSource ) ; if ( transactionContextHolder == null || transactionContextHolder . getCtx ( ) != context ) { log . debug ( "Closing context" ) ; // This is not the transactional context or the transaction is // no longer active - we should close it. context . close ( ) ; } else { log . debug ( "Leaving transactional context open" ) ; } }
Close the supplied context but only if it is not associated with the current transaction .
134
16
28,714
protected String encodeLdap ( ) { StringBuffer buff = new StringBuffer ( key . length ( ) + value . length ( ) * 2 ) ; buff . append ( key ) ; buff . append ( ' ' ) ; buff . append ( LdapEncoder . nameEncode ( value ) ) ; return buff . toString ( ) ; }
Encode key and value to ldap .
74
10
28,715
public String encodeUrl ( ) { // Use the URI class to properly URL encode the value. try { URI valueUri = new URI ( null , null , value , null ) ; return key + "=" + valueUri . toString ( ) ; } catch ( URISyntaxException e ) { // This should really never happen... return key + "=" + "value" ; } }
Get a String representation of this instance for use in URLs .
83
12
28,716
public int compareTo ( Object obj ) { LdapRdnComponent that = ( LdapRdnComponent ) obj ; // It's safe to compare directly against key and value, // because they are validated not to be null on instance creation. int keyCompare = this . key . toLowerCase ( ) . compareTo ( that . key . toLowerCase ( ) ) ; if ( keyCompare == 0 ) { return this . value . toLowerCase ( ) . compareTo ( that . value . toLowerCase ( ) ) ; } else { return keyCompare ; } }
Compare this instance to the supplied object .
122
8
28,717
public static void collectAttributeValues ( Attributes attributes , String name , Collection < Object > collection ) { collectAttributeValues ( attributes , name , collection , Object . class ) ; }
Collect all the values of a the specified attribute from the supplied Attributes .
36
14
28,718
public static < T > void collectAttributeValues ( Attributes attributes , String name , Collection < T > collection , Class < T > clazz ) { Assert . notNull ( attributes , "Attributes must not be null" ) ; Assert . hasText ( name , "Name must not be empty" ) ; Assert . notNull ( collection , "Collection must not be null" ) ; Attribute attribute = attributes . get ( name ) ; if ( attribute == null ) { throw new NoSuchAttributeException ( "No attribute with name '" + name + "'" ) ; } iterateAttributeValues ( attribute , new CollectingAttributeValueCallbackHandler < T > ( collection , clazz ) ) ; }
Collect all the values of a the specified attribute from the supplied Attributes as the specified class .
147
18
28,719
public static void iterateAttributeValues ( Attribute attribute , AttributeValueCallbackHandler callbackHandler ) { Assert . notNull ( attribute , "Attribute must not be null" ) ; Assert . notNull ( callbackHandler , "callbackHandler must not be null" ) ; if ( attribute instanceof Iterable ) { int i = 0 ; for ( Object obj : ( Iterable ) attribute ) { handleAttributeValue ( attribute . getID ( ) , obj , i , callbackHandler ) ; i ++ ; } } else { for ( int i = 0 ; i < attribute . size ( ) ; i ++ ) { try { handleAttributeValue ( attribute . getID ( ) , attribute . get ( i ) , i , callbackHandler ) ; } catch ( javax . naming . NamingException e ) { throw convertLdapException ( e ) ; } } } }
Iterate through all the values of the specified Attribute calling back to the specified callbackHandler .
183
19
28,720
public static LdapName newLdapName ( String distinguishedName ) { Assert . notNull ( distinguishedName , "distinguishedName must not be null" ) ; try { return new LdapName ( distinguishedName ) ; } catch ( InvalidNameException e ) { throw convertLdapException ( e ) ; } }
Construct a new LdapName instance from the supplied distinguished name string .
71
15
28,721
public static Rdn getRdn ( Name name , String key ) { Assert . notNull ( name , "name must not be null" ) ; Assert . hasText ( key , "key must not be blank" ) ; LdapName ldapName = returnOrConstructLdapNameFromName ( name ) ; List < Rdn > rdns = ldapName . getRdns ( ) ; for ( Rdn rdn : rdns ) { NamingEnumeration < String > ids = rdn . toAttributes ( ) . getIDs ( ) ; while ( ids . hasMoreElements ( ) ) { String id = ids . nextElement ( ) ; if ( key . equalsIgnoreCase ( id ) ) { return rdn ; } } } throw new NoSuchElementException ( "No Rdn with the requested key: '" + key + "'" ) ; }
Find the Rdn with the requested key in the supplied Name .
198
13
28,722
public static Object getValue ( Name name , String key ) { NamingEnumeration < ? extends Attribute > allAttributes = getRdn ( name , key ) . toAttributes ( ) . getAll ( ) ; while ( allAttributes . hasMoreElements ( ) ) { Attribute oneAttribute = allAttributes . nextElement ( ) ; if ( key . equalsIgnoreCase ( oneAttribute . getID ( ) ) ) { try { return oneAttribute . get ( ) ; } catch ( javax . naming . NamingException e ) { throw convertLdapException ( e ) ; } } } // This really shouldn't happen throw new NoSuchElementException ( "No Rdn with the requested key: '" + key + "'" ) ; }
Get the value of the Rdn with the requested key in the supplied Name .
161
16
28,723
public static Object getValue ( Name name , int index ) { Assert . notNull ( name , "name must not be null" ) ; LdapName ldapName = returnOrConstructLdapNameFromName ( name ) ; Rdn rdn = ldapName . getRdn ( index ) ; if ( rdn . size ( ) > 1 ) { LOGGER . warn ( "Rdn at position " + index + " of dn '" + name + "' is multi-value - returned value is not to be trusted. " + "Consider using name-based getValue method instead" ) ; } return rdn . getValue ( ) ; }
Get the value of the Rdn at the requested index in the supplied Name .
144
16
28,724
public static String getStringValue ( Name name , String key ) { return ( String ) getValue ( name , key ) ; }
Get the value of the Rdn with the requested key in the supplied Name as a String .
27
19
28,725
static byte [ ] numberToBytes ( String number , int length , boolean bigEndian ) { BigInteger bi = new BigInteger ( number ) ; byte [ ] bytes = bi . toByteArray ( ) ; int remaining = length - bytes . length ; if ( remaining < 0 ) { bytes = Arrays . copyOfRange ( bytes , - remaining , bytes . length ) ; } else { byte [ ] fill = new byte [ remaining ] ; bytes = addAll ( fill , bytes ) ; } if ( ! bigEndian ) { reverse ( bytes ) ; } return bytes ; }
Converts the given number to a binary representation of the specified length and endian - ness .
122
20
28,726
static String toHexString ( final byte b ) { String hexString = Integer . toHexString ( b & 0xFF ) ; if ( hexString . length ( ) % 2 != 0 ) { // Pad with 0 hexString = "0" + hexString ; } return hexString ; }
Converts a byte into its hexadecimal representation padding with a leading zero to get an even number of characters .
64
24
28,727
static String toHexString ( final byte [ ] b ) { StringBuffer sb = new StringBuffer ( "{" ) ; for ( int i = 0 ; i < b . length ; i ++ ) { sb . append ( toHexString ( b [ i ] ) ) ; if ( i < b . length - 1 ) { sb . append ( "," ) ; } } sb . append ( "}" ) ; return sb . toString ( ) ; }
Converts a byte array into its hexadecimal representation padding each with a leading zero to get an even number of characters .
102
26
28,728
public Context getInnermostDelegateContext ( ) { final Context delegateContext = this . getDelegateContext ( ) ; if ( delegateContext instanceof DelegatingContext ) { return ( ( DelegatingContext ) delegateContext ) . getInnermostDelegateContext ( ) ; } return delegateContext ; }
Recursivley inspect delegates until a non - delegating context is found .
66
16
28,729
public boolean isSatisfiedBy ( LdapAttributes record ) throws NamingException { if ( record != null ) { //DN is required. LdapName dn = record . getName ( ) ; if ( dn != null ) { //objectClass definition is required. if ( record . get ( "objectClass" ) != null ) { //Naming attribute is required. Rdn rdn = dn . getRdn ( dn . size ( ) - 1 ) ; if ( record . get ( rdn . getType ( ) ) != null ) { Object object = record . get ( rdn . getType ( ) ) . get ( ) ; if ( object instanceof String ) { String value = ( String ) object ; if ( ( ( String ) rdn . getValue ( ) ) . equalsIgnoreCase ( value ) ) { return true ; } } else if ( object instanceof byte [ ] ) { String rdnValue = LdapEncoder . printBase64Binary ( ( ( String ) rdn . getValue ( ) ) . getBytes ( ) ) ; String attributeValue = LdapEncoder . printBase64Binary ( ( byte [ ] ) object ) ; if ( rdnValue . equals ( attributeValue ) ) return true ; } } } } }
Determines if the policy is satisfied by the supplied LdapAttributes object .
278
17
28,730
public void destroy ( ) { try { ctx . close ( ) ; } catch ( javax . naming . NamingException e ) { LOG . warn ( "Error when closing" , e ) ; } }
Destroy method that allows the target DirContext to be cleaned up when the SingleContextSource is not going to be used any more .
45
26
28,731
protected final void parse ( String path ) { DnParser parser = DefaultDnParserFactory . createDnParser ( unmangleCompositeName ( path ) ) ; DistinguishedName dn ; try { dn = parser . dn ( ) ; } catch ( ParseException e ) { throw new BadLdapGrammarException ( "Failed to parse DN" , e ) ; } catch ( TokenMgrError e ) { throw new BadLdapGrammarException ( "Failed to parse DN" , e ) ; } this . names = dn . names ; }
Parse the supplied String and make this instance represent the corresponding distinguished name .
128
15
28,732
public String toUrl ( ) { StringBuffer buffer = new StringBuffer ( DEFAULT_BUFFER_SIZE ) ; for ( int i = names . size ( ) - 1 ; i >= 0 ; i -- ) { LdapRdn n = ( LdapRdn ) names . get ( i ) ; buffer . append ( n . encodeUrl ( ) ) ; if ( i > 0 ) { buffer . append ( "," ) ; } } return buffer . toString ( ) ; }
Builds a complete LDAP path ldap and url encoded . Separates only with .
104
20
28,733
public int compareTo ( Object obj ) { DistinguishedName that = ( DistinguishedName ) obj ; ListComparator comparator = new ListComparator ( ) ; return comparator . compare ( this . names , that . names ) ; }
Compare this instance to another object . Note that the comparison is done in order of significance so the most significant Rdn is compared first then the second and so on .
50
33
28,734
public DistinguishedName immutableDistinguishedName ( ) { List listWithImmutableRdns = new ArrayList ( names . size ( ) ) ; for ( Iterator iterator = names . iterator ( ) ; iterator . hasNext ( ) ; ) { LdapRdn rdn = ( LdapRdn ) iterator . next ( ) ; listWithImmutableRdns . add ( rdn . immutableLdapRdn ( ) ) ; } return new DistinguishedName ( Collections . unmodifiableList ( listWithImmutableRdns ) ) ; }
Return an immutable copy of this instance . It will not be possible to add or remove any Rdns to or from the returned instance and the respective Rdns will also be immutable in turn .
121
38
28,735
private boolean processAttributeAnnotation ( Field field ) { // Default to no syntax specified syntax = "" ; // Default to a String based attribute isBinary = false ; // Default name of attribute to the name of the field name = new CaseIgnoreString ( field . getName ( ) ) ; // We have not yet found the @Attribute annotation boolean foundAnnotation = false ; // Grab the @Attribute annotation Attribute attribute = field . getAnnotation ( Attribute . class ) ; List < String > attrList = new ArrayList < String > ( ) ; // Did we find the annotation? if ( attribute != null ) { // Pull attribute name, syntax and whether attribute is binary // from the annotation foundAnnotation = true ; String localAttributeName = attribute . name ( ) ; // Would be more efficient to use !isEmpty - but that then makes us Java 6 dependent if ( localAttributeName != null && localAttributeName . length ( ) > 0 ) { name = new CaseIgnoreString ( localAttributeName ) ; attrList . add ( localAttributeName ) ; } syntax = attribute . syntax ( ) ; isBinary = attribute . type ( ) == Attribute . Type . BINARY ; isReadOnly = attribute . readonly ( ) ; } attributes = attrList . toArray ( new String [ attrList . size ( ) ] ) ; isObjectClass = name . equals ( OBJECT_CLASS_ATTRIBUTE_CI ) ; return foundAnnotation ; }
syntax isBinary isObjectClass and name .
314
11
28,736
private static Map < String , String > readSyntaxMap ( File syntaxMapFile ) throws IOException { Map < String , String > result = new HashMap < String , String > ( ) ; BufferedReader reader = null ; try { reader = new BufferedReader ( new FileReader ( syntaxMapFile ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { String trimmed = line . trim ( ) ; if ( trimmed . length ( ) > 0 ) { if ( trimmed . charAt ( 0 ) != ' ' ) { String [ ] parts = trimmed . split ( "," ) ; if ( parts . length != 2 ) { throw new IOException ( String . format ( "Failed to parse line \"%1$s\"" , trimmed ) ) ; } String partOne = parts [ 0 ] . trim ( ) ; String partTwo = parts [ 1 ] . trim ( ) ; if ( partOne . length ( ) == 0 || partTwo . length ( ) == 0 ) { throw new IOException ( String . format ( "Failed to parse line \"%1$s\"" , trimmed ) ) ; } result . put ( partOne , partTwo ) ; } } } } finally { if ( reader != null ) { reader . close ( ) ; } } return result ; }
Read mappings of LDAP syntaxes to Java classes .
281
12
28,737
private static ObjectSchema readSchema ( String url , String user , String pass , SyntaxToJavaClass syntaxToJavaClass , Set < String > binarySet , Set < String > objectClasses ) throws NamingException , ClassNotFoundException { // Set up environment Hashtable < String , String > env = new Hashtable < String , String > ( ) ; env . put ( Context . PROVIDER_URL , url ) ; env . put ( Context . INITIAL_CONTEXT_FACTORY , "com.sun.jndi.ldap.LdapCtxFactory" ) ; if ( user != null ) { env . put ( Context . SECURITY_PRINCIPAL , user ) ; } if ( pass != null ) { env . put ( Context . SECURITY_CREDENTIALS , pass ) ; } DirContext context = new InitialDirContext ( env ) ; DirContext schemaContext = context . getSchema ( "" ) ; SchemaReader reader = new SchemaReader ( schemaContext , syntaxToJavaClass , binarySet ) ; ObjectSchema schema = reader . getObjectSchema ( objectClasses ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( String . format ( "Schema - %1$s" , schema . toString ( ) ) ) ; } return schema ; }
Bind to the directory read and process the schema
290
9
28,738
private static void createCode ( String packageName , String className , ObjectSchema schema , Set < SyntaxToJavaClass . ClassInfo > imports , File outputFile ) throws IOException , TemplateException { Configuration freeMarkerConfiguration = new Configuration ( ) ; freeMarkerConfiguration . setClassForTemplateLoading ( DEFAULT_LOADER_CLASS , "" ) ; freeMarkerConfiguration . setObjectWrapper ( new DefaultObjectWrapper ( ) ) ; // Build the model for FreeMarker Map < String , Object > model = new HashMap < String , Object > ( ) ; model . put ( "package" , packageName ) ; model . put ( "class" , className ) ; model . put ( "schema" , schema ) ; model . put ( "imports" , imports ) ; // Have FreeMarker process the model with the template Template template = freeMarkerConfiguration . getTemplate ( TEMPLATE_FILE ) ; if ( LOG . isDebugEnabled ( ) ) { Writer out = new OutputStreamWriter ( System . out ) ; template . process ( model , out ) ; out . flush ( ) ; } LOG . debug ( String . format ( "Writing java to: %1$s" , outputFile . getAbsolutePath ( ) ) ) ; FileOutputStream outputStream = new FileOutputStream ( outputFile ) ; Writer out = new OutputStreamWriter ( outputStream ) ; template . process ( model , out ) ; out . flush ( ) ; out . close ( ) ; }
Create the Java
320
3
28,739
private static File makeOutputFile ( String outputDir , String packageName , String className ) throws IOException { // Convert the package name to a path Pattern pattern = Pattern . compile ( "\\." ) ; Matcher matcher = pattern . matcher ( packageName ) ; String sepToUse = File . separator ; if ( sepToUse . equals ( "\\" ) ) { sepToUse = "\\\\" ; } // Try to create the necessary directories String directoryPath = outputDir + File . separator + matcher . replaceAll ( sepToUse ) ; File directory = new File ( directoryPath ) ; File outputFile = new File ( directory , className + ".java" ) ; LOG . debug ( String . format ( "Attempting to create output file at %1$s" , outputFile . getAbsolutePath ( ) ) ) ; try { directory . mkdirs ( ) ; outputFile . createNewFile ( ) ; } catch ( SecurityException se ) { throw new IOException ( String . format ( "Can't write to output file %1$s" , outputFile . getAbsoluteFile ( ) ) , se ) ; } catch ( IOException ioe ) { throw new IOException ( String . format ( "Can't write to output file %1$s" , outputFile . getAbsoluteFile ( ) ) , ioe ) ; } return outputFile ; }
Create the output file for the generated code along with all intervening directories
296
13
28,740
public ObjectSchema getObjectSchema ( Set < String > objectClasses ) throws NamingException , ClassNotFoundException { ObjectSchema result = new ObjectSchema ( ) ; createObjectClass ( objectClasses , schemaContext , result ) ; return result ; }
Get the object schema for the given object classes
57
9
28,741
private void createObjectClass ( Set < String > objectClasses , DirContext schemaContext , ObjectSchema schema ) throws NamingException , ClassNotFoundException { // Super classes Set < String > supList = new HashSet < String > ( ) ; // For each of the given object classes for ( String objectClass : objectClasses ) { // Add to set of included object classes schema . addObjectClass ( objectClass ) ; // Grab the LDAP schema of the object class Attributes attributes = schemaContext . getAttributes ( "ClassDefinition/" + objectClass ) ; NamingEnumeration < ? extends Attribute > valuesEnumeration = attributes . getAll ( ) ; // Loop through each of the attributes while ( valuesEnumeration . hasMoreElements ( ) ) { Attribute currentAttribute = valuesEnumeration . nextElement ( ) ; // Get the attribute name and lower case it (as this is all case indep) String currentId = currentAttribute . getID ( ) . toUpperCase ( ) ; // Is this a MUST, MAY or SUP attribute SchemaAttributeType type = getSchemaAttributeType ( currentId ) ; // Loop through all the values NamingEnumeration < ? > currentValues = currentAttribute . getAll ( ) ; while ( currentValues . hasMoreElements ( ) ) { String currentValue = ( String ) currentValues . nextElement ( ) ; switch ( type ) { case SUP : // Its a super class String lowerCased = currentValue . toLowerCase ( ) ; if ( ! schema . getObjectClass ( ) . contains ( lowerCased ) ) { supList . add ( lowerCased ) ; } break ; case MUST : // Add must attribute schema . addMust ( createAttributeSchema ( currentValue , schemaContext ) ) ; break ; case MAY : // Add may attribute schema . addMay ( createAttributeSchema ( currentValue , schemaContext ) ) ; break ; default : // Nothing to do } } } // Recurse for super classes createObjectClass ( supList , schemaContext , schema ) ; } }
Recursively extract schema from the directory and process it
437
11
28,742
private void closeContext ( DirContext ctx ) { if ( ctx != null ) { try { ctx . close ( ) ; } catch ( Exception e ) { LOG . debug ( "Exception closing context" , e ) ; } } }
Close the context and swallow any exceptions .
51
8
28,743
protected DirContext createContext ( Hashtable < String , Object > environment ) { DirContext ctx = null ; try { ctx = getDirContextInstance ( environment ) ; if ( LOG . isInfoEnabled ( ) ) { Hashtable < ? , ? > ctxEnv = ctx . getEnvironment ( ) ; String ldapUrl = ( String ) ctxEnv . get ( Context . PROVIDER_URL ) ; LOG . debug ( "Got Ldap context on server '" + ldapUrl + "'" ) ; } return ctx ; } catch ( NamingException e ) { closeContext ( ctx ) ; throw LdapUtils . convertLdapException ( e ) ; } }
Create a DirContext using the supplied environment .
154
9
28,744
public void afterPropertiesSet ( ) { if ( ObjectUtils . isEmpty ( urls ) ) { throw new IllegalArgumentException ( "At least one server url must be set" ) ; } if ( authenticationSource == null ) { LOG . debug ( "AuthenticationSource not set - " + "using default implementation" ) ; if ( ! StringUtils . hasText ( userDn ) ) { LOG . info ( "Property 'userDn' not set - " + "anonymous context will be used for read-write operations" ) ; anonymousReadOnly = true ; } else if ( ! StringUtils . hasText ( password ) ) { LOG . info ( "Property 'password' not set - " + "blank password will be used" ) ; } authenticationSource = new SimpleAuthenticationSource ( ) ; } if ( cacheEnvironmentProperties ) { anonymousEnv = setupAnonymousEnv ( ) ; } }
Checks that all necessary data is set and that there is no compatibility issues after which the instance is initialized . Note that you need to call this method explicitly after setting all desired properties if using the class outside of a Spring Context .
197
46
28,745
public void setBaseEnvironmentProperties ( Map < String , Object > baseEnvironmentProperties ) { this . baseEnv = new Hashtable < String , Object > ( baseEnvironmentProperties ) ; }
If any custom environment properties are needed these can be set using this method .
42
15
28,746
public LdapNameBuilder add ( Name name ) { Assert . notNull ( name , "name must not be null" ) ; try { ldapName . addAll ( ldapName . size ( ) , name ) ; return this ; } catch ( InvalidNameException e ) { throw new org . springframework . ldap . InvalidNameException ( e ) ; } }
Append the specified name to the currently built LdapName .
83
14
28,747
public LdapNameBuilder add ( String name ) { Assert . notNull ( name , "name must not be null" ) ; return add ( LdapUtils . newLdapName ( name ) ) ; }
Append the LdapName represented by the specified string to the currently built LdapName .
49
21
28,748
protected void deleteRecursively ( DirContext ctx , Name name ) { NamingEnumeration enumeration = null ; try { enumeration = ctx . listBindings ( name ) ; while ( enumeration . hasMore ( ) ) { Binding binding = ( Binding ) enumeration . next ( ) ; LdapName childName = LdapUtils . newLdapName ( binding . getName ( ) ) ; childName . addAll ( 0 , name ) ; deleteRecursively ( ctx , childName ) ; } ctx . unbind ( name ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Entry " + name + " deleted" ) ; } } catch ( javax . naming . NamingException e ) { throw LdapUtils . convertLdapException ( e ) ; } finally { try { enumeration . close ( ) ; } catch ( Exception e ) { // Never mind this } } }
Delete all subcontexts including the current one recursively .
209
13
28,749
private void assureReturnObjFlagSet ( SearchControls controls ) { Assert . notNull ( controls , "controls must not be null" ) ; if ( ! controls . getReturningObjFlag ( ) ) { LOG . debug ( "The returnObjFlag of supplied SearchControls is not set" + " but a ContextMapper is used - setting flag to true" ) ; controls . setReturningObjFlag ( true ) ; } }
Make sure the returnObjFlag is set in the supplied SearchControls . Set it and log if it s not set .
94
25
28,750
public DirContext getInnermostDelegateDirContext ( ) { final DirContext delegateDirContext = this . getDelegateDirContext ( ) ; if ( delegateDirContext instanceof DelegatingDirContext ) { return ( ( DelegatingDirContext ) delegateDirContext ) . getInnermostDelegateDirContext ( ) ; } return delegateDirContext ; }
Recursivley inspect delegates until a non - delegating dir context is found .
77
17
28,751
public static Name getFirstArgumentAsName ( Object [ ] args ) { Assert . notEmpty ( args ) ; Object firstArg = args [ 0 ] ; return getArgumentAsName ( firstArg ) ; }
Get the first parameter in the argument list as a Name .
46
12
28,752
public static Name getArgumentAsName ( Object arg ) { if ( arg instanceof String ) { return LdapUtils . newLdapName ( ( String ) arg ) ; } else if ( arg instanceof Name ) { return ( Name ) arg ; } else { throw new IllegalArgumentException ( "First argument needs to be a Name or a String representation thereof" ) ; } }
Get the argument as a Name .
84
7
28,753
public static Attributes lookupAttributes ( LdapOperations ldapOperations , Name dn , String [ ] attributes ) { return loopForAllAttributeValues ( ldapOperations , dn , attributes ) . getCollectedAttributes ( ) ; }
Lookup all values for the specified attributes looping through the results incrementally if necessary .
54
18
28,754
public Object getObject ( ) throws Exception { if ( converterConfigList == null ) { throw new FactoryBeanNotInitializedException ( "converterConfigList has not been set" ) ; } ConverterManagerImpl result = new ConverterManagerImpl ( ) ; for ( ConverterConfig converterConfig : converterConfigList ) { if ( converterConfig . fromClasses == null || converterConfig . toClasses == null || converterConfig . converter == null ) { throw new FactoryBeanNotInitializedException ( String . format ( "All of fromClasses, toClasses and converter must be specified in bean %1$s" , converterConfig . toString ( ) ) ) ; } for ( Class < ? > fromClass : converterConfig . fromClasses ) { for ( Class < ? > toClass : converterConfig . toClasses ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( String . format ( "Adding converter from %1$s to %2$s" , fromClass , toClass ) ) ; } result . addConverter ( fromClass , converterConfig . syntax , toClass , converterConfig . converter ) ; } } } return result ; }
Creates a ConverterManagerImpl populating it with Converter instances from the converterConfigList property .
251
21
28,755
public void setAttribute ( Attribute attribute ) { if ( ! updateMode ) { originalAttrs . put ( attribute ) ; } else { updatedAttrs . put ( attribute ) ; } }
Set the supplied attribute .
40
5
28,756
public LdapContext getInnermostDelegateLdapContext ( ) { final LdapContext delegateLdapContext = this . getDelegateLdapContext ( ) ; if ( delegateLdapContext instanceof DelegatingLdapContext ) { return ( ( DelegatingLdapContext ) delegateLdapContext ) . getInnermostDelegateLdapContext ( ) ; } return delegateLdapContext ; }
Recursivley inspect delegates until a non - delegating ldap context is found .
99
19
28,757
protected DirContext getContext ( DirContextType dirContextType ) { final DirContext dirContext ; try { dirContext = ( DirContext ) this . keyedObjectPool . borrowObject ( dirContextType ) ; } catch ( Exception e ) { throw new DataAccessResourceFailureException ( "Failed to borrow DirContext from pool." , e ) ; } if ( dirContext instanceof LdapContext ) { return new DelegatingLdapContext ( this . keyedObjectPool , ( LdapContext ) dirContext , dirContextType ) ; } return new DelegatingDirContext ( this . keyedObjectPool , dirContext , dirContextType ) ; }
Gets a DirContext of the specified type from the keyed object pool .
142
16
28,758
public static String filterEncode ( String value ) { if ( value == null ) return null ; // make buffer roomy StringBuilder encodedValue = new StringBuilder ( value . length ( ) * 2 ) ; int length = value . length ( ) ; for ( int i = 0 ; i < length ; i ++ ) { char c = value . charAt ( i ) ; if ( c < FILTER_ESCAPE_TABLE . length ) { encodedValue . append ( FILTER_ESCAPE_TABLE [ c ] ) ; } else { // default: add the char encodedValue . append ( c ) ; } } return encodedValue . toString ( ) ; }
Escape a value for use in a filter .
141
10
28,759
public static String nameEncode ( String value ) { if ( value == null ) return null ; // make buffer roomy StringBuilder encodedValue = new StringBuilder ( value . length ( ) * 2 ) ; int length = value . length ( ) ; int last = length - 1 ; for ( int i = 0 ; i < length ; i ++ ) { char c = value . charAt ( i ) ; // space first or last if ( c == ' ' && ( i == 0 || i == last ) ) { encodedValue . append ( "\\ " ) ; continue ; } if ( c < NAME_ESCAPE_TABLE . length ) { // check in table for escapes String esc = NAME_ESCAPE_TABLE [ c ] ; if ( esc != null ) { encodedValue . append ( esc ) ; continue ; } } // default: add the char encodedValue . append ( c ) ; } return encodedValue . toString ( ) ; }
LDAP Encodes a value for use with a DN . Escapes for LDAP not JNDI!
200
22
28,760
static public String nameDecode ( String value ) throws BadLdapGrammarException { if ( value == null ) return null ; // make buffer same size StringBuilder decoded = new StringBuilder ( value . length ( ) ) ; int i = 0 ; while ( i < value . length ( ) ) { char currentChar = value . charAt ( i ) ; if ( currentChar == ' ' ) { if ( value . length ( ) <= i + 1 ) { // Ending with a single backslash is not allowed throw new BadLdapGrammarException ( "Unexpected end of value " + "unterminated '\\'" ) ; } else { char nextChar = value . charAt ( i + 1 ) ; if ( nextChar == ' ' || nextChar == ' ' || nextChar == ' ' || nextChar == ' ' || nextChar == ' ' || nextChar == ' ' || nextChar == ' ' || nextChar == ' ' || nextChar == ' ' || nextChar == ' ' ) { // Normal backslash escape decoded . append ( nextChar ) ; i += 2 ; } else { if ( value . length ( ) <= i + 2 ) { throw new BadLdapGrammarException ( "Unexpected end of value " + "expected special or hex, found '" + nextChar + "'" ) ; } else { // This should be a hex value String hexString = "" + nextChar + value . charAt ( i + 2 ) ; decoded . append ( ( char ) Integer . parseInt ( hexString , HEX ) ) ; i += 3 ; } } } } else { // This character wasn't escaped - just append it decoded . append ( currentChar ) ; i ++ ; } } return decoded . toString ( ) ; }
Decodes a value . Converts escaped chars to ordinary chars .
384
13
28,761
public static String printBase64Binary ( byte [ ] val ) { Assert . notNull ( val , "val must not be null!" ) ; String encoded = DatatypeConverter . printBase64Binary ( val ) ; int length = encoded . length ( ) ; StringBuilder sb = new StringBuilder ( length + length / RFC2849_MAX_BASE64_CHARS_PER_LINE ) ; for ( int i = 0 , len = length ; i < len ; i ++ ) { sb . append ( encoded . charAt ( i ) ) ; if ( ( i + 1 ) % RFC2849_MAX_BASE64_CHARS_PER_LINE == 0 ) { sb . append ( ' ' ) ; sb . append ( ' ' ) ; } } return sb . toString ( ) ; }
Converts an array of bytes into a Base64 encoded string according to the rules for converting LDAP Attributes in RFC2849 .
182
26
28,762
public static byte [ ] parseBase64Binary ( String val ) { Assert . notNull ( val , "val must not be null!" ) ; int length = val . length ( ) ; StringBuilder sb = new StringBuilder ( length ) ; for ( int i = 0 , len = length ; i < len ; i ++ ) { char c = val . charAt ( i ) ; if ( c == ' ' ) { if ( i + 1 < len && val . charAt ( i + 1 ) == ' ' ) { i ++ ; } continue ; } sb . append ( c ) ; } return DatatypeConverter . parseBase64Binary ( sb . toString ( ) ) ; }
Converts the Base64 encoded string argument into an array of bytes .
153
14
28,763
protected Object invokeMethod ( String method , Class < ? > clazz , Object control ) { Method actualMethod = ReflectionUtils . findMethod ( clazz , method ) ; return ReflectionUtils . invokeMethod ( actualMethod , control ) ; }
Utility method for invoking a method on a Control .
53
11
28,764
public Set < User > findAllMembers ( Iterable < Name > absoluteIds ) { return Sets . newLinkedHashSet ( userRepo . findAll ( toRelativeIds ( absoluteIds ) ) ) ; }
This method expects absolute DNs of group members . In order to find the actual users the DNs need to have the base LDAP path removed .
49
30
28,765
private User updateUserStandard ( LdapName originalId , User existingUser ) { User savedUser = userRepo . save ( existingUser ) ; if ( ! originalId . equals ( savedUser . getId ( ) ) ) { // The user has moved - we need to update group references. LdapName oldMemberDn = toAbsoluteDn ( originalId ) ; LdapName newMemberDn = toAbsoluteDn ( savedUser . getId ( ) ) ; Collection < Group > groups = groupRepo . findByMember ( oldMemberDn ) ; updateGroupReferences ( groups , oldMemberDn , newMemberDn ) ; } return savedUser ; }
Update the user and - if its id changed - update all group references to the user .
149
18
28,766
protected ModificationItem getCompensatingModificationItem ( Attributes originalAttributes , ModificationItem modificationItem ) { Attribute modificationAttribute = modificationItem . getAttribute ( ) ; Attribute originalAttribute = originalAttributes . get ( modificationAttribute . getID ( ) ) ; if ( modificationItem . getModificationOp ( ) == DirContext . REMOVE_ATTRIBUTE ) { if ( modificationAttribute . size ( ) == 0 ) { // If the modification attribute size it means that the // Attribute should be removed entirely - we should store a // ModificationItem to restore all present values for rollback. return new ModificationItem ( DirContext . ADD_ATTRIBUTE , ( Attribute ) originalAttribute . clone ( ) ) ; } else { // The rollback modification will be to re-add the removed // attribute values. return new ModificationItem ( DirContext . ADD_ATTRIBUTE , ( Attribute ) modificationAttribute . clone ( ) ) ; } } else if ( modificationItem . getModificationOp ( ) == DirContext . REPLACE_ATTRIBUTE ) { if ( originalAttribute != null ) { return new ModificationItem ( DirContext . REPLACE_ATTRIBUTE , ( Attribute ) originalAttribute . clone ( ) ) ; } else { // The attribute doesn't previously exist - the rollback // operation will be to remove the attribute. return new ModificationItem ( DirContext . REMOVE_ATTRIBUTE , new BasicAttribute ( modificationAttribute . getID ( ) ) ) ; } } else { // An ADD_ATTRIBUTE operation if ( originalAttribute == null ) { // The attribute doesn't previously exist - the rollback // operation will be to remove the attribute. return new ModificationItem ( DirContext . REMOVE_ATTRIBUTE , new BasicAttribute ( modificationAttribute . getID ( ) ) ) ; } else { // The attribute does exist before - we should store the // previous value and it should be used for replacing in // rollback. return new ModificationItem ( DirContext . REPLACE_ATTRIBUTE , ( Attribute ) originalAttribute . clone ( ) ) ; } } }
Get a ModificationItem to use for rollback of the supplied modification .
456
15
28,767
public int compare ( Object o1 , Object o2 ) { List list1 = ( List ) o1 ; List list2 = ( List ) o2 ; for ( int i = 0 ; i < list1 . size ( ) ; i ++ ) { if ( list2 . size ( ) > i ) { Comparable component1 = ( Comparable ) list1 . get ( i ) ; Comparable component2 = ( Comparable ) list2 . get ( i ) ; int componentsCompared = component1 . compareTo ( component2 ) ; if ( componentsCompared != 0 ) { return componentsCompared ; } } else { // First instance has more components, so that instance is // greater. return 1 ; } } // All components so far are equal - if the other instance has // more components it is greater otherwise they are equal. if ( list2 . size ( ) > list1 . size ( ) ) { return - 1 ; } else { return 0 ; } }
Compare two lists of Comparable objects .
201
8
28,768
@ Override public String getSqlWithValues ( ) { final StringBuilder sb = new StringBuilder ( ) ; final String statementQuery = getStatementQuery ( ) ; // iterate over the characters in the query replacing the parameter placeholders // with the actual values int currentParameter = 0 ; for ( int pos = 0 ; pos < statementQuery . length ( ) ; pos ++ ) { char character = statementQuery . charAt ( pos ) ; if ( statementQuery . charAt ( pos ) == ' ' && currentParameter <= parameterValues . size ( ) ) { // replace with parameter value Value value = parameterValues . get ( currentParameter ) ; sb . append ( value != null ? value . toString ( ) : new Value ( ) . toString ( ) ) ; currentParameter ++ ; } else { sb . append ( character ) ; } } return sb . toString ( ) ; }
Generates the query for the prepared statement with all parameter placeholders replaced with the actual parameter values
189
19
28,769
protected static void doLogElapsed ( int connectionId , long timeElapsedNanos , Category category , String prepared , String sql , String url ) { doLog ( connectionId , timeElapsedNanos , category , prepared , sql , url ) ; }
this is an internal method called by logElapsed
54
10
28,770
protected static void doLog ( int connectionId , long elapsedNanos , Category category , String prepared , String sql , String url ) { // give it one more try if not initialized yet if ( logger == null ) { initialize ( ) ; if ( logger == null ) { return ; } } final String format = P6SpyOptions . getActiveInstance ( ) . getDateformat ( ) ; final String stringNow ; if ( format == null ) { stringNow = Long . toString ( System . currentTimeMillis ( ) ) ; } else { stringNow = new SimpleDateFormat ( format ) . format ( new java . util . Date ( ) ) . trim ( ) ; } logger . logSQL ( connectionId , stringNow , TimeUnit . NANOSECONDS . toMillis ( elapsedNanos ) , category , prepared , sql , url ) ; final boolean stackTrace = P6SpyOptions . getActiveInstance ( ) . getStackTrace ( ) ; if ( stackTrace ) { final String stackTraceClass = P6SpyOptions . getActiveInstance ( ) . getStackTraceClass ( ) ; Exception e = new Exception ( ) ; if ( stackTraceClass != null ) { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; e . printStackTrace ( pw ) ; String stack = sw . toString ( ) ; if ( stack . indexOf ( stackTraceClass ) == - 1 ) { e = null ; } } if ( e != null ) { logger . logException ( e ) ; } } }
Writes log information provided .
343
6
28,771
private static boolean meetsThresholdRequirement ( long timeTaken ) { final P6LogLoadableOptions opts = P6LogOptions . getActiveInstance ( ) ; long executionThreshold = null != opts ? opts . getExecutionThreshold ( ) : 0 ; return executionThreshold <= 0 || TimeUnit . NANOSECONDS . toMillis ( timeTaken ) > executionThreshold ; }
on whether on not it has taken greater than x amount of time .
90
14
28,772
protected synchronized void bindDataSource ( ) throws SQLException { // we'll check in the synchronized section again (to prevent unnecessary reinitialization) if ( null != realDataSource ) { return ; } final P6SpyLoadableOptions options = P6SpyOptions . getActiveInstance ( ) ; // can be set when object is bound to JNDI, or // can be loaded from spy.properties if ( rdsName == null ) { rdsName = options . getRealDataSource ( ) ; } if ( rdsName == null ) { throw new SQLException ( "P6DataSource: no value for Real Data Source Name, cannot perform jndi lookup" ) ; } // setup environment for the JNDI lookup Hashtable < String , String > env = null ; String factory ; if ( ( factory = options . getJNDIContextFactory ( ) ) != null ) { env = new Hashtable < String , String > ( ) ; env . put ( Context . INITIAL_CONTEXT_FACTORY , factory ) ; String url = options . getJNDIContextProviderURL ( ) ; if ( url != null ) { env . put ( Context . PROVIDER_URL , url ) ; } String custom = options . getJNDIContextCustom ( ) ; if ( custom != null ) { env . putAll ( parseDelimitedString ( custom ) ) ; } } // lookup the real data source InitialContext ctx ; try { if ( env != null ) { ctx = new InitialContext ( env ) ; } else { ctx = new InitialContext ( ) ; } realDataSource = ( CommonDataSource ) ctx . lookup ( rdsName ) ; } catch ( NamingException e ) { throw new SQLException ( "P6DataSource: naming exception during jndi lookup of Real Data Source Name of '" + rdsName + "'. " + e . getMessage ( ) , e ) ; } // Set any properties that the spy.properties file contains // that are supported by set methods in this class Map < String , String > props = parseDelimitedString ( options . getRealDataSourceProperties ( ) ) ; if ( props != null ) { setDataSourceProperties ( props ) ; } if ( realDataSource == null ) { throw new SQLException ( "P6DataSource: jndi lookup for Real Data Source Name of '" + rdsName + "' failed, cannot bind named data source." ) ; } }
Binds the JNDI DataSource to proxy .
539
11
28,773
public void generateLogMessage ( ) { if ( lastRowLogged != currRow ) { P6LogQuery . log ( Category . RESULTSET , this ) ; resultMap . clear ( ) ; lastRowLogged = currRow ; } }
Generates log message with column values accessed if the row s column values have not already been logged .
54
20
28,774
@ Override public void setExclude ( String exclude ) { optionsRepository . setSet ( String . class , EXCLUDE_LIST , exclude ) ; // setting effective string optionsRepository . set ( String . class , EXCLUDE , P6Util . joinNullSafe ( optionsRepository . getSet ( String . class , EXCLUDE_LIST ) , "," ) ) ; optionsRepository . setOrUnSet ( Pattern . class , INCLUDE_EXCLUDE_PATTERN , computeIncludeExcludePattern ( ) , defaults . get ( INCLUDE_EXCLUDE_PATTERN ) ) ; }
JMX exposed API
143
4
28,775
@ Override protected Response serve ( ) { invoke ( ) ; String s = ParseTime . getTimezone ( ) . getID ( ) ; JsonObject response = new JsonObject ( ) ; response . addProperty ( "tz" , s ) ; return Response . done ( response ) ; }
Reply value is the current setting
64
6
28,776
@ Override public V get ( ) { // check priorities - FJ task can only block on a task with higher priority! Thread cThr = Thread . currentThread ( ) ; int priority = ( cThr instanceof FJWThr ) ? ( ( FJWThr ) cThr ) . _priority : - 1 ; // was hitting this (priority=1 but _dt.priority()=0 for DRemoteTask) - not clear who increased priority of FJWThr to 1... // assert _dt.priority() > priority || (_dt.priority() == priority && (_dt instanceof DRemoteTask || _dt instanceof MRTask2)) assert _dt . priority ( ) > priority || ( ( _dt instanceof DRemoteTask || _dt instanceof MRTask2 ) ) : "*** Attempting to block on task (" + _dt . getClass ( ) + ") with equal or lower priority. Can lead to deadlock! " + _dt . priority ( ) + " <= " + priority ; if ( _done ) return result ( ) ; // Fast-path shortcut // Use FJP ManagedBlock for this blocking-wait - so the FJP can spawn // another thread if needed. try { try { ForkJoinPool . managedBlock ( this ) ; } catch ( InterruptedException e ) { } } catch ( Throwable t ) { // catch and rethrow to preserve the stack trace! throw new RuntimeException ( t ) ; } if ( _done ) return result ( ) ; // Fast-path shortcut assert isCancelled ( ) ; return null ; }
null for canceled tasks including those where the target dies .
341
11
28,777
protected int response ( AutoBuffer ab ) { assert _tasknum == ab . getTask ( ) ; if ( _done ) return ab . close ( ) ; // Ignore duplicate response packet int flag = ab . getFlag ( ) ; // Must read flag also, to advance ab if ( flag == SERVER_TCP_SEND ) return ab . close ( ) ; // Ignore UDP packet for a TCP reply assert flag == SERVER_UDP_SEND ; synchronized ( this ) { // Install the answer under lock if ( _done ) return ab . close ( ) ; // Ignore duplicate response packet UDPTimeOutThread . PENDING . remove ( this ) ; _dt . read ( ab ) ; // Read the answer (under lock?) _size_rez = ab . size ( ) ; // Record received size ab . close ( ) ; // Also finish the read (under lock?) _dt . onAck ( ) ; // One time only execute (before sending ACKACK) _done = true ; // Only read one (of many) response packets ab . _h2o . taskRemove ( _tasknum ) ; // Flag as task-completed, even if the result is null notifyAll ( ) ; // And notify in any case } doAllCompletions ( ) ; // Send all tasks needing completion to the work queues return 0 ; }
Install it as The Answer packet and wake up anybody waiting on an answer .
284
15
28,778
private void accum_all ( Chunk chks [ ] , Chunk wrks , int nnids [ ] ) { final DHistogram hcs [ ] [ ] = _hcs ; // Sort the rows by NID, so we visit all the same NIDs in a row // Find the count of unique NIDs in this chunk int nh [ ] = new int [ hcs . length + 1 ] ; for ( int i : nnids ) if ( i >= 0 ) nh [ i + 1 ] ++ ; // Rollup the histogram of rows-per-NID in this chunk for ( int i = 0 ; i < hcs . length ; i ++ ) nh [ i + 1 ] += nh [ i ] ; // Splat the rows into NID-groups int rows [ ] = new int [ nnids . length ] ; for ( int row = 0 ; row < nnids . length ; row ++ ) if ( nnids [ row ] >= 0 ) rows [ nh [ nnids [ row ] ] ++ ] = row ; // rows[] has Chunk-local ROW-numbers now, in-order, grouped by NID. // nh[] lists the start of each new NID, and is indexed by NID+1. accum_all2 ( chks , wrks , nh , rows ) ; }
histograms once - per - NID but requires pre - sorting the rows by NID .
294
19
28,779
private void accum_all2 ( Chunk chks [ ] , Chunk wrks , int nh [ ] , int [ ] rows ) { final DHistogram hcs [ ] [ ] = _hcs ; // Local temp arrays, no atomic updates. int bins [ ] = new int [ nbins ] ; double sums [ ] = new double [ nbins ] ; double ssqs [ ] = new double [ nbins ] ; // For All Columns for ( int c = 0 ; c < _ncols ; c ++ ) { // for all columns Chunk chk = chks [ c ] ; // For All NIDs for ( int n = 0 ; n < hcs . length ; n ++ ) { final DRealHistogram rh = ( ( DRealHistogram ) hcs [ n ] [ c ] ) ; if ( rh == null ) continue ; // Ignore untracked columns in this split final int lo = n == 0 ? 0 : nh [ n - 1 ] ; final int hi = nh [ n ] ; float min = rh . _min2 ; float max = rh . _maxIn ; // While most of the time we are limited to nbins, we allow more bins // in a few cases (top-level splits have few total bins across all // the (few) splits) so it's safe to bin more; also categoricals want // to split one bin-per-level no matter how many levels). if ( rh . _bins . length >= bins . length ) { // Grow bins if needed bins = new int [ rh . _bins . length ] ; sums = new double [ rh . _bins . length ] ; ssqs = new double [ rh . _bins . length ] ; } // Gather all the data for this set of rows, for 1 column and 1 split/NID // Gather min/max, sums and sum-squares. for ( int xrow = lo ; xrow < hi ; xrow ++ ) { int row = rows [ xrow ] ; float col_data = ( float ) chk . at0 ( row ) ; if ( col_data < min ) min = col_data ; if ( col_data > max ) max = col_data ; int b = rh . bin ( col_data ) ; // Compute bin# via linear interpolation bins [ b ] ++ ; // Bump count in bin double resp = wrks . at0 ( row ) ; sums [ b ] += resp ; ssqs [ b ] += resp * resp ; } // Add all the data into the Histogram (atomically add) rh . setMin ( min ) ; // Track actual lower/upper bound per-bin rh . setMax ( max ) ; for ( int b = 0 ; b < rh . _bins . length ; b ++ ) { // Bump counts in bins if ( bins [ b ] != 0 ) { Utils . AtomicIntArray . add ( rh . _bins , b , bins [ b ] ) ; bins [ b ] = 0 ; } if ( ssqs [ b ] != 0 ) { rh . incr1 ( b , sums [ b ] , ssqs [ b ] ) ; sums [ b ] = ssqs [ b ] = 0 ; } } } } }
For all columns for all NIDs for all ROWS ...
709
12
28,780
public String setAndServe ( String offset ) { _offset . reset ( ) ; _offset . check ( null , offset ) ; _view . reset ( ) ; _view . check ( null , "20" ) ; _filter . reset ( ) ; return new Gson ( ) . toJson ( serve ( ) . _response ) ; }
Used by tests
74
3
28,781
public int addArgument ( String str , String next ) { int i = commandLineArgs . length ; int consumed = 1 ; commandLineArgs = Arrays . copyOf ( commandLineArgs , i + 1 ) ; /* * Flags have a null string as val and flag of true; Binding have non-empty * name, a non-null val (possibly ""), and a flag of false; Plain strings * have an empty name, "", a non-null, non-empty val, and a flag of true; */ if ( str . startsWith ( "-" ) ) { int startOffset = ( str . startsWith ( "--" ) ) ? 2 : 1 ; String arg = "" ; String opt ; boolean flag = false ; int eqPos = str . indexOf ( "=" ) ; if ( eqPos > 0 || ( next != null && ! next . startsWith ( "-" ) ) ) { if ( eqPos > 0 ) { opt = str . substring ( startOffset , eqPos ) ; arg = str . substring ( eqPos + 1 ) ; } else { opt = str . substring ( startOffset ) ; arg = next ; consumed = 2 ; } } else { flag = true ; opt = str . substring ( startOffset ) ; } commandLineArgs [ i ] = new Entry ( opt , arg , flag , i ) ; return consumed ; } else { commandLineArgs [ i ] = new Entry ( "" , str , true , i ) ; return consumed ; } }
Add a new argument to this command line . The argument will be parsed and add at the end of the list . Bindings have the following format - name = value if value is empty the binding is treated as an option . Options have the form - name . All other strings are treated as values .
318
60
28,782
private int extract ( Arg arg , Field [ ] fields ) { int count = 0 ; for ( Field field : fields ) { String name = field . getName ( ) ; Class cl = field . getType ( ) ; String opt = getValue ( name ) ; // optional value try { if ( cl . isPrimitive ( ) ) { if ( cl == Boolean . TYPE ) { boolean curval = field . getBoolean ( arg ) ; boolean xval = curval ; if ( opt != null ) xval = ! curval ; if ( "1" . equals ( opt ) || "true" . equals ( opt ) ) xval = true ; if ( "0" . equals ( opt ) || "false" . equals ( opt ) ) xval = false ; if ( opt != null ) field . setBoolean ( arg , xval ) ; } else if ( opt == null || opt . length ( ) == 0 ) continue ; else if ( cl == Integer . TYPE ) field . setInt ( arg , Integer . parseInt ( opt ) ) ; else if ( cl == Float . TYPE ) field . setFloat ( arg , Float . parseFloat ( opt ) ) ; else if ( cl == Double . TYPE ) field . setDouble ( arg , Double . parseDouble ( opt ) ) ; else if ( cl == Long . TYPE ) field . setLong ( arg , Long . parseLong ( opt ) ) ; else continue ; count ++ ; } else if ( cl == String . class ) { if ( opt != null ) { field . set ( arg , opt ) ; count ++ ; } } } catch ( Exception e ) { Log . err ( "Argument failed with " , e ) ; } } Arrays . sort ( commandLineArgs ) ; for ( int i = 0 ; i < commandLineArgs . length ; i ++ ) commandLineArgs [ i ] . position = i ; return count ; }
Extracts bindings and options ; and sets appropriate fields in the CommandLineArgument object .
403
19
28,783
private void parse ( String [ ] s ) { commandLineArgs = new Entry [ 0 ] ; for ( int i = 0 ; i < s . length ; ) { String next = ( i + 1 < s . length ) ? s [ i + 1 ] : null ; i += addArgument ( s [ i ] , next ) ; } }
Parse the command line arguments and extracts options . The current implementation allows the same command line instance to parse several argument lists the results will be merged .
73
30
28,784
public float progress ( ) { Freezable f = UKV . get ( destination_key ) ; if ( f instanceof Progress ) return ( ( Progress ) f ) . progress ( ) ; return 0 ; }
Return progress of this job .
44
6
28,785
public static Job [ ] all ( ) { List list = UKV . get ( LIST ) ; Job [ ] jobs = new Job [ list == null ? 0 : list . _jobs . length ] ; int j = 0 ; for ( int i = 0 ; i < jobs . length ; i ++ ) { Job job = UKV . get ( list . _jobs [ i ] ) ; if ( job != null ) jobs [ j ++ ] = job ; } if ( j < jobs . length ) jobs = Arrays . copyOf ( jobs , j ) ; return jobs ; }
Returns a list of all jobs in a system .
121
10
28,786
public static boolean isRunning ( Key job_key ) { Job j = UKV . get ( job_key ) ; assert j != null : "Job should be always in DKV!" ; return j . isRunning ( ) ; }
Check if given job is running .
49
7
28,787
public void remove ( ) { end_time = System . currentTimeMillis ( ) ; if ( state == JobState . RUNNING ) state = JobState . DONE ; // Overwrite handle - copy end_time, state, msg replaceByJobHandle ( ) ; }
Marks job as finished and records job end time .
58
11
28,788
public static Job findJobByDest ( final Key destKey ) { Job job = null ; for ( Job current : Job . all ( ) ) { if ( current . dest ( ) . equals ( destKey ) ) { job = current ; break ; } } return job ; }
Finds a job with given dest key or returns null
58
11
28,789
public Job fork ( ) { init ( ) ; H2OCountedCompleter task = new H2OCountedCompleter ( ) { @ Override public void compute2 ( ) { try { try { // Exec always waits till the end of computation Job . this . exec ( ) ; Job . this . remove ( ) ; } catch ( Throwable t ) { if ( ! ( t instanceof ExpectedExceptionForDebug ) ) Log . err ( t ) ; Job . this . cancel ( t ) ; } } finally { tryComplete ( ) ; } } } ; start ( task ) ; H2O . submitTask ( task ) ; return this ; }
Forks computation of this job .
141
7
28,790
public static void waitUntilJobEnded ( Key jobkey , int pollingIntervalMillis ) { while ( true ) { if ( Job . isEnded ( jobkey ) ) { return ; } try { Thread . sleep ( pollingIntervalMillis ) ; } catch ( Exception ignore ) { } } }
Block synchronously waiting for a job to end success or not .
65
13
28,791
public static < T extends FrameJob > T hygiene ( T job ) { job . source = null ; return job ; }
Hygienic method to prevent accidental capture of non desired values .
25
14
28,792
@ Override protected Split ltSplit ( int col , Data d , int [ ] dist , int distWeight , Random rand ) { final int [ ] distL = new int [ d . classes ( ) ] , distR = dist . clone ( ) ; final double upperBoundReduction = upperBoundReduction ( d . classes ( ) ) ; double maxReduction = - 1 ; int bestSplit = - 1 ; int totL = 0 , totR = 0 ; // Totals in the distribution int classL = 0 , classR = 0 ; // Count of non-zero classes in the left/right distributions for ( int e : distR ) { // All zeros for the left, but need to compute for the right totR += e ; if ( e != 0 ) classR ++ ; } // For this one column, look at all his split points and find the one with the best gain. for ( int i = 0 ; i < _columnDists [ col ] . length - 1 ; ++ i ) { int [ ] cdis = _columnDists [ col ] [ i ] ; for ( int j = 0 ; j < distL . length ; ++ j ) { int v = cdis [ j ] ; if ( v == 0 ) continue ; // No rows with this class totL += v ; totR -= v ; if ( distL [ j ] == 0 ) classL ++ ; // One-time transit from zero to non-zero for class j distL [ j ] += v ; distR [ j ] -= v ; if ( distR [ j ] == 0 ) classR -- ; // One-time transit from non-zero to zero for class j } if ( totL == 0 ) continue ; // Totals are zero ==> this will not actually split anything if ( totR == 0 ) continue ; // Totals are zero ==> this will not actually split anything // Compute gain. // If the distribution has only 1 class, the gain will be zero. double eL = 0 , eR = 0 ; if ( classL > 1 ) for ( int e : distL ) eL += gain ( , totL ) ; if ( classR > 1 ) for ( int e : distR ) eR += gain ( , totR ) ; double eReduction = upperBoundReduction - ( ( eL * totL + eR * totR ) / ( totL + totR ) ) ; if ( eReduction == maxReduction ) { // For now, don't break ties. Most ties are because we have several // splits with NO GAIN. This happens *billions* of times in a standard // covtype RF, because we have >100K leaves per tree (and 50 trees and // 54 columns per leave and however many bins per column), and most // leaves have no gain at most split points. //if (rand.nextInt(10)<2) bestSplit=i; } else if ( eReduction > maxReduction ) { bestSplit = i ; maxReduction = eReduction ; } } return bestSplit == - 1 ? Split . impossible ( Utils . maxIndex ( dist , _random ) ) : Split . split ( col , bestSplit , maxReduction ) ; }
LessThenEqual splits s
688
6
28,793
public boolean inetAddressOnNetwork ( InetAddress ia ) { int i = ( _o1 << 24 ) | ( _o2 << 16 ) | ( _o3 << 8 ) | ( _o4 << 0 ) ; byte [ ] barr = ia . getAddress ( ) ; if ( barr . length != 4 ) { return false ; } int j = ( ( ( int ) barr [ 0 ] & 0xff ) << 24 ) | ( ( ( int ) barr [ 1 ] & 0xff ) << 16 ) | ( ( ( int ) barr [ 2 ] & 0xff ) << 8 ) | ( ( ( int ) barr [ 3 ] & 0xff ) << 0 ) ; // Do mask math in 64-bit to handle 32-bit wrapping cases. long mask1 = ( ( long ) 1 << ( 32 - _bits ) ) ; long mask2 = mask1 - 1 ; long mask3 = ~ mask2 ; int mask4 = ( int ) ( mask3 & 0xffffffff ) ; if ( ( i & mask4 ) == ( j & mask4 ) ) { return true ; } return false ; }
Test if an internet address lives on this user specified network .
240
12
28,794
public Lockable write_lock ( Key job_key ) { Log . debug ( Log . Tag . Sys . LOCKS , "write-lock " + _key + " by job " + job_key ) ; return ( ( PriorWriteLock ) new PriorWriteLock ( job_key ) . invoke ( _key ) ) . _old ; }
Write - lock this returns OLD guy
75
8
28,795
public T delete_and_lock ( Key job_key ) { Lockable old = write_lock ( job_key ) ; if ( old != null ) { Log . debug ( Log . Tag . Sys . LOCKS , "lock-then-clear " + _key + " by job " + job_key ) ; old . delete_impl ( new Futures ( ) ) . blockForPending ( ) ; } return ( T ) this ; }
Write - lock this delete any old thing returns NEW guy
98
11
28,796
public static void delete ( Key k , Key job_key ) { if ( k == null ) return ; Value val = DKV . get ( k ) ; if ( val == null ) return ; // Or just nothing there to delete if ( ! val . isLockable ( ) ) UKV . remove ( k ) ; // Simple things being deleted else ( ( Lockable ) val . get ( ) ) . delete ( job_key , 0.0f ) ; // Lockable being deleted }
Write - lock & delete k . Will fail if k is locked by anybody other than job_key
103
20
28,797
public void delete ( Key job_key , float dummy ) { if ( _key != null ) { Log . debug ( Log . Tag . Sys . LOCKS , "lock-then-delete " + _key + " by job " + job_key ) ; new PriorWriteLock ( job_key ) . invoke ( _key ) ; } Futures fs = new Futures ( ) ; delete_impl ( fs ) ; if ( _key != null ) DKV . remove ( _key , fs ) ; // Delete self also fs . blockForPending ( ) ; }
Will fail if locked by anybody other than job_key
123
11
28,798
public void update ( Key job_key ) { Log . debug ( Log . Tag . Sys . LOCKS , "update write-locked " + _key + " by job " + job_key ) ; new Update ( job_key ) . invoke ( _key ) ; }
Atomically set a new version of self
60
9
28,799
public void unlock ( Key job_key ) { if ( _key != null ) { Log . debug ( Log . Tag . Sys . LOCKS , "unlock " + _key + " by job " + job_key ) ; new Unlock ( job_key ) . invoke ( _key ) ; } }
Atomically set a new version of self & unlock .
67
12