idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
22,900
public void writeFile ( String aFileName , String aData ) throws IOException { Object lock = retrieveLock ( aFileName ) ; synchronized ( lock ) { IO . writeFile ( aFileName , aData , IO . CHARSET ) ; } }
Write string file data
55
4
22,901
private Object retrieveLock ( String key ) { Object lock = this . lockMap . get ( key ) ; if ( lock == null ) { lock = key ; this . lockMap . put ( key , lock ) ; } return lock ; }
Retrieve the lock object for a given key
50
9
22,902
protected void formatMessage ( String aID , Map < Object , Object > aBindValues ) { Presenter presenter = Presenter . getPresenter ( this . getClass ( ) ) ; message = presenter . getText ( aID , aBindValues ) ; }
Format the exception message using the presenter getText method
55
10
22,903
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) protected DirContext setupKerberosContext ( Hashtable < String , Object > env ) throws NamingException { LoginContext lc = null ; try { lc = new LoginContext ( getClass ( ) . getName ( ) , new JXCallbackHandler ( ) ) ; lc . login ( ) ; } catch ( LoginException ex ) { throw new NamingException ( "login problem: " + ex ) ; } DirContext ctx = ( DirContext ) Subject . doAs ( lc . getSubject ( ) , new JndiAction ( env ) ) ; if ( ctx == null ) throw new NamingException ( "another problem with GSSAPI" ) ; else return ctx ; }
Initial LDAP for kerberos support
170
8
22,904
public Principal authenicate ( String uid , char [ ] password ) throws SecurityException { String rootDN = Config . getProperty ( ROOT_DN_PROP ) ; int timeout = Config . getPropertyInteger ( TIMEOUT_SECS_PROP ) . intValue ( ) ; Debugger . println ( LDAP . class , "timeout=" + timeout ) ; String uidAttributeName = Config . getProperty ( UID_ATTRIB_NM_PROP ) ; String groupAttributeName = Config . getProperty ( GROUP_ATTRIB_NM_PROP , "" ) ; String memberOfAttributeName = Config . getProperty ( MEMBEROF_ATTRIB_NM_PROP , "" ) ; return authenicate ( uid , password , rootDN , uidAttributeName , memberOfAttributeName , groupAttributeName , timeout ) ; }
Authenticate user ID and password against the LDAP server
183
11
22,905
public GenericField [ ] getFields ( ) { Collection < GenericField > values = fieldMap . values ( ) ; if ( values == null || values . isEmpty ( ) ) return null ; GenericField [ ] fieldMirrors = new GenericField [ values . size ( ) ] ; values . toArray ( fieldMirrors ) ; return fieldMirrors ; }
List all fields
76
3
22,906
public void sortRows ( Comparator < List < String > > comparator ) { if ( data . isEmpty ( ) ) return ; Collections . sort ( data , comparator ) ; }
Sort the rows by comparator
40
6
22,907
public JavaBeanGeneratorCreator < T > randomizeProperty ( String property ) { if ( property == null || property . length ( ) == 0 ) return this ; this . randomizeProperties . add ( property ) ; return this ; }
Setup property to generate a random value
52
7
22,908
public JavaBeanGeneratorCreator < T > fixedProperties ( String ... fixedPropertyNames ) { if ( fixedPropertyNames == null || fixedPropertyNames . length == 0 ) { return this ; } HashSet < String > fixSet = new HashSet <> ( Arrays . asList ( fixedPropertyNames ) ) ; Map < Object , Object > map = null ; if ( this . prototype != null ) { map = JavaBean . toMap ( this . prototype ) ; } else map = JavaBean . toMap ( ClassPath . newInstance ( this . creationClass ) ) ; if ( map == null || map . isEmpty ( ) ) return this ; String propertyName = null ; for ( Object propertyNameObject : map . keySet ( ) ) { propertyName = String . valueOf ( propertyNameObject ) ; if ( ! fixSet . contains ( propertyName ) ) { this . randomizeProperty ( propertyName ) ; } } return this ; }
Randomized to records that are not in fixed list
205
10
22,909
public void setPrimaryKey ( int primaryKey ) throws IllegalArgumentException { if ( primaryKey <= NULL ) { this . primaryKey = Data . NULL ; } else { this . primaryKey = primaryKey ; //resetNew(); return ; } }
Set primary key
52
3
22,910
public T lookup ( String text ) { if ( text == null ) return null ; for ( Entry < String , T > entry : lookupMap . entrySet ( ) ) { if ( Text . matches ( text , entry . getKey ( ) ) ) return lookupMap . get ( entry . getKey ( ) ) ; } return null ; }
Lookup a value of the dictionary
71
7
22,911
@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public static final < T > Collection < DataRow > constructDataRows ( Iterator < T > iterator , QuestCriteria questCriteria , DataRowCreator visitor ) { if ( iterator == null ) return null ; ArrayList < DataRow > dataRows = new ArrayList < DataRow > ( BATCH_SIZE ) ; boolean usePaging = false ; boolean savePagination = false ; int pageSize = 0 ; PageCriteria pageCriteria = questCriteria . getPageCriteria ( ) ; Pagination pagination = null ; if ( pageCriteria != null ) { pageSize = pageCriteria . getSize ( ) ; if ( pageSize > 0 ) { usePaging = true ; savePagination = pageCriteria . isSavePagination ( ) ; if ( savePagination ) pagination = Pagination . getPagination ( pageCriteria ) ; } } if ( usePaging ) { //Process results with paging being used //int index = 0; T item ; DataRow dataRow ; while ( iterator . hasNext ( ) ) { item = iterator . next ( ) ; JavaBean . acceptVisitor ( item , visitor ) ; dataRow = visitor . getDataRow ( ) ; dataRows . add ( dataRow ) ; if ( savePagination ) pagination . store ( dataRow , pageCriteria ) ; visitor . clear ( ) ; //if datarows greater than page size if ( dataRows . size ( ) >= pageSize ) { //then check if has more results and continue to gather results in break ground if ( savePagination && iterator . hasNext ( ) ) { pagination . constructPaging ( iterator , pageCriteria , ( RowObjectCreator ) visitor ) ; } break ; //break look since page is filled } } } else { //no paging used Object item ; while ( iterator . hasNext ( ) ) { item = iterator . next ( ) ; JavaBean . acceptVisitor ( item , visitor ) ; dataRows . add ( visitor . getDataRow ( ) ) ; visitor . clear ( ) ; } } dataRows . trimToSize ( ) ; //data rows to paging collection PagingCollection < DataRow > pagingCollection = new PagingCollection < DataRow > ( dataRows , questCriteria . getPageCriteria ( ) ) ; return pagingCollection ; }
Process results with support for paging
530
7
22,912
public void rebind ( Remote [ ] remotes ) { String rmiUrl = null ; //loop thru remote objects for ( int i = 0 ; i < remotes . length ; i ++ ) { //use is if instance of Identifier if ( remotes [ i ] instanceof Identifier && ! Text . isNull ( ( ( Identifier ) remotes [ i ] ) . getId ( ) ) ) { rmiUrl = ( ( Identifier ) remotes [ i ] ) . getId ( ) ; } else { //get rmiUrl rmiUrl = Config . getProperty ( remotes [ i ] . getClass ( ) , "bind.rmi.url" ) ; } //rebind rebind ( rmiUrl , remotes [ i ] ) ; } }
Bind all object . Note that the rmiUrl in located in the config . properties
166
17
22,913
public static Registry getRegistry ( ) throws RemoteException { return LocateRegistry . getRegistry ( Config . getProperty ( RMI . class , "host" ) , Config . getPropertyInteger ( RMI . class , "port" ) . intValue ( ) ) ; }
Create a new local registry on a local port
60
9
22,914
public Object restore ( String savePoint , Class < ? > objClass ) { String location = whereIs ( savePoint , objClass ) ; Object cacheObject = CacheFarm . getCache ( ) . get ( location ) ; if ( cacheObject != null ) return cacheObject ; cacheObject = IO . deserialize ( new File ( location ) ) ; CacheFarm . getCache ( ) . put ( location , cacheObject ) ; return cacheObject ; }
Retrieve the de - serialized object
94
8
22,915
public void store ( String savePoint , Object obj ) { if ( savePoint == null ) throw new RequiredException ( "savePoint" ) ; if ( obj == null ) throw new RequiredException ( "obj" ) ; String location = whereIs ( savePoint , obj . getClass ( ) ) ; Debugger . println ( this , "Storing in " + location ) ; IO . serializeToFile ( obj , new File ( location ) ) ; }
Store the serialized object
96
5
22,916
static int requireValidExponent ( final int exponent ) { if ( exponent < MIN_EXPONENT ) { throw new IllegalArgumentException ( "exponent(" + exponent + ") < " + MIN_EXPONENT ) ; } if ( exponent > MAX_EXPONENT ) { throw new IllegalArgumentException ( "exponent(" + exponent + ") > " + MAX_EXPONENT ) ; } return exponent ; }
Validates given exponent .
92
5
22,917
public void setLookupTable ( Map < String , Map < K , V > > lookupTable ) { this . lookupTable = new TreeMap < String , Map < K , V > > ( lookupTable ) ; }
The key of the lookup table is a regular expression
46
10
22,918
@ SuppressWarnings ( "unchecked" ) public static < T > T getProperty ( Object bean , String name ) throws SystemException { try { return ( T ) getNestedProperty ( bean , name ) ; } catch ( Exception e ) { throw new SystemException ( "Get property \"" + name + "\" ERROR:" + e . getMessage ( ) , e ) ; } }
Retrieve the bean property
84
5
22,919
public static Collection < Object > getCollectionProperties ( Collection < ? > collection , String name ) throws Exception { if ( collection == null ) throw new IllegalArgumentException ( "collection, name" ) ; ArrayList < Object > list = new ArrayList < Object > ( collection . size ( ) ) ; for ( Object bean : collection ) { list . add ( getNestedProperty ( bean , name ) ) ; } return list ; }
Retrieve the list of properties that exists in a given collection
92
12
22,920
public String getText ( ) { //loop thru text StringText stringText = new StringText ( ) ; stringText . setText ( this . target . getText ( ) ) ; TextDecorator < Textable > textDecorator = null ; //loop thru decorator and get results from each for ( Iterator < TextDecorator < Textable > > i = textables . iterator ( ) ; i . hasNext ( ) ; ) { textDecorator = i . next ( ) ; textDecorator . setTarget ( stringText ) ; stringText . setText ( textDecorator . getText ( ) ) ; } return stringText . getText ( ) ; }
Get the target text and execute each text decorator on its results
146
13
22,921
public static < T > Collection < T > sortByCriteria ( Collection < T > aVOs ) { final List < T > list ; if ( aVOs instanceof List ) list = ( List < T > ) aVOs ; else list = new ArrayList < T > ( aVOs ) ; Collections . sort ( list , new CriteriaComparator ( ) ) ; return list ; }
Sort a list
85
3
22,922
@ Override public void bag ( Date unBaggedObject ) { if ( unBaggedObject == null ) this . time = 0 ; else this . time = unBaggedObject . getTime ( ) ; }
Wraps a given date in a format that can be easily unbagged
45
14
22,923
public static Method findMethod ( Class < ? > objClass , String methodName , Class < ? > [ ] parameterTypes ) throws NoSuchMethodException { try { return objClass . getDeclaredMethod ( methodName , parameterTypes ) ; } catch ( NoSuchMethodException e ) { if ( Object . class . equals ( objClass ) ) throw e ; try { // try super return findMethod ( objClass . getSuperclass ( ) , methodName , parameterTypes ) ; } catch ( NoSuchMethodException parentException ) { throw e ; } } }
Find the method for a target of its parent
117
9
22,924
@ Override public String getText ( ) { if ( this . target == null ) return null ; try { //Check if load of template needed if ( ( this . template == null || this . template . length ( ) == 0 ) && this . templateName != null ) { try { this . template = Text . loadTemplate ( templateName ) ; } catch ( Exception e ) { throw new SetupException ( "Cannot load template:" + templateName , e ) ; } } Map < Object , Object > faultMap = JavaBean . toMap ( this . target ) ; if ( this . argumentTextDecorator != null ) { this . argumentTextDecorator . setTarget ( this . target . getArgument ( ) ) ; faultMap . put ( this . argumentKeyName , this . argumentTextDecorator . getText ( ) ) ; } return Text . format ( this . template , faultMap ) ; } catch ( FormatException e ) { throw new FormatFaultException ( this . template , e ) ; } }
Converts the target fault into a formatted text .
219
10
22,925
public static void addCells ( StringBuilder builder , String ... cells ) { if ( builder == null || cells == null || cells . length == 0 ) return ; for ( String cell : cells ) { addCell ( builder , cell ) ; } }
Add formatted CSV cells to a builder
52
7
22,926
public static String toCSV ( String ... cells ) { if ( cells == null || cells . length == 0 ) return null ; StringBuilder builder = new StringBuilder ( ) ; addCells ( builder , cells ) ; return builder . toString ( ) ; }
Create a CSV line
55
4
22,927
public String encryptText ( String text ) throws Exception { return toByteText ( this . encrypt ( text . getBytes ( IO . CHARSET ) ) ) ; }
The text to encrypt
35
4
22,928
public static void main ( String [ ] args ) { try { if ( args . length == 0 ) { System . err . println ( "Usage java " + Cryption . class . getName ( ) + " <text>" ) ; return ; } final String decryptedPassword ; if ( args [ 0 ] . equals ( "-d" ) ) { if ( args . length > 2 ) { StringBuilder p = new StringBuilder ( ) ; for ( int i = 1 ; i < args . length ; i ++ ) { if ( i > 1 ) p . append ( ' ' ) ; p . append ( args [ i ] ) ; } decryptedPassword = p . toString ( ) ; } else { decryptedPassword = args [ 1 ] ; } System . out . println ( getCanonical ( ) . decryptText ( decryptedPassword ) ) ; } else System . out . println ( CRYPTION_PREFIX + getCanonical ( ) . encryptText ( args [ 0 ] ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
Encrypt a given values
232
5
22,929
@ Override public int compareTo ( Object object ) { if ( ! ( object instanceof User ) ) { return - 1 ; } User user = ( User ) object ; return getLastName ( ) . compareTo ( user . getLastName ( ) ) ; }
Compare user s by last name
56
6
22,930
public static Object executeMethod ( Object object , MethodCallFact methodCallFact ) throws Exception { if ( object == null ) throw new RequiredException ( "object" ) ; if ( methodCallFact == null ) throw new RequiredException ( "methodCallFact" ) ; return executeMethod ( object , methodCallFact . getMethodName ( ) , methodCallFact . getArguments ( ) ) ; }
Execute the method call on a object
83
8
22,931
public synchronized void setUp ( ) { if ( initialized ) return ; String className = null ; //Load Map < Object , Object > properties = settings . getProperties ( ) ; String key = null ; Object serviceObject = null ; for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { key = String . valueOf ( entry . getKey ( ) ) ; if ( key . startsWith ( PROP_PREFIX ) ) { try { className = ( String ) entry . getValue ( ) ; serviceObject = ClassPath . newInstance ( className ) ; factoryMap . put ( key , serviceObject ) ; } catch ( Throwable e ) { throw new SetupException ( "CLASS:" + className + " ERROR:" + e . getMessage ( ) , e ) ; } } } initialized = true ; }
Setup the factory beans
181
4
22,932
private String getValidURL ( String url ) { if ( url != null && url . length ( ) > 0 ) { // XXX really important that this one happens first!! return url . replaceAll ( "[%]" , "%25" ) . replaceAll ( " " , "%20" ) . replaceAll ( "[<]" , "%3c" ) . replaceAll ( "[>]" , "%3e" ) . replaceAll ( "[\"]" , "%3f" ) . replaceAll ( "[#]" , "%23" ) . replaceAll ( "[{]" , "%7b" ) . replaceAll ( "[}]" , "%7d" ) . replaceAll ( "[|]" , "%7c" ) . replaceAll ( "[\\\\]" , "%5c" ) // double check this // one :-) . replaceAll ( "[\\^]" , "%5e" ) . replaceAll ( "[~]" , "%7e" ) . replaceAll ( "[\\[]" , "%5b" ) . replaceAll ( "[\\]]" , "%5d" ) . replaceAll ( "[']" , "%27" ) . replaceAll ( "[?]" , "%3f" ) ; } return url ; }
Returns valid LDAP URL for the specified URL .
256
10
22,933
private static void setupSimpleSecurityProperties ( Hashtable < String , Object > env , String userDn , char [ ] pwd ) { // 'simple' = username + password env . put ( Context . SECURITY_AUTHENTICATION , "simple" ) ; // add the full user dn env . put ( Context . SECURITY_PRINCIPAL , userDn ) ; // set password env . put ( Context . SECURITY_CREDENTIALS , new String ( pwd ) ) ; }
Sets the environment properties needed for a simple username + password authenticated jndi connection .
114
18
22,934
private Hashtable < ? , ? > setupBasicProperties ( Hashtable < String , Object > env ) throws NamingException { return setupBasicProperties ( env , this . fullUrl ) ; }
Sets basic LDAP connection properties in env .
42
10
22,935
public static String getProperty ( Class < ? > aClass , String key , ResourceBundle resourceBundle ) { return getSettings ( ) . getProperty ( aClass , key , resourceBundle ) ; }
Get the property
44
3
22,936
public static String getProperty ( String key , String aDefault ) { return getSettings ( ) . getProperty ( key , aDefault ) ; }
Retrieves a configuration property as a String object .
30
11
22,937
public static Integer getPropertyInteger ( Class < ? > aClass , String key , int defaultValue ) { return getSettings ( ) . getPropertyInteger ( key , defaultValue ) ; }
Get a configuration property as an Integer object .
39
9
22,938
public static Character getPropertyCharacter ( Class < ? > aClass , String key , char defaultValue ) { return getSettings ( ) . getPropertyCharacter ( aClass , key , defaultValue ) ; }
Get a configuration property as an c object .
42
9
22,939
public static char [ ] getPropertyPassword ( Class < ? > aClass , String key , char [ ] defaultPassword ) { return getSettings ( ) . getPropertyPassword ( aClass , key , defaultPassword ) ; }
Retrieve the password
46
4
22,940
public static < T > void addAll ( Collection < T > pagingResults , Collection < T > paging , BooleanExpression < T > filter ) { if ( pagingResults == null || paging == null ) return ; if ( filter != null ) { for ( T obj : paging ) { if ( filter . apply ( obj ) ) pagingResults . add ( obj ) ; } } else { // add independent of a filter for ( T obj : paging ) { pagingResults . add ( obj ) ; } } }
Add all collections
113
3
22,941
public static Object findMapValueByKey ( Object key , Map < ? , ? > map , Object defaultValue ) { if ( key == null || map == null ) return defaultValue ; Object value = map . get ( key ) ; if ( value == null ) return defaultValue ; return value ; }
Find the value with a given key in the map .
63
11
22,942
public static void addAll ( Collection < Object > list , Object [ ] objects ) { list . addAll ( Arrays . asList ( objects ) ) ; }
Add object to a list
34
5
22,943
public static void copyToArray ( Collection < Object > collection , Object [ ] objects ) { System . arraycopy ( collection . toArray ( ) , 0 , objects , 0 , objects . length ) ; }
Copy collection objects to a given array
43
7
22,944
public static < K , V > void addMappableCopiesToMap ( Collection < Mappable < K , V > > aMappables , Map < K , V > aMap ) { if ( aMappables == null || aMap == null ) return ; Mappable < K , V > mappable = null ; Copier previous = null ; for ( Iterator < Mappable < K , V > > i = aMappables . iterator ( ) ; i . hasNext ( ) ; ) { mappable = i . next ( ) ; previous = ( Copier ) aMap . get ( mappable . getKey ( ) ) ; if ( previous != null ) { // copy data previous . copy ( ( Copier ) mappable ) ; } else { // add to map aMap . put ( ( K ) mappable . getKey ( ) , ( V ) mappable . getValue ( ) ) ; } } }
Add mappable to map
207
6
22,945
public static < T , K > Collection < T > findMapValuesByKey ( Collection < K > aKeys , Map < K , T > aMap ) { if ( aKeys == null || aMap == null ) return null ; Object key = null ; ArrayList < T > results = new ArrayList < T > ( aMap . size ( ) ) ; for ( Iterator < K > i = aKeys . iterator ( ) ; i . hasNext ( ) ; ) { key = i . next ( ) ; results . add ( aMap . get ( key ) ) ; } results . trimToSize ( ) ; return results ; }
Find values in map that match a given key
135
9
22,946
public static < T > void addAll ( Collection < T > aFrom , Collection < T > aTo ) { if ( aFrom == null || aTo == null ) return ; // do nothing T object = null ; for ( Iterator < T > i = aFrom . iterator ( ) ; i . hasNext ( ) ; ) { object = i . next ( ) ; if ( object != null ) { aTo . add ( object ) ; } } }
All object to a given collection
97
6
22,947
public static Map < String , Criteria > constructCriteriaMap ( Collection < Criteria > aCriterias ) { if ( aCriterias == null ) return null ; Map < String , Criteria > map = new HashMap < String , Criteria > ( aCriterias . size ( ) ) ; Criteria criteria = null ; for ( Iterator < Criteria > i = aCriterias . iterator ( ) ; i . hasNext ( ) ; ) { criteria = ( Criteria ) i . next ( ) ; map . put ( criteria . getId ( ) , criteria ) ; } return map ; }
construct map for collection of criteria object wher the key is Criteria . getId
131
17
22,948
public static Map < Integer , PrimaryKey > constructPrimaryKeyMap ( Collection < PrimaryKey > aPrimaryKeys ) { if ( aPrimaryKeys == null ) return null ; Map < Integer , PrimaryKey > map = new HashMap < Integer , PrimaryKey > ( aPrimaryKeys . size ( ) ) ; PrimaryKey primaryKey = null ; for ( Iterator < PrimaryKey > i = aPrimaryKeys . iterator ( ) ; i . hasNext ( ) ; ) { primaryKey = ( PrimaryKey ) i . next ( ) ; map . put ( Integer . valueOf ( primaryKey . getPrimaryKey ( ) ) , primaryKey ) ; } return map ; }
construct map for collection of criteria object where the key is Criteria . getId
138
16
22,949
public static < K > void makeAuditableCopies ( Map < K , Copier > aFormMap , Map < K , Copier > aToMap , Auditable aAuditable ) { if ( aFormMap == null || aToMap == null ) return ; // for thru froms K fromKey = null ; Copier to = null ; Copier from = null ; for ( Map . Entry < K , Copier > entry : aFormMap . entrySet ( ) ) { fromKey = entry . getKey ( ) ; if ( aToMap . keySet ( ) . contains ( fromKey ) ) { // copy existening data to = ( Copier ) aToMap . get ( fromKey ) ; to . copy ( ( Copier ) entry . getValue ( ) ) ; // copy auditing info if ( aAuditable != null && to instanceof Auditable ) { AbstractAuditable . copy ( aAuditable , ( Auditable ) to ) ; } } else { from = ( Copier ) aFormMap . get ( fromKey ) ; // copy auditing info if ( aAuditable != null && from instanceof Auditable ) { AbstractAuditable . copy ( aAuditable , ( Auditable ) from ) ; } // add to aToMap . put ( fromKey , from ) ; } } }
Copy value form one map to another
281
7
22,950
public static Object [ ] toArray ( Object obj ) { if ( obj instanceof Object [ ] ) return ( Object [ ] ) obj ; else { Object [ ] returnArray = { obj } ; return returnArray ; } }
Cast into an array of objects or create a array with a single entry
47
14
22,951
public static < StoredObjectType , ResultSetType > Pagination createPagination ( PageCriteria pageCriteria ) { String id = pageCriteria . getId ( ) ; if ( id == null || id . length ( ) == 0 ) { return null ; } Pagination pagination = ClassPath . newInstance ( paginationClassName , String . class , pageCriteria . getId ( ) ) ; paginationMap . put ( id , pagination ) ; return pagination ; }
Create a pagination instance
105
5
22,952
public void loadJar ( File fileJar ) throws IOException { JarFile jar = null ; try { jar = new JarFile ( fileJar ) ; Enumeration < JarEntry > enumerations = jar . entries ( ) ; JarEntry entry = null ; byte [ ] classByte = null ; ByteArrayOutputStream byteStream = null ; String fileName = null ; String className = null ; Class < ? > jarClass = null ; while ( enumerations . hasMoreElements ( ) ) { entry = ( JarEntry ) enumerations . nextElement ( ) ; if ( entry . isDirectory ( ) ) continue ; //skip directories fileName = entry . getName ( ) ; if ( ! fileName . endsWith ( ".class" ) ) continue ; //skip non classes InputStream is = jar . getInputStream ( entry ) ; byteStream = new ByteArrayOutputStream ( ) ; IO . write ( byteStream , is ) ; classByte = byteStream . toByteArray ( ) ; className = formatClassName ( fileName ) ; Debugger . println ( this , "className=" + className ) ; jarClass = defineClass ( className , classByte , 0 , classByte . length , null ) ; classes . put ( className , jarClass ) ; classByte = null ; byteStream = null ; } //end while } finally { if ( jar != null ) { try { jar . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } }
Load all classes in the fileJar
320
7
22,953
public Class < ? > findClass ( String className ) { Class < ? > result = null ; // look in hash map result = ( Class < ? > ) classes . get ( className ) ; if ( result != null ) { return result ; } try { return findSystemClass ( className ) ; } catch ( Exception e ) { Debugger . printWarn ( e ) ; } try { URL resourceURL = ClassLoader . getSystemResource ( className . replace ( ' ' , File . separatorChar ) + ".class" ) ; if ( resourceURL == null ) return null ; String classPath = resourceURL . getFile ( ) ; classPath = classPath . substring ( 1 ) ; return loadClass ( className , new File ( classPath ) ) ; } catch ( Exception e ) { Debugger . printError ( e ) ; return null ; } }
Find the class by it name
185
6
22,954
private byte [ ] loadClassBytes ( File classFile ) throws IOException { int size = ( int ) classFile . length ( ) ; byte buff [ ] = new byte [ size ] ; FileInputStream fis = new FileInputStream ( classFile ) ; DataInputStream dis = null ; try { dis = new DataInputStream ( fis ) ; dis . readFully ( buff ) ; } finally { if ( dis != null ) dis . close ( ) ; } return buff ; }
Load the class name
104
4
22,955
public int compareTo ( Day object ) { if ( object == null ) throw new IllegalArgumentException ( "day cannot be null" ) ; Day day = ( Day ) object ; return localDate . compareTo ( day . localDate ) ; }
Compare this day to the specified day . If object is not of type Day a ClassCastException is thrown .
52
22
22,956
public boolean isAfter ( Day day ) { if ( day == null ) throw new IllegalArgumentException ( "day cannot be null" ) ; return localDate . isAfter ( day . localDate ) ; }
Return true if this day is after the specified day .
44
11
22,957
public boolean isBefore ( Day day ) { if ( day == null ) throw new IllegalArgumentException ( "day cannot be null" ) ; return localDate . isBefore ( day . localDate ) ; }
Return true if this day is before the specified day .
44
11
22,958
public boolean isSameDay ( Day compared ) { if ( compared == null ) return false ; return this . getMonth ( ) == compared . getMonth ( ) && this . getDayOfMonth ( ) == compared . getDayOfMonth ( ) && this . getYear ( ) == compared . getYear ( ) ; }
Compare based on month day year
67
6
22,959
@ Override public synchronized String lookup ( String id ) { if ( this . properties == null ) this . setUp ( ) ; String associated = this . properties . getProperty ( id ) ; if ( associated == null ) { associated = this . next ( ) ; //Est. new association register ( id , associated ) ; } return associated ; }
Lookup the location of a key
72
7
22,960
public void manage ( int workersCount ) { this . workers . clear ( ) ; WorkerThread worker = null ; for ( int i = 0 ; i < workersCount ; i ++ ) { worker = new WorkerThread ( this ) ; //TODO expensive use thread pool this . manage ( worker ) ; } }
Manage a number of default worker threads
65
8
22,961
String getMatchingJavaEncoding ( String javaEncoding ) { if ( javaEncoding != null && this . javaEncodingsUc . contains ( javaEncoding . toUpperCase ( Locale . ENGLISH ) ) ) { return javaEncoding ; } return this . javaEncodingsUc . get ( 0 ) ; }
If javaEncoding parameter value is one of available java encodings for this charset then returns javaEncoding value as is . Otherwise returns first available java encoding name .
74
35
22,962
@ Override public UserProfile convert ( String text ) { if ( text == null || text . trim ( ) . length ( ) == 0 ) return null ; String [ ] lines = text . split ( "\\\n" ) ; BiConsumer < String , UserProfile > strategy = null ; UserProfile userProfile = null ; String lineUpper = null ; for ( String line : lines ) { //get first term int index = line . indexOf ( ";" ) ; if ( index < 0 ) continue ; //skip line // String term = line . substring ( 0 , index ) ; strategy = strategies . get ( term . toLowerCase ( ) ) ; lineUpper = line . toUpperCase ( ) ; if ( strategy == null ) { //check for a different format //N:Green;Gregory;;; if ( lineUpper . startsWith ( "N:" ) ) strategy = strategies . get ( "n" ) ; else if ( lineUpper . startsWith ( "FN:" ) ) strategy = strategies . get ( "fn" ) ; else if ( lineUpper . contains ( "EMAIL;" ) ) strategy = strategies . get ( "email" ) ; else continue ; //skip } if ( userProfile == null ) { userProfile = ClassPath . newInstance ( this . userProfileClass ) ; } strategy . accept ( line , userProfile ) ; } return userProfile ; }
Convert from text from user profile
298
7
22,963
public synchronized static ServiceFactory getInstance ( Class < ? > aClass , String configurationPath ) { if ( configurationPath == null ) { configurationPath = "" ; } if ( instances . get ( configurationPath ) == null ) { instances . put ( configurationPath , createServiceFactory ( aClass , configurationPath ) ) ; } return ( ServiceFactory ) instances . get ( configurationPath ) ; }
Singleton factory method
81
4
22,964
public String getText ( ) { //convert textable to map of text Object key = null ; try { //read bindTemplate String bindTemplate = getTemplate ( ) ; Map < Object , String > textMap = new Hashtable < Object , String > ( ) ; for ( Map . Entry < String , Textable > entry : map . entrySet ( ) ) { key = entry . getKey ( ) ; try { //convert to text textMap . put ( key , ( entry . getValue ( ) ) . getText ( ) ) ; } catch ( Exception e ) { throw new SystemException ( "Unable to build text for key:" + key + " error:" + e . getMessage ( ) , e ) ; } } Debugger . println ( this , "bindTemplate=" + bindTemplate ) ; String formattedOutput = Text . format ( bindTemplate , textMap ) ; Debugger . println ( this , "formattedOutput=" + formattedOutput ) ; return formattedOutput ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new SetupException ( e . getMessage ( ) , e ) ; } }
Convert get text output from each Textable in map . Return the format output using Text . format .
242
21
22,965
public < T > Collection < T > startWorking ( Callable < T > [ ] callables ) { List < Future < T >> list = new ArrayList < Future < T > > ( ) ; for ( int i = 0 ; i < callables . length ; i ++ ) { list . add ( executor . submit ( callables [ i ] ) ) ; } ArrayList < T > resultList = new ArrayList < T > ( callables . length ) ; // Now retrieve the result T output ; for ( Future < T > future : list ) { try { output = future . get ( ) ; if ( output != null ) resultList . add ( output ) ; } catch ( InterruptedException e ) { throw new SystemException ( e ) ; } catch ( ExecutionException e ) { throw new SystemException ( e ) ; } } return resultList ; }
Start the array of the callables
182
7
22,966
public Collection < Future < ? > > startWorking ( WorkQueue queue , boolean background ) { ArrayList < Future < ? > > futures = new ArrayList < Future < ? > > ( queue . size ( ) ) ; while ( queue . hasMoreTasks ( ) ) { futures . add ( executor . submit ( queue . nextTask ( ) ) ) ; } if ( background ) return futures ; try { for ( Future < ? > future : futures ) { future . get ( ) ; //join submitted thread } return futures ; } catch ( InterruptedException e ) { throw new SystemException ( e ) ; } catch ( ExecutionException e ) { throw new SystemException ( e ) ; } }
The start the work threads
146
5
22,967
public static Mirror newInstanceForClassName ( String className ) throws ClassNotFoundException , InstantiationException , IllegalAccessException { className = className . trim ( ) ; Class < ? > objClass = Class . forName ( className ) ; return new Mirror ( ClassPath . newInstance ( objClass ) ) ; }
Create an instance of the given object
69
7
22,968
public static void waitFor ( File aFile ) { if ( aFile == null ) return ; String path = aFile . getAbsolutePath ( ) ; long previousSize = IO . getFileSize ( path ) ; long currentSize = previousSize ; long sleepTime = Config . getPropertyLong ( "file.monitor.file.wait.time" , 100 ) . longValue ( ) ; while ( true ) { try { Thread . sleep ( sleepTime ) ; } catch ( InterruptedException e ) { } currentSize = IO . getFileSize ( path ) ; if ( currentSize == previousSize ) return ; previousSize = currentSize ; } }
Used to wait for transferred file s content length to stop changes for 5 seconds
138
15
22,969
protected synchronized void notifyChange ( File file ) { System . out . println ( "Notify change file=" + file . getAbsolutePath ( ) ) ; this . notify ( FileEvent . createChangedEvent ( file ) ) ; }
Notify observers that the file has changed
49
8
22,970
@ Override public UserProfile convert ( File file ) { if ( file == null ) return null ; try { String text = IO . readFile ( file ) ; if ( text == null || text . length ( ) == 0 ) return null ; return converter . convert ( text ) ; } catch ( IOException e ) { throw new SystemException ( "Unable to convert file:" + file . getAbsolutePath ( ) + " to user profile ERROR:" + e . getMessage ( ) , e ) ; } }
Convert the user profile
108
5
22,971
public < T > void register ( String subjectName , SubjectObserver < T > subjectObserver , Subject < T > subject ) { subject . add ( subjectObserver ) ; this . registry . put ( subjectName , subject ) ; }
Add subject observer to a subject
50
6
22,972
@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public < T > void removeRegistraion ( String subjectName , SubjectObserver < T > subjectObserver ) { Subject subject = ( Subject ) this . registry . get ( subjectName ) ; if ( subject == null ) return ; subject . remove ( subjectObserver ) ; }
Remove an observer for a registered observer
79
7
22,973
@ SuppressWarnings ( { "Duplicates" } ) public static BufferByteOutput < ByteBuffer > of ( final int capacity , final WritableByteChannel channel ) { if ( capacity <= 0 ) { throw new IllegalArgumentException ( "capacity(" + capacity + ") <= 0" ) ; } if ( channel == null ) { throw new NullPointerException ( "channel is null" ) ; } return new BufferByteOutput < ByteBuffer > ( null ) { @ Override public void write ( final int value ) throws IOException { if ( target == null ) { target = ByteBuffer . allocate ( capacity ) ; // position: zero, limit: capacity } if ( ! target . hasRemaining ( ) ) { // no space to put target . flip ( ) ; // limit -> position, position -> zero do { channel . write ( target ) ; } while ( target . position ( ) == 0 ) ; target . compact ( ) ; } super . write ( value ) ; } @ Override public void setTarget ( final ByteBuffer target ) { throw new UnsupportedOperationException ( ) ; } } ; }
Creates a new instance which writes bytes to specified channel using a byte buffer of given capacity .
236
19
22,974
public static int flush ( final BufferByteOutput < ? > output , final WritableByteChannel channel ) throws IOException { final ByteBuffer buffer = output . getTarget ( ) ; if ( buffer == null ) { return 0 ; } int written = 0 ; for ( buffer . flip ( ) ; buffer . hasRemaining ( ) ; ) { written += channel . write ( buffer ) ; } buffer . clear ( ) ; // position -> zero; limit -> capacity return written ; }
Flushes the internal byte buffer of given byte output to specified channel and returns the number of bytes written .
99
21
22,975
public static long durationMS ( LocalDateTime start , LocalDateTime end ) { if ( start == null || end == null ) { return 0 ; } return Duration . between ( start , end ) . toMillis ( ) ; }
The time between two dates
49
5
22,976
public static double durationSeconds ( LocalDateTime start , LocalDateTime end ) { return Duration . between ( start , end ) . getSeconds ( ) ; }
1 millisecond = 0 . 001 seconds
35
9
22,977
public static long durationHours ( LocalDateTime start , LocalDateTime end ) { if ( start == null || end == null ) return ZERO ; return Duration . between ( start , end ) . toHours ( ) ; }
1 Hours = 60 minutes
47
5
22,978
public void scheduleRecurring ( Runnable runnable , Date firstTime , long period ) { timer . scheduleAtFixedRate ( toTimerTask ( runnable ) , firstTime , period ) ; }
Schedule runnable to run a given interval
44
10
22,979
public static TimerTask toTimerTask ( Runnable runnable ) { if ( runnable instanceof TimerTask ) return ( TimerTask ) runnable ; return new TimerTaskRunnerAdapter ( runnable ) ; }
Convert timer task to a runnable
52
9
22,980
public String getText ( ) { if ( this . target == null ) throw new RequiredException ( "this.target in ReplaceTextDecorator" ) ; return Text . replaceForRegExprWith ( this . target . getText ( ) , regExp , replacement ) ; }
replace the text based on a RegExpr
59
9
22,981
public Integer getInteger ( Class < ? > aClass , String key , int defaultValue ) { return getInteger ( aClass . getName ( ) + ".key" , defaultValue ) ; }
Get a Setting property as an Integer object .
41
9
22,982
public Character getCharacter ( Class < ? > aClass , String key , char defaultValue ) { String results = getText ( aClass , key , "" ) ; if ( results . length ( ) == 0 ) return Character . valueOf ( defaultValue ) ; else return Character . valueOf ( results . charAt ( 0 ) ) ; //return first character }
Get a Settings property as an c object .
75
9
22,983
public Integer getInteger ( String key ) { Integer iVal = null ; String sVal = getText ( key ) ; if ( ( sVal != null ) && ( sVal . length ( ) > 0 ) ) { iVal = Integer . valueOf ( sVal ) ; } return iVal ; }
Get a Settings property as an Integer object .
64
9
22,984
public Boolean getBoolean ( String key ) { Boolean bVal = null ; String sVal = getText ( key ) ; if ( ( sVal != null ) && ( sVal . length ( ) > 0 ) ) { bVal = Boolean . valueOf ( sVal ) ; } return bVal ; }
Get a Setting property as a Boolean object .
65
9
22,985
public synchronized void playMethodCalls ( Memento memento , String [ ] savePoints ) { String savePoint = null ; MethodCallFact methodCallFact = null ; SummaryException exceptions = new SummaryException ( ) ; //loop thru savepoints for ( int i = 0 ; i < savePoints . length ; i ++ ) { savePoint = savePoints [ i ] ; if ( savePoint == null || savePoint . length ( ) == 0 || savePoint . trim ( ) . length ( ) == 0 ) continue ; Debugger . println ( this , "processing savepoint=" + savePoint ) ; //get method call fact methodCallFact = ( MethodCallFact ) memento . restore ( savePoint , MethodCallFact . class ) ; try { ObjectProxy . executeMethod ( prepareObject ( methodCallFact , savePoint ) , methodCallFact ) ; } catch ( Exception e ) { exceptions . addException ( new SystemException ( "savePoint=" + savePoint + " methodCallFact=" + methodCallFact + " exception=" + Debugger . stackTrace ( e ) ) ) ; throw new SystemException ( e ) ; // TODO: } } if ( ! exceptions . isEmpty ( ) ) throw exceptions ; }
Redo the method calls of a target object
259
9
22,986
public static void printError ( Object caller , Object message ) { StringBuilder text = new StringBuilder ( ) ; Class < ? > c = callerBuilder ( caller , text ) ; if ( message instanceof Throwable ) getLog ( c ) . error ( text . append ( stackTrace ( ( Throwable ) message ) ) ) ; else getLog ( c ) . error ( text . append ( message ) ) ; }
Print a error message . The stack trace will be printed if the given message is an exception .
88
19
22,987
public static void printError ( Object errorMessage ) { if ( errorMessage instanceof Throwable ) { Throwable e = ( Throwable ) errorMessage ; getLog ( Debugger . class ) . error ( stackTrace ( e ) ) ; } else getLog ( Debugger . class ) . error ( errorMessage ) ; }
Print error message using the configured log . The stack trace will be printed if the given message is an exception .
69
22
22,988
public static void printFatal ( Object message ) { if ( message instanceof Throwable ) { Throwable e = ( Throwable ) message ; e . printStackTrace ( ) ; } Log log = getLog ( Debugger . class ) ; if ( log != null ) log . fatal ( message ) ; else System . err . println ( message ) ; }
Print a fatal level message . The stack trace will be printed if the given message is an exception .
76
20
22,989
public static void printFatal ( Object caller , Object message ) { StringBuilder text = new StringBuilder ( ) ; Class < ? > c = callerBuilder ( caller , text ) ; if ( message instanceof Throwable ) getLog ( c ) . fatal ( text . append ( stackTrace ( ( Throwable ) message ) ) ) ; else getLog ( c ) . fatal ( text . append ( message ) ) ; }
Print a fatal message . The stack trace will be printed if the given message is an exception .
89
19
22,990
public static void printInfo ( Object caller , Object message ) { StringBuilder text = new StringBuilder ( ) ; Class < ? > c = callerBuilder ( caller , text ) ; if ( message instanceof Throwable ) getLog ( c ) . info ( text . append ( stackTrace ( ( Throwable ) message ) ) ) ; else getLog ( c ) . info ( text . append ( message ) ) ; }
Print an INFO message
88
4
22,991
public static void printInfo ( Object message ) { if ( message instanceof Throwable ) { Throwable e = ( Throwable ) message ; getLog ( Debugger . class ) . info ( stackTrace ( e ) ) ; } else getLog ( Debugger . class ) . info ( message ) ; }
Print a INFO level message
65
5
22,992
public static void printWarn ( Object caller , Object message ) { StringBuilder text = new StringBuilder ( ) ; Class < ? > c = callerBuilder ( caller , text ) ; if ( message instanceof Throwable ) getLog ( c ) . warn ( text . append ( stackTrace ( ( Throwable ) message ) ) ) ; else getLog ( c ) . warn ( text . append ( message ) ) ; }
Print a warning level message . The stack trace will be printed if the given message is an exception .
89
20
22,993
public static void printWarn ( Object message ) { if ( message instanceof Throwable ) { Throwable e = ( Throwable ) message ; getLog ( Debugger . class ) . warn ( stackTrace ( e ) ) ; } else getLog ( Debugger . class ) . warn ( message ) ; }
Print A WARN message . The stack trace will be printed if the given message is an exception .
66
19
22,994
public void registerMemoryNotifications ( NotificationListener notificationListener , Object handback ) { NotificationEmitter emitter = ( NotificationEmitter ) this . getMemory ( ) ; emitter . addNotificationListener ( notificationListener , null , handback ) ; }
Allows a listener to be registered within the MemoryMXBean as a notification listener usage threshold exceeded notification - for notifying that the memory usage of a memory pool is increased and has reached or exceeded its usage threshold value .
53
44
22,995
public ProcessInfo execute ( boolean background , String ... command ) { ProcessBuilder pb = new ProcessBuilder ( command ) ; return executeProcess ( background , pb ) ; }
Executes a giving shell command
36
6
22,996
private ProcessInfo executeProcess ( boolean background , ProcessBuilder pb ) { try { pb . directory ( workingDirectory ) ; pb . redirectErrorStream ( false ) ; if ( log != null ) pb . redirectOutput ( Redirect . appendTo ( log ) ) ; pb . environment ( ) . putAll ( envMap ) ; Process p = pb . start ( ) ; String out = null ; String error = null ; if ( background ) { out = IO . readText ( p . getInputStream ( ) , true , defaultBackgroundReadSize ) ; error = IO . readText ( p . getErrorStream ( ) , true , 20 ) ; } else { out = IO . readText ( p . getInputStream ( ) , true ) ; error = IO . readText ( p . getErrorStream ( ) , true ) ; } if ( background ) return new ProcessInfo ( 0 , out , error ) ; return new ProcessInfo ( p . waitFor ( ) , out , error ) ; } catch ( Exception e ) { return new ProcessInfo ( - 1 , null , Debugger . stackTrace ( e ) ) ; } }
Executes a process
243
4
22,997
public static void main ( String [ ] args ) { if ( args . length != 4 ) { System . err . println ( "Usage java " + SumStatsByMillisecondsFormular . class . getName ( ) + " file msSecColumn calculateCol sumByMillisec" ) ; System . exit ( - 1 ) ; } File file = Paths . get ( args [ 0 ] ) . toFile ( ) ; try { if ( ! file . exists ( ) ) { throw new FileNotFoundException ( file . getAbsolutePath ( ) ) ; } int timeMsIndex = Integer . parseInt ( args [ 1 ] ) ; int calculateColumn = Integer . parseInt ( args [ 2 ] ) ; long milliseconds = Long . parseLong ( args [ 3 ] ) ; SumStatsByMillisecondsFormular formular = new SumStatsByMillisecondsFormular ( timeMsIndex , calculateColumn , milliseconds ) ; new CsvReader ( file ) . calc ( formular ) ; System . out . println ( formular ) ; } catch ( NumberFormatException e ) { System . err . println ( "Checks timeMsIndex:" + args [ 1 ] + ",calculateColumn:" + args [ 2 ] + " and milliseconds:" + args [ 3 ] + " are valids numbers error:" + e ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }
Usages file msSecColumn calculateCol sumByMillisec
318
12
22,998
public static String decorateEncryption ( char [ ] password ) { if ( password == null || password . length == 0 ) return null ; return new StringBuilder ( ENCRYPTED_PASSWORD_PREFIX ) . append ( encrypt ( password ) ) . append ( ENCRYPTED_PASSWORD_SUFFIX ) . toString ( ) ; }
Surround encrypted password with a prefix and suffix to indicate it has been encrypted
80
15
22,999
public static char [ ] decrypt ( char [ ] password ) { if ( password == null || password . length == 0 ) return null ; String passwordString = String . valueOf ( password ) ; try { byte [ ] decrypted = null ; if ( passwordString . startsWith ( "encrypted(" ) && passwordString . endsWith ( ")" ) ) { passwordString = passwordString . substring ( 10 , passwordString . length ( ) - 1 ) ; } SecretKeySpec key = new SecretKeySpec ( init , "Blowfish" ) ; Cipher cipher = Cipher . getInstance ( CIPHER_INSTANCE ) ; cipher . init ( Cipher . DECRYPT_MODE , key ) ; decrypted = cipher . doFinal ( hexStringToByteArray ( passwordString ) ) ; return new String ( decrypted , Charset . forName ( "UTF8" ) ) . toCharArray ( ) ; } catch ( Exception e ) { throw new SecurityException ( "Unable to decrypt password. Check that the password has been encrypted." , e ) ; } }
decrypt an encrypted password string .
225
7