idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
5,000
|
private void setNodeDirty ( final Node < K , V > node ) { final int nodeid = node . id ; final int index = nodeid < 0 ? - nodeid : nodeid ; ( node . isLeaf ( ) ? dirtyLeafNodes : dirtyInternalNodes ) . put ( nodeid , node ) ; ( node . isLeaf ( ) ? cacheLeafNodes : cacheInternalNodes ) . remove ( nodeid ) ; if ( enableIOStats ) { getIOStat ( nodeid ) . incCacheWrite ( ) ; } if ( enableDirtyCheck ) { dirtyCheck . set ( index ) ; } }
|
Put a node in dirty cache
|
5,001
|
private IOStat getIOStat ( final int nodeid ) { IOStat io = iostats . get ( nodeid ) ; if ( io == null ) { io = new IOStat ( nodeid ) ; iostats . put ( nodeid , io ) ; } return io ; }
|
Return or Create if not exist an IOStat object for a nodeid
|
5,002
|
public void dumpStats ( final String file ) throws FileNotFoundException { PrintStream out = null ; try { out = new PrintStream ( new FileOutputStream ( file ) ) ; dumpStats ( out ) ; } finally { try { out . close ( ) ; } catch ( Exception ign ) { } } }
|
Dump IOStats of tree to a file
|
5,003
|
public PropsReplacer replaceProps ( String pattern , Properties properties ) { List < String > replaced = new ArrayList < > ( ) ; for ( String path : paths ) { replaced . add ( replaceProps ( pattern , path , properties ) ) ; } setPaths ( replaced ) ; return this ; }
|
Fluent - api method . Replace properties in each path from paths field using pattern . Change paths filed value
|
5,004
|
private String replaceProps ( String pattern , String path , Properties properties ) { Matcher matcher = Pattern . compile ( pattern ) . matcher ( path ) ; String replaced = path ; while ( matcher . find ( ) ) { replaced = replaced . replace ( matcher . group ( 0 ) , properties . getProperty ( matcher . group ( 1 ) , "" ) ) ; } return replaced ; }
|
Replace properties in given path using pattern
|
5,005
|
public < T > T populate ( String prefix , Class < T > clazz , Set < Class > resolvedConfigs ) { checkConfigurationClass ( clazz ) ; Map < Method , PropertyInfo > properties = resolve ( prefix , clazz . getMethods ( ) , resolvedConfigs ) ; return ( T ) Proxy . newProxyInstance ( classLoader , new Class [ ] { clazz } , new PropertiesProxy ( properties ) ) ; }
|
Creates a proxy instance of given configuration .
|
5,006
|
protected void setValueToField ( Field field , Object bean , Object value ) { try { field . setAccessible ( true ) ; field . set ( bean , value ) ; } catch ( Exception e ) { throw new PropertyLoaderException ( String . format ( "Can not set bean <%s> field <%s> value" , bean , field ) , e ) ; } }
|
Set given value to specified field of given object .
|
5,007
|
private < T extends AnnotatedElement > Map < T , PropertyInfo > resolveProperty ( String keyPrefix , T element ) { Map < T , PropertyInfo > result = new HashMap < > ( ) ; if ( ! shouldDecorate ( element ) ) { return result ; } String key = getKey ( keyPrefix , element ) ; String defaultValue = getPropertyDefaultValue ( element ) ; String stringValue = compiled . getProperty ( key , defaultValue ) ; if ( stringValue == null ) { checkRequired ( key , element ) ; return result ; } Object value = convertValue ( element , stringValue ) ; result . put ( element , new PropertyInfo ( key , stringValue , value ) ) ; return result ; }
|
Resolve the property for given element .
|
5,008
|
private < T extends AnnotatedElement > Map < T , PropertyInfo > resolveConfig ( String keyPrefix , T element , Set < Class > resolvedConfigs ) { Map < T , PropertyInfo > result = new HashMap < > ( ) ; if ( ! element . isAnnotationPresent ( Config . class ) ) { return result ; } String prefix = concat ( keyPrefix , element . getAnnotation ( Config . class ) . prefix ( ) ) ; Class < ? > returnType = getValueType ( element ) ; checkRecursiveConfigs ( resolvedConfigs , returnType ) ; resolvedConfigs . add ( returnType ) ; Object proxy = populate ( prefix , returnType , resolvedConfigs ) ; result . put ( element , new PropertyInfo ( proxy ) ) ; return result ; }
|
Resolve the config for given element .
|
5,009
|
private void checkRecursiveConfigs ( Set < Class > resolvedConfigs , Class < ? > configClass ) { if ( resolvedConfigs . contains ( configClass ) ) { throw new PropertyLoaderException ( String . format ( "Recursive configuration <%s>" , configClass ) ) ; } }
|
Throws an exception if already meet the config .
|
5,010
|
protected void checkRequired ( String key , AnnotatedElement element ) { if ( isRequired ( element ) ) { throw new PropertyLoaderException ( String . format ( "Required property <%s> doesn't exists" , key ) ) ; } }
|
Throws an exception if given element is required .
|
5,011
|
protected String concat ( String first , String second ) { return first == null ? second : String . format ( "%s.%s" , first , second ) ; }
|
Concat the given prefixes into one .
|
5,012
|
public < T > PropertyLoader register ( Converter < T > converter , Class < T > type ) { manager . register ( type , converter ) ; return this ; }
|
Register custom converter for given type .
|
5,013
|
public final static String byteArrayAsHex ( final byte [ ] buf , final int limit ) { final StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < limit ; ++ i ) { if ( ( i % 16 ) == 0 ) { sb . append ( nativeAsHex ( i , 32 ) ) . append ( " " ) ; } else if ( ( ( i ) % 8 ) == 0 ) { sb . append ( " " ) ; } sb . append ( nativeAsHex ( ( buf [ i ] & 0xFF ) , 8 ) ) . append ( " " ) ; if ( ( ( i % 16 ) == 15 ) || ( i == ( buf . length - 1 ) ) ) { for ( int j = ( 16 - ( i % 16 ) ) ; j > 1 ; j -- ) { sb . append ( " " ) ; } sb . append ( " |" ) ; final int start = ( ( i / 16 ) * 16 ) ; final int end = ( ( buf . length < i + 1 ) ? buf . length : ( i + 1 ) ) ; for ( int j = start ; j < end ; ++ j ) { if ( ( buf [ j ] >= 32 ) && ( buf [ j ] <= 126 ) ) { sb . append ( ( char ) buf [ j ] ) ; } else { sb . append ( "." ) ; } } sb . append ( "|\n" ) ; } } return sb . toString ( ) ; }
|
Return hexdump of byte - array
|
5,014
|
public void clear ( final boolean shrink ) { while ( queue . poll ( ) != null ) { ; } if ( elementCount > 0 ) { elementCount = 0 ; } if ( shrink && ( elementData . length > 1024 ) && ( elementData . length > defaultSize ) ) { elementData = newElementArray ( defaultSize ) ; } else { Arrays . fill ( elementData , null ) ; } computeMaxSize ( ) ; while ( queue . poll ( ) != null ) { ; } }
|
Clear the set
|
5,015
|
public T get ( final T value ) { expungeStaleEntries ( ) ; final int index = ( value . hashCode ( ) & 0x7FFFFFFF ) % elementData . length ; Entry < T > m = elementData [ index ] ; while ( m != null ) { if ( eq ( value , m . get ( ) ) ) { return m . get ( ) ; } m = m . nextInSlot ; } return null ; }
|
Returns the specified value .
|
5,016
|
public T put ( final T value ) { expungeStaleEntries ( ) ; final int hash = value . hashCode ( ) ; int index = ( hash & 0x7FFFFFFF ) % elementData . length ; Entry < T > entry = elementData [ index ] ; while ( entry != null && ! eq ( value , entry . get ( ) ) ) { entry = entry . nextInSlot ; } if ( entry == null ) { if ( ++ elementCount > threshold ) { expandElementArray ( elementData . length ) ; index = ( hash & 0x7FFFFFFF ) % elementData . length ; } entry = createHashedEntry ( value , index ) ; return null ; } final T result = entry . get ( ) ; return result ; }
|
Puts the specified value in the set .
|
5,017
|
public T remove ( final T value ) { expungeStaleEntries ( ) ; final Entry < T > entry = removeEntry ( value ) ; if ( entry == null ) { return null ; } final T ret = entry . get ( ) ; return ret ; }
|
Removes the specified value from this set .
|
5,018
|
public void clear ( boolean shrink ) { if ( elementCount > 0 ) { elementCount = 0 ; } if ( shrink && ( ( elementKeys . length > 1024 ) && ( elementKeys . length > defaultSize ) ) ) { elementKeys = newKeyArray ( defaultSize ) ; elementValues = newElementArray ( defaultSize ) ; } else { Arrays . fill ( elementKeys , Integer . MIN_VALUE ) ; Arrays . fill ( elementValues , null ) ; } computeMaxSize ( ) ; }
|
Removes all mappings from this hash map leaving it empty .
|
5,019
|
private void computeMaxSize ( ) { threshold = ( int ) ( elementKeys . length * loadFactor ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( this . getClass ( ) . getName ( ) + "::computeMaxSize()=" + threshold + " collisions=" + collisions + " (" + ( collisions * 100 / elementKeys . length ) + ")" ) ; } collisions = 0 ; }
|
Returns a shallow copy of this map .
|
5,020
|
protected void createRootNode ( ) { final Node < K , V > node = createLeafNode ( ) ; node . allocId ( ) ; rootIdx = node . id ; height = 1 ; elements = 0 ; putNode ( node ) ; }
|
Create a Leaf root node and alloc nodeid for this
|
5,021
|
private int getMaxStructSize ( ) { final int leafSize = ( createLeafNode ( ) . getStructMaxSize ( ) ) ; final int internalSize = ( createInternalNode ( ) . getStructMaxSize ( ) ) ; return Math . max ( leafSize , internalSize ) ; }
|
Get the maximal size for a node
|
5,022
|
private void findOptimalNodeOrder ( final int block_size ) { final Node < K , V > leaf = createLeafNode ( ) ; final Node < K , V > internal = createInternalNode ( ) ; final int nodeSize = Math . max ( leaf . getStructEstimateSize ( MIN_B_ORDER ) , internal . getStructEstimateSize ( MIN_B_ORDER ) ) ; blockSize = ( ( nodeSize > block_size ) ? roundBlockSize ( nodeSize , block_size ) : block_size ) ; b_order_leaf = findOptimalNodeOrder ( leaf ) ; b_order_internal = findOptimalNodeOrder ( internal ) ; }
|
Calculate optimal values for b - order to fit in a block of block_size
|
5,023
|
private int findOptimalNodeOrder ( final Node < K , V > node ) { int low = MIN_B_ORDER ; int high = ( blockSize / node . getStructEstimateSize ( 1 ) ) << 2 ; while ( low <= high ) { int mid = ( ( low + high ) >>> 1 ) ; mid += ( 1 - ( mid % 2 ) ) ; int nodeSize = node . getStructEstimateSize ( mid ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( this . getClass ( ) . getName ( ) + "::findOptimalNodeOrder(" + node . getClass ( ) . getName ( ) + ") blockSize=" + blockSize + " nodeSize=" + nodeSize + " b_low=" + low + " b_order=" + mid + " b_high=" + high ) ; } if ( nodeSize < blockSize ) { low = mid + 2 ; } else if ( nodeSize > blockSize ) { high = mid - 2 ; } else { return mid ; } } return low - 2 ; }
|
Find b - order for a blockSize of this tree
|
5,024
|
private final LeafNode < K , V > findLeafNode ( final K key , final boolean tracePath ) { Node < K , V > node = getNode ( rootIdx ) ; if ( tracePath ) { stackNodes . clear ( ) ; stackSlots . clear ( ) ; } while ( ! node . isLeaf ( ) ) { final InternalNode < K , V > nodeInternal = ( InternalNode < K , V > ) node ; int slot = node . findSlotByKey ( key ) ; slot = ( ( slot < 0 ) ? ( - slot ) - 1 : slot + 1 ) ; if ( tracePath ) { stackNodes . push ( nodeInternal ) ; stackSlots . push ( slot ) ; } node = getNode ( nodeInternal . childs [ slot ] ) ; if ( node == null ) { log . error ( "ERROR childs[" + slot + "] in node=" + nodeInternal ) ; return null ; } } return ( node . isLeaf ( ) ? ( LeafNode < K , V > ) node : null ) ; }
|
Find node that can hold the key
|
5,025
|
public synchronized TreeEntry < K , V > pollFirstEntry ( ) { final TreeEntry < K , V > entry = firstEntry ( ) ; if ( entry != null ) { remove ( entry . getKey ( ) ) ; } return entry ; }
|
Removes and returns a key - value mapping associated with the least key in this map or null if the map is empty .
|
5,026
|
public synchronized TreeEntry < K , V > pollLastEntry ( ) { final TreeEntry < K , V > entry = lastEntry ( ) ; if ( entry != null ) { remove ( entry . getKey ( ) ) ; } return entry ; }
|
Removes and returns a key - value mapping associated with the greatest key in this map or null if the map is empty .
|
5,027
|
private final K getRoundKey ( final K key , final boolean upORdown , final boolean acceptEqual ) { final TreeEntry < K , V > entry = getRoundEntry ( key , upORdown , acceptEqual ) ; if ( entry == null ) { return null ; } return entry . getKey ( ) ; }
|
Return ceilingKey floorKey higherKey or lowerKey
|
5,028
|
public synchronized TreeEntry < K , V > ceilingEntry ( final K key ) { return getRoundEntry ( key , true , true ) ; }
|
Returns the least key greater than or equal to the given key or null if there is no such key .
|
5,029
|
public synchronized TreeEntry < K , V > floorEntry ( final K key ) { return getRoundEntry ( key , false , true ) ; }
|
Returns the greatest key less than or equal to the given key or null if there is no such key .
|
5,030
|
public synchronized TreeEntry < K , V > higherEntry ( final K key ) { return getRoundEntry ( key , true , false ) ; }
|
Returns the least key strictly greater than the given key or null if there is no such key .
|
5,031
|
public synchronized TreeEntry < K , V > lowerEntry ( final K key ) { return getRoundEntry ( key , false , false ) ; }
|
Returns the greatest key strictly less than the given key or null if there is no such key .
|
5,032
|
private final TreeEntry < K , V > getRoundEntry ( final K key , final boolean upORdown , final boolean acceptEqual ) { if ( ! validState ) { throw new InvalidStateException ( ) ; } if ( _isEmpty ( ) ) { return null ; } if ( key == null ) { return null ; } try { LeafNode < K , V > node = findLeafNode ( key , false ) ; if ( node == null ) { return null ; } int slot = node . findSlotByKey ( key ) ; if ( upORdown ) { slot = ( ( slot < 0 ) ? ( - slot ) - 1 : ( acceptEqual ? slot : slot + 1 ) ) ; if ( slot >= node . allocated ) { node = node . nextNode ( ) ; if ( node == null ) { return null ; } slot = 0 ; } } else { slot = ( ( slot < 0 ) ? ( - slot ) - 2 : ( acceptEqual ? slot : slot - 1 ) ) ; if ( slot < 0 ) { node = node . prevNode ( ) ; if ( node == null ) { return null ; } slot = node . allocated - 1 ; } } return ( ( node . keys [ slot ] == null ) ? null : new TreeEntry < K , V > ( node . keys [ slot ] , node . values [ slot ] ) ) ; } finally { releaseNodes ( ) ; } }
|
Return ceilingEntry floorEntry higherEntry or lowerEntry
|
5,033
|
public synchronized V get ( final K key ) { if ( ! validState ) { throw new InvalidStateException ( ) ; } if ( _isEmpty ( ) ) { return null ; } if ( key == null ) { return null ; } try { final LeafNode < K , V > node = findLeafNode ( key , false ) ; if ( node == null ) { return null ; } int slot = node . findSlotByKey ( key ) ; if ( slot >= 0 ) { return node . values [ slot ] ; } return null ; } finally { releaseNodes ( ) ; } }
|
Find a Key in the Tree
|
5,034
|
public synchronized boolean remove ( final K key ) { if ( readOnly ) { return false ; } if ( ! validState ) { throw new InvalidStateException ( ) ; } if ( key == null ) { return false ; } try { if ( log . isDebugEnabled ( ) ) { log . debug ( "trying remove key=" + key ) ; } submitRedoRemove ( key ) ; if ( removeIterative ( key ) ) { elements -- ; Node < K , V > nodeRoot = getNode ( rootIdx ) ; if ( nodeRoot . isEmpty ( ) && ( elements > 0 ) ) { rootIdx = ( ( InternalNode < K , V > ) nodeRoot ) . childs [ 0 ] ; freeNode ( nodeRoot ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "DECREASES TREE HEIGHT (ROOT): elements=" + elements + " oldRoot=" + nodeRoot . id + " newRoot=" + rootIdx ) ; } height -- ; } else if ( nodeRoot . isEmpty ( ) && nodeRoot . isLeaf ( ) && ( elements == 0 ) && ( getHighestNodeId ( ) > 4096 ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "RESET TREE: elements=" + elements + " leaf=" + nodeRoot . isLeaf ( ) + " empty=" + nodeRoot . isEmpty ( ) + " id=" + nodeRoot . id + " lastNodeId=" + getHighestNodeId ( ) + " nodeRoot=" + nodeRoot ) ; } clear ( ) ; } else if ( ( elements == 0 ) && ( ! nodeRoot . isLeaf ( ) || ! nodeRoot . isEmpty ( ) ) ) { log . error ( "ERROR in TREE: elements=" + elements + " rootLeaf=" + nodeRoot . isLeaf ( ) + " rootEmpty=" + nodeRoot . isEmpty ( ) + " rootId=" + nodeRoot . id + " nodeRoot=" + nodeRoot ) ; } return true ; } return false ; } finally { stackNodes . clear ( ) ; stackSlots . clear ( ) ; releaseNodes ( ) ; } }
|
Remove a key from key
|
5,035
|
private String toStringIterative ( ) { final String PADDING = " " ; final StringBuilder sb = new StringBuilder ( ) ; int elements_debug_local_recounter = 0 ; Node < K , V > node = null ; int nodeid = rootIdx ; int depth = 0 ; stackSlots . clear ( ) ; stackSlots . push ( rootIdx ) ; boolean lastIsInternal = ! Node . isLeaf ( rootIdx ) ; while ( ! stackSlots . isEmpty ( ) ) { nodeid = stackSlots . pop ( ) ; node = getNode ( nodeid ) ; if ( ! node . isLeaf ( ) ) { for ( int i = node . allocated ; i >= 0 ; i -- ) { stackSlots . push ( ( ( InternalNode < K , V > ) node ) . childs [ i ] ) ; } } else { elements_debug_local_recounter += node . allocated ; } if ( lastIsInternal || ! node . isLeaf ( ) ) { depth += ( lastIsInternal ? + 1 : - 1 ) ; } lastIsInternal = ! node . isLeaf ( ) ; sb . append ( PADDING . substring ( 0 , Math . min ( PADDING . length ( ) , Math . max ( depth - 1 , 0 ) ) ) ) ; sb . append ( node . toString ( ) ) . append ( "\n" ) ; } sb . append ( "height=" ) . append ( getHeight ( ) ) . append ( " root=" ) . append ( rootIdx ) . append ( " low=" ) . append ( lowIdx ) . append ( " high=" ) . append ( highIdx ) . append ( " elements=" ) . append ( elements ) . append ( " recounter=" ) . append ( elements_debug_local_recounter ) ; return sb . toString ( ) ; }
|
A iterative algorithm for converting this tree into a string
|
5,036
|
@ SuppressWarnings ( "unused" ) private String toStringRecursive ( ) { final StringBuilder sb = new StringBuilder ( ) ; int elements_debug_local_recounter = toString ( rootIdx , sb , 0 ) ; sb . append ( "height=" ) . append ( getHeight ( ) ) . append ( " root=" ) . append ( rootIdx ) . append ( " low=" ) . append ( lowIdx ) . append ( " high=" ) . append ( highIdx ) . append ( " elements=" ) . append ( elements ) . append ( " recounter=" ) . append ( elements_debug_local_recounter ) ; return sb . toString ( ) ; }
|
A recursive algorithm for converting this tree into a string
|
5,037
|
public Iterator < BplusTree . TreeEntry < K , V > > iterator ( ) { return new TreeIterator < BplusTree . TreeEntry < K , V > > ( this ) ; }
|
Note that the iterator cannot be guaranteed to be thread - safe as it is generally speaking impossible to make any hard guarantees in the presence of unsynchronized concurrent modification .
|
5,038
|
public LeafNode < K , V > prevNode ( ) { if ( leftid == NULL_ID ) { return null ; } return ( LeafNode < K , V > ) tree . getNode ( leftid ) ; }
|
Return the previous LeafNode in LinkedList
|
5,039
|
public LeafNode < K , V > nextNode ( ) { if ( rightid == NULL_ID ) { return null ; } return ( LeafNode < K , V > ) tree . getNode ( rightid ) ; }
|
Return the next LeafNode in LinkedList
|
5,040
|
public synchronized boolean isValid ( ) { if ( ! validState ) { throw new InvalidStateException ( ) ; } final long size = size ( ) ; if ( size == 0 ) { return true ; } try { final long offset = ( size - FOOTER_LEN ) ; if ( offset < 0 ) { return false ; } if ( offset >= offsetOutputCommited ) { if ( bufOutput . position ( ) > 0 ) { log . warn ( "WARN: autoflush forced" ) ; flushBuffer ( ) ; } } bufInput . clear ( ) ; bufInput . limit ( FOOTER_LEN ) ; final int readed = fcInput . position ( offset ) . read ( bufInput ) ; if ( readed < FOOTER_LEN ) { return false ; } bufInput . flip ( ) ; final int footer = bufInput . get ( ) ; if ( footer != MAGIC_FOOT ) { log . error ( "MAGIC FOOT fake=" + Integer . toHexString ( footer ) + " expected=" + Integer . toHexString ( MAGIC_FOOT ) ) ; return false ; } return true ; } catch ( Exception e ) { log . error ( "Exception in isValid()" , e ) ; } return false ; }
|
Read end of valid and check last magic footer
|
5,041
|
public synchronized long readFromEnd ( final long datalen , final ByteBuffer buf ) { if ( ! validState ) { throw new InvalidStateException ( ) ; } final long size = size ( ) ; final long offset = ( size - HEADER_LEN - datalen - FOOTER_LEN ) ; return read ( offset , buf ) ; }
|
Read desired block of datalen from end of file
|
5,042
|
private final void alignBuffer ( final int diff ) throws IOException { if ( bufOutput . remaining ( ) < diff ) { flushBuffer ( ) ; } bufOutput . put ( MAGIC_PADDING ) ; int i = 1 ; for ( ; i + 8 <= diff ; i += 8 ) { bufOutput . putLong ( 0L ) ; } for ( ; i + 4 <= diff ; i += 4 ) { bufOutput . putInt ( 0 ) ; } switch ( diff - i ) { case 3 : bufOutput . put ( ( byte ) 0 ) ; case 2 : bufOutput . putShort ( ( short ) 0 ) ; break ; case 1 : bufOutput . put ( ( byte ) 0 ) ; } }
|
Pad output buffer with NULL to complete alignment
|
5,043
|
public synchronized boolean flush ( ) { if ( ! validState ) { throw new InvalidStateException ( ) ; } try { flushBuffer ( ) ; return true ; } catch ( Exception e ) { log . error ( "Exception in flush()" , e ) ; } return false ; }
|
Flush buffer to file
|
5,044
|
private final void flushBuffer ( ) throws IOException { if ( bufOutput . position ( ) > 0 ) { bufOutput . flip ( ) ; fcOutput . write ( bufOutput ) ; bufOutput . clear ( ) ; offsetOutputUncommited = offsetOutputCommited = fcOutput . position ( ) ; if ( syncOnFlush ) { fcOutput . force ( false ) ; if ( callback != null ) { callback . synched ( offsetOutputCommited ) ; } } } }
|
Write uncommited data to disk
|
5,045
|
private final boolean checkUnderflowWithRight ( final int slot ) { final Node < K , V > nodeLeft = tree . getNode ( childs [ slot ] ) ; if ( nodeLeft . isUnderFlow ( ) ) { final Node < K , V > nodeRight = tree . getNode ( childs [ slot + 1 ] ) ; if ( nodeLeft . canMerge ( nodeRight ) ) { nodeLeft . merge ( this , slot , nodeRight ) ; childs [ slot ] = nodeLeft . id ; } else { nodeLeft . shiftRL ( this , slot , nodeRight ) ; } tree . putNode ( this ) ; tree . putNode ( nodeRight ) ; tree . putNode ( nodeLeft ) ; return true ; } return false ; }
|
Check if underflow ocurred in child of slot
|
5,046
|
public static DatagramPacket getDatagram ( String serviceType ) { StringBuilder sb = new StringBuilder ( "M-SEARCH * HTTP/1.1\r\n" ) ; sb . append ( "HOST: " + SsdpParams . getSsdpMulticastAddress ( ) . getHostAddress ( ) + ":" + SsdpParams . getSsdpMulticastPort ( ) + "\r\n" ) ; sb . append ( "MAN: \"ssdp:discover\"\r\n" ) ; sb . append ( "MX: 3\r\n" ) ; sb . append ( "USER-AGENT: Resourcepool SSDP Client\r\n" ) ; sb . append ( serviceType == null ? "ST: ssdp:all\r\n" : "ST: " + serviceType + "\r\n\r\n" ) ; byte [ ] content = sb . toString ( ) . getBytes ( UTF_8 ) ; return new DatagramPacket ( content , content . length , SsdpParams . getSsdpMulticastAddress ( ) , SsdpParams . getSsdpMulticastPort ( ) ) ; }
|
Get Datagram from serviceType .
|
5,047
|
public static void selectAppropriateInterface ( MulticastSocket socket ) throws SocketException { Enumeration e = NetworkInterface . getNetworkInterfaces ( ) ; while ( e . hasMoreElements ( ) ) { NetworkInterface n = ( NetworkInterface ) e . nextElement ( ) ; Enumeration ee = n . getInetAddresses ( ) ; while ( ee . hasMoreElements ( ) ) { InetAddress i = ( InetAddress ) ee . nextElement ( ) ; if ( i . isSiteLocalAddress ( ) && ! i . isAnyLocalAddress ( ) && ! i . isLinkLocalAddress ( ) && ! i . isLoopbackAddress ( ) && ! i . isMulticastAddress ( ) ) { socket . setNetworkInterface ( NetworkInterface . getByName ( n . getName ( ) ) ) ; } } } }
|
Selects the appropriate interface to use Multicast . This prevents computers with multiple interfaces to select the wrong one by default .
|
5,048
|
public static SsdpResponse parse ( DatagramPacket packet ) { Map < String , String > headers = new HashMap < String , String > ( ) ; byte [ ] body = null ; SsdpResponse . Type type = null ; byte [ ] data = packet . getData ( ) ; int endOfHeaders = findEndOfHeaders ( data ) ; if ( endOfHeaders == - 1 ) { endOfHeaders = packet . getLength ( ) ; } String [ ] headerLines = new String ( Arrays . copyOfRange ( data , 0 , endOfHeaders ) ) . split ( "\r\n" ) ; if ( SEARCH_REQUEST_LINE_PATTERN . matcher ( headerLines [ 0 ] ) . matches ( ) ) { type = SsdpResponse . Type . DISCOVERY_RESPONSE ; } else if ( SERVICE_ANNOUNCEMENT_LINE_PATTERN . matcher ( headerLines [ 0 ] ) . matches ( ) ) { type = SsdpResponse . Type . PRESENCE_ANNOUNCEMENT ; } if ( type == null ) { return null ; } for ( int i = 1 ; i < headerLines . length ; i ++ ) { String line = headerLines [ i ] ; Matcher matcher = HEADER_PATTERN . matcher ( line ) ; if ( matcher . matches ( ) ) { headers . put ( matcher . group ( 1 ) . toUpperCase ( ) . trim ( ) , matcher . group ( 2 ) . trim ( ) ) ; } } long expiry = parseCacheHeader ( headers ) ; int endOfBody = packet . getLength ( ) ; if ( endOfBody > endOfHeaders + 4 ) { body = Arrays . copyOfRange ( data , endOfHeaders + 4 , endOfBody ) ; } return new SsdpResponse ( type , headers , body , expiry , packet . getAddress ( ) ) ; }
|
Parse incoming Datagram into SsdpResponse .
|
5,049
|
private static long parseCacheHeader ( Map < String , String > headers ) { if ( headers . get ( "CACHE-CONTROL" ) != null ) { String cacheControlHeader = headers . get ( "CACHE-CONTROL" ) ; Matcher m = CACHE_CONTROL_PATTERN . matcher ( cacheControlHeader ) ; if ( m . matches ( ) ) { return new Date ( ) . getTime ( ) + Long . parseLong ( m . group ( 1 ) ) * 1000L ; } } if ( headers . get ( "EXPIRES" ) != null ) { try { return DATE_HEADER_FORMAT . parse ( headers . get ( "EXPIRES" ) ) . getTime ( ) ; } catch ( ParseException e ) { } } return 0 ; }
|
Parse both Cache - Control and Expires headers to determine if there is any caching strategy requested by service .
|
5,050
|
private static int findEndOfHeaders ( byte [ ] data ) { for ( int i = 0 ; i < data . length - 3 ; i ++ ) { if ( data [ i ] != CRLF [ 0 ] || data [ i + 1 ] != CRLF [ 1 ] || data [ i + 2 ] != CRLF [ 0 ] || data [ i + 3 ] != CRLF [ 1 ] ) { continue ; } return i ; } return - 1 ; }
|
Find the index matching the end of the header data .
|
5,051
|
private void reset ( DiscoveryRequest req , DiscoveryListener callback ) { this . callback = callback ; this . state = State . ACTIVE ; this . requests = new ArrayList < DiscoveryRequest > ( ) ; if ( req != null ) { requests . add ( req ) ; } for ( Map . Entry < String , SsdpService > e : this . cache . entrySet ( ) ) { if ( e . getValue ( ) . isExpired ( ) ) { this . cache . remove ( e . getKey ( ) ) ; } else { callback . onServiceDiscovered ( e . getValue ( ) ) ; } } }
|
Reset all stateful attributes .
|
5,052
|
private void handleIncomingPacket ( DatagramPacket packet ) { SsdpResponse response = new ResponseParser ( ) . parse ( packet ) ; if ( response == null ) { return ; } if ( response . getType ( ) . equals ( SsdpResponse . Type . DISCOVERY_RESPONSE ) ) { handleDiscoveryResponse ( response ) ; } else if ( response . getType ( ) . equals ( SsdpResponse . Type . PRESENCE_ANNOUNCEMENT ) ) { handlePresenceAnnouncement ( response ) ; } }
|
Thid handler handles incoming SSDP packets .
|
5,053
|
private void sendDiscoveryRequest ( ) { try { if ( requests . isEmpty ( ) ) { return ; } for ( DiscoveryRequest req : requests ) { if ( req . getServiceTypes ( ) == null || req . getServiceTypes ( ) . isEmpty ( ) ) { clientSocket . send ( SsdpDiscovery . getDatagram ( null ) ) ; } else { for ( String st : req . getServiceTypes ( ) ) { clientSocket . send ( SsdpDiscovery . getDatagram ( st ) ) ; } } } } catch ( IOException e ) { if ( clientSocket . isClosed ( ) && ! State . ACTIVE . equals ( state ) ) { return ; } callback . onFailed ( e ) ; } }
|
Send discovery Multicast request .
|
5,054
|
private void openAndBindSocket ( ) { try { this . clientSocket = new MulticastSocket ( ) ; Utils . selectAppropriateInterface ( clientSocket ) ; this . clientSocket . joinGroup ( SsdpParams . getSsdpMulticastAddress ( ) ) ; } catch ( IOException e ) { callback . onFailed ( e ) ; } }
|
Open MulticastSocket and bind to Ssdp port .
|
5,055
|
private void handlePresenceAnnouncement ( SsdpResponse response ) { SsdpServiceAnnouncement ssdpServiceAnnouncement = response . toServiceAnnouncement ( ) ; if ( ssdpServiceAnnouncement . getSerialNumber ( ) == null ) { callback . onFailed ( new NoSerialNumberException ( ) ) ; return ; } if ( cache . containsKey ( ssdpServiceAnnouncement . getSerialNumber ( ) ) ) { callback . onServiceAnnouncement ( ssdpServiceAnnouncement ) ; } else { requests . add ( DiscoveryRequest . builder ( ) . serviceType ( ssdpServiceAnnouncement . getServiceType ( ) ) . build ( ) ) ; } }
|
Handle presence announcement Datagrams .
|
5,056
|
private void handleDiscoveryResponse ( SsdpResponse response ) { SsdpService ssdpService = response . toService ( ) ; if ( ssdpService . getSerialNumber ( ) == null ) { callback . onFailed ( new NoSerialNumberException ( ) ) ; return ; } if ( ! cache . containsKey ( ssdpService . getSerialNumber ( ) ) ) { callback . onServiceDiscovered ( ssdpService ) ; } cache . put ( ssdpService . getSerialNumber ( ) , ssdpService ) ; }
|
Handle discovery response Datagrams .
|
5,057
|
public T get ( T dest , int index ) { checkBounds ( index ) ; copier . copy ( dest , offset ( index ) ) ; return dest ; }
|
Copies the element at index into dest
|
5,058
|
public void swap ( int i , int j ) { checkBounds ( i ) ; checkBounds ( j ) ; if ( i == j ) return ; copier . copy ( tmp , offset ( i ) ) ; unsafe . copyMemory ( null , offset ( j ) , null , offset ( i ) , elementSpacing ) ; unsafe . copyMemory ( tmp , firstFieldOffset , null , offset ( j ) , elementSize ) ; }
|
Swaps two elements
|
5,059
|
public UnsafeCopier build ( Unsafe unsafe ) throws IllegalAccessException , InstantiationException , NoSuchMethodException , InvocationTargetException { checkArgument ( offset >= 0 , "Offset must be set" ) ; checkArgument ( length >= 0 , "Length must be set" ) ; checkNotNull ( unsafe ) ; Class < ? > dynamicType = new ByteBuddy ( ) . subclass ( UnsafeCopier . class ) . method ( named ( "copy" ) ) . intercept ( new CopierImplementation ( offset , length ) ) . make ( ) . load ( getClass ( ) . getClassLoader ( ) , ClassLoadingStrategy . Default . WRAPPER ) . getLoaded ( ) ; return ( UnsafeCopier ) dynamicType . getDeclaredConstructor ( Unsafe . class ) . newInstance ( unsafe ) ; }
|
Constructs a new Copier using the passed in Unsafe instance
|
5,060
|
public static < E extends Comparable < E > > void recursiveQuickSort ( List < E > array , int startIdx , int endIdx ) { int idx = partition ( array , startIdx , endIdx ) ; if ( startIdx < idx - 1 ) { recursiveQuickSort ( array , startIdx , idx - 1 ) ; } if ( endIdx > idx ) { recursiveQuickSort ( array , idx , endIdx ) ; } }
|
Recursive quicksort logic .
|
5,061
|
public static void printMemoryLayout2 ( ) { Object o1 = new Object ( ) ; Object o2 = new Object ( ) ; Byte b1 = new Byte ( ( byte ) 0x12 ) ; Byte b2 = new Byte ( ( byte ) 0x34 ) ; Byte b3 = new Byte ( ( byte ) 0x56 ) ; Long l = new Long ( 0x0123456789ABCDEFL ) ; Person p = new Person ( "Bob" , 406425600000L , 'M' ) ; System . out . printf ( "Object len:%d header:%d\n" , UnsafeHelper . sizeOf ( o1 ) , UnsafeHelper . headerSize ( o1 ) ) ; UnsafeHelper . hexDump ( System . out , o1 ) ; UnsafeHelper . hexDump ( System . out , o2 ) ; System . out . printf ( "Byte len:%d header:%d\n" , UnsafeHelper . sizeOf ( b1 ) , UnsafeHelper . headerSize ( b1 ) ) ; UnsafeHelper . hexDump ( System . out , b1 ) ; UnsafeHelper . hexDump ( System . out , b2 ) ; UnsafeHelper . hexDump ( System . out , b3 ) ; Byte [ ] bArray0 = new Byte [ ] { } ; Byte [ ] bArray1 = new Byte [ ] { b1 } ; Byte [ ] bArray2 = new Byte [ ] { b1 , b2 } ; Byte [ ] bArray3 = new Byte [ ] { b1 , b2 , b3 } ; System . out . printf ( "Byte[0] len:%d header:%d\n" , UnsafeHelper . sizeOf ( bArray0 ) , UnsafeHelper . headerSize ( bArray0 ) ) ; UnsafeHelper . hexDump ( System . out , bArray0 ) ; System . out . printf ( "Byte[1] len:%d header:%d\n" , UnsafeHelper . sizeOf ( bArray1 ) , UnsafeHelper . headerSize ( bArray1 ) ) ; UnsafeHelper . hexDump ( System . out , bArray1 ) ; System . out . printf ( "Byte[2] len:%d header:%d\n" , UnsafeHelper . sizeOf ( bArray2 ) , UnsafeHelper . headerSize ( bArray2 ) ) ; UnsafeHelper . hexDump ( System . out , bArray2 ) ; System . out . printf ( "Byte[3] len:%d header:%d\n" , UnsafeHelper . sizeOf ( bArray3 ) , UnsafeHelper . headerSize ( bArray3 ) ) ; UnsafeHelper . hexDump ( System . out , bArray3 ) ; System . out . printf ( "Long len:%d header:%d\n" , UnsafeHelper . sizeOf ( l ) , UnsafeHelper . headerSize ( l ) ) ; UnsafeHelper . hexDump ( System . out , l ) ; System . out . printf ( "Person len:%d header:%d\n" , UnsafeHelper . sizeOf ( p ) , UnsafeHelper . headerSize ( p ) ) ; UnsafeHelper . hexDump ( System . out , p ) ; }
|
Prints the memory layout of various test classes .
|
5,062
|
@ Setup ( Level . Trial ) public void setup ( ) throws Exception { test = benchmarks . get ( list + "-" + type ) ; if ( test == null ) { throw new RuntimeException ( "Can't find requested test " + list + " " + type ) ; } test . setSize ( size ) ; test . setRandomSeed ( size ) ; test . setup ( ) ; }
|
Sets up the benchmark .
|
5,063
|
public static void main ( String [ ] args ) throws RunnerException { for ( String benchmark : benchmarks . keySet ( ) ) { String [ ] parts = benchmark . split ( "-" ) ; Options opt = new OptionsBuilder ( ) . include ( ArrayListBenchmark . class . getSimpleName ( ) ) . warmupIterations ( 2 ) . measurementIterations ( 5 ) . mode ( Mode . AverageTime ) . warmupTime ( TimeValue . seconds ( 10 ) ) . measurementTime ( TimeValue . seconds ( 60 ) ) . param ( "size" , "80000000" , "20000000" , "5000000" ) . param ( "list" , parts [ 0 ] ) . param ( "type" , parts [ 1 ] ) . forks ( 1 ) . jvmArgs ( "-Xmx16g" ) . build ( ) ; new Runner ( opt ) . run ( ) ; } }
|
Runs the ArrayListBenchmarks .
|
5,064
|
public static String memoryUsage ( ) { final Runtime runtime = Runtime . getRuntime ( ) ; runtime . gc ( ) ; final long max = runtime . maxMemory ( ) ; final long total = runtime . totalMemory ( ) ; final long free = runtime . freeMemory ( ) ; final long used = total - free ; return String . format ( "%d\t%d\t%d\t%d" , max , total , free , used ) ; }
|
Calculates the memory usage according to Runtime .
|
5,065
|
public static int getPid ( ) throws NoSuchFieldException , IllegalAccessException , NoSuchMethodException , InvocationTargetException { RuntimeMXBean runtime = ManagementFactory . getRuntimeMXBean ( ) ; Field jvm = runtime . getClass ( ) . getDeclaredField ( "jvm" ) ; jvm . setAccessible ( true ) ; VMManagement mgmt = ( VMManagement ) jvm . get ( runtime ) ; Method getProcessId = mgmt . getClass ( ) . getDeclaredMethod ( "getProcessId" ) ; getProcessId . setAccessible ( true ) ; return ( Integer ) getProcessId . invoke ( mgmt ) ; }
|
Returns the pid of the current process . This fails on systems without process identifiers .
|
5,066
|
public static String pidMemoryUsage ( int pid ) throws IOException { Process process = new ProcessBuilder ( ) . command ( "ps" , "-o" , "pid,rss,vsz" , "-p" , Long . toString ( pid ) ) . start ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( process . getInputStream ( ) ) ) ; reader . readLine ( ) ; String line = reader . readLine ( ) ; String [ ] parts = line . trim ( ) . split ( "\\s+" , 3 ) ; int readPid = Integer . parseInt ( parts [ 0 ] ) ; if ( pid != readPid ) { throw new RuntimeException ( "`ps` returned something unexpected: '" + line + "'" ) ; } long rss = Long . parseLong ( parts [ 1 ] ) * 1024 ; long vsz = Long . parseLong ( parts [ 2 ] ) ; return String . format ( "%d\t%d" , rss , vsz ) ; }
|
Calculates the memory usage according to ps for a given pid .
|
5,067
|
public static long toAddress ( Object obj ) { Object [ ] array = new Object [ ] { obj } ; long baseOffset = unsafe . arrayBaseOffset ( Object [ ] . class ) ; return normalize ( unsafe . getInt ( array , baseOffset ) ) ; }
|
Returns the address the object is located at
|
5,068
|
public static void copyMemory ( final Object src , long srcOffset , final Object dest , final long destOffset , final long len ) { Preconditions . checkNotNull ( src ) ; Preconditions . checkArgument ( len % COPY_STRIDE != 0 , "Length (%d) is not a multiple of stride" , len ) ; Preconditions . checkArgument ( destOffset % COPY_STRIDE != 0 , "Dest offset (%d) is not stride aligned" , destOffset ) ; long end = destOffset + len ; for ( long offset = destOffset ; offset < end ; ) { unsafe . putLong ( dest , offset , unsafe . getLong ( srcOffset ) ) ; offset += COPY_STRIDE ; srcOffset += COPY_STRIDE ; } }
|
Copies the memory from srcAddress into dest
|
5,069
|
public static void copyMemoryFieldByField ( long srcAddress , Object dest ) { Class clazz = dest . getClass ( ) ; while ( clazz != Object . class ) { for ( Field f : clazz . getDeclaredFields ( ) ) { if ( ( f . getModifiers ( ) & Modifier . STATIC ) == 0 ) { final Class type = f . getType ( ) ; Preconditions . checkArgument ( type . isPrimitive ( ) , "Only primitives are supported" ) ; final long offset = unsafe . objectFieldOffset ( f ) ; final long src = srcAddress + offset ; if ( type == int . class ) { unsafe . putInt ( dest , offset , unsafe . getInt ( src ) ) ; } else if ( type == long . class ) { unsafe . putLong ( dest , offset , unsafe . getLong ( src ) ) ; } else { throw new IllegalArgumentException ( "Type not supported yet: " + type ) ; } } } clazz = clazz . getSuperclass ( ) ; } }
|
Copies from srcAddress to dest one field at a time .
|
5,070
|
public static byte [ ] toByteArray ( Object obj ) { int len = ( int ) sizeOf ( obj ) ; byte [ ] bytes = new byte [ len ] ; unsafe . copyMemory ( obj , 0 , bytes , Unsafe . ARRAY_BYTE_BASE_OFFSET , bytes . length ) ; return bytes ; }
|
Returns the object as a byte array including header padding and all fields .
|
5,071
|
private static byte [ ] stringToByteArray ( String str ) { byte [ ] result = new byte [ str . length ( ) + 1 ] ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { result [ i ] = ( byte ) str . charAt ( i ) ; } result [ str . length ( ) ] = 0 ; return result ; }
|
Returns this java string as a null - terminated byte array
|
5,072
|
public void createKey ( HKey hk , String key ) throws RegistryException { int [ ] ret ; try { ret = ReflectedMethods . createKey ( hk . root ( ) , hk . hex ( ) , key ) ; } catch ( Exception e ) { throw new RegistryException ( "Cannot create key " + key , e ) ; } if ( ret . length == 0 ) { throw new RegistryException ( "Cannot create key " + key + ". Zero return length" ) ; } if ( ret [ 1 ] != RC . SUCCESS ) { throw new RegistryException ( "Cannot create key " + key + ". Return code is " + ret [ 1 ] ) ; } }
|
Create key in registry .
|
5,073
|
public void deleteKey ( HKey hk , String key ) throws RegistryException { int rc = - 1 ; try { rc = ReflectedMethods . deleteKey ( hk . root ( ) , hk . hex ( ) , key ) ; } catch ( Exception e ) { throw new RegistryException ( "Cannot delete key " + key , e ) ; } if ( rc != RC . SUCCESS ) { throw new RegistryException ( "Cannot delete key " + key + ". Return code is " + rc ) ; } }
|
Delete given key from registry .
|
5,074
|
public void close ( ) { File tmp = new File ( webpTmpDir ) ; if ( tmp . exists ( ) && tmp . isDirectory ( ) ) { File [ ] files = tmp . listFiles ( ) ; for ( File file : Objects . requireNonNull ( files ) ) { file . delete ( ) ; } tmp . delete ( ) ; } }
|
delete temp dir and commands
|
5,075
|
private String getOsName ( ) { if ( OS_NAME . contains ( "win" ) ) { boolean is64bit = ( System . getenv ( "ProgramFiles(x86)" ) != null ) ; return "windows_" + ( is64bit ? "x86_64" : "x86" ) ; } else if ( OS_NAME . contains ( "mac" ) ) { return "mac_" + OS_ARCH ; } else if ( OS_NAME . contains ( "nix" ) || OS_NAME . contains ( "nux" ) || OS_NAME . indexOf ( "aix" ) > 0 ) { return "amd64" . equalsIgnoreCase ( OS_ARCH ) ? "linux_x86_64" : "linux_" + OS_ARCH ; } else { throw new WebpIOException ( "Hi boy, Your OS is not support!!" ) ; } }
|
get os name and arch
|
5,076
|
private String getExtensionByOs ( String os ) { if ( os == null || os . isEmpty ( ) ) return "" ; else if ( os . contains ( "win" ) ) return ".exe" ; return "" ; }
|
Return the Os specific extension
|
5,077
|
public List < Tag > getInstanceTags ( ) { final DescribeInstancesResult response = ec2 . describeInstances ( new DescribeInstancesRequest ( ) . withInstanceIds ( Collections . singletonList ( instanceIdentity . instanceId ) ) ) ; return response . getReservations ( ) . stream ( ) . flatMap ( reservation -> reservation . getInstances ( ) . stream ( ) ) . flatMap ( instance -> instance . getTags ( ) . stream ( ) ) . collect ( Collectors . toList ( ) ) ; }
|
Returns all of the tags defined on the EC2 current instance instanceId .
|
5,078
|
public TagsUtils validateTags ( ) { final List < String > instanceTags = getInstanceTags ( ) . stream ( ) . map ( Tag :: getKey ) . collect ( Collectors . toList ( ) ) ; final List < String > missingTags = getAwsTagNames ( ) . map ( List :: stream ) . orElse ( Stream . empty ( ) ) . filter ( configuredTag -> ! instanceTags . contains ( configuredTag ) ) . collect ( Collectors . toList ( ) ) ; if ( ! missingTags . isEmpty ( ) ) { throw new IllegalStateException ( "expected instance tag(s) missing: " + missingTags . stream ( ) . collect ( Collectors . joining ( ", " ) ) ) ; } return this ; }
|
Configured tags will be validated against the instance tags . If one or more tags are missing on the instance an exception will be thrown .
|
5,079
|
private static List < String > parseTagNames ( String tagNames ) { return Arrays . stream ( tagNames . split ( "\\s*,\\s*" ) ) . map ( String :: trim ) . collect ( Collectors . toList ( ) ) ; }
|
Parses a comma separated list of tag names .
|
5,080
|
private static String getIdentityDocument ( final HttpClient client ) throws IOException { try { final HttpGet getInstance = new HttpGet ( ) ; getInstance . setURI ( INSTANCE_IDENTITY_URI ) ; final HttpResponse response = client . execute ( getInstance ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) != HttpStatus . SC_OK ) { throw new IOException ( "failed to get instance identity, tried: " + INSTANCE_IDENTITY_URL + ", response: " + response . getStatusLine ( ) . getReasonPhrase ( ) ) ; } return EntityUtils . toString ( response . getEntity ( ) ) ; } catch ( Exception e ) { throw new IOException ( "failed to get instance identity" , e ) ; } }
|
Gets the body of the content returned from a GET request to uri .
|
5,081
|
private static void setupAWSExceptionLogging ( AmazonEC2 ec2 ) { boolean accessible = false ; Field exceptionUnmarshallersField = null ; try { exceptionUnmarshallersField = AmazonEC2Client . class . getDeclaredField ( "exceptionUnmarshallers" ) ; accessible = exceptionUnmarshallersField . isAccessible ( ) ; exceptionUnmarshallersField . setAccessible ( true ) ; @ SuppressWarnings ( "unchecked" ) final List < Unmarshaller < AmazonServiceException , Node > > exceptionUnmarshallers = ( List < Unmarshaller < AmazonServiceException , Node > > ) exceptionUnmarshallersField . get ( ec2 ) ; exceptionUnmarshallers . add ( 0 , new AWSFaultLogger ( ) ) ; ( ( AmazonEC2Client ) ec2 ) . addRequestHandler ( ( RequestHandler ) exceptionUnmarshallers . get ( 0 ) ) ; } catch ( Throwable t ) { } finally { if ( exceptionUnmarshallersField != null ) { try { exceptionUnmarshallersField . setAccessible ( accessible ) ; } catch ( SecurityException se ) { } } } }
|
Sets up the AmazonEC2Client to log soap faults from the AWS EC2 api server .
|
5,082
|
public static boolean isValid ( String kidnummer ) { try { KidnummerValidator . getKidnummer ( kidnummer ) ; return true ; } catch ( IllegalArgumentException e ) { return false ; } }
|
Return true if the provided String is a valid KID - nummmer .
|
5,083
|
public static Kidnummer getKidnummer ( String kidnummer ) throws IllegalArgumentException { validateSyntax ( kidnummer ) ; validateChecksum ( kidnummer ) ; return new Kidnummer ( kidnummer ) ; }
|
Returns an object that represents a Kidnummer .
|
5,084
|
public static List < Organisasjonsnummer > getOrganisasjonsnummerList ( int length ) { List < Organisasjonsnummer > result = new ArrayList < Organisasjonsnummer > ( ) ; int numAddedToList = 0 ; while ( numAddedToList < length ) { StringBuilder orgnrBuffer = new StringBuilder ( LENGTH ) ; for ( int i = 0 ; i < LENGTH ; i ++ ) { orgnrBuffer . append ( ( int ) ( Math . random ( ) * 10 ) ) ; } Organisasjonsnummer orgNr ; try { orgNr = OrganisasjonsnummerValidator . getAndForceValidOrganisasjonsnummer ( orgnrBuffer . toString ( ) ) ; } catch ( IllegalArgumentException iae ) { continue ; } result . add ( orgNr ) ; numAddedToList ++ ; } return result ; }
|
Returns a List with completely random but syntactically valid Organisasjonsnummer instances .
|
5,085
|
public static void main ( String [ ] args ) throws Exception { GeoParser parser = GeoParserFactory . getDefault ( "./IndexDirectory" ) ; File inputFile = new File ( "src/test/resources/sample-docs/Somalia-doc.txt" ) ; String inputString = TextUtils . fileToString ( inputFile ) ; List < ResolvedLocation > resolvedLocations = parser . parse ( inputString ) ; for ( ResolvedLocation resolvedLocation : resolvedLocations ) System . out . println ( resolvedLocation ) ; System . out . println ( "\n\"That's all folks!\"" ) ; }
|
Run this after installing & configuring CLAVIN to get a sense of how to use it .
|
5,086
|
public static no . bekk . bekkopen . person . Fodselsnummer getFodselsnummer ( String fodselsnummer ) throws IllegalArgumentException { validateSyntax ( fodselsnummer ) ; validateIndividnummer ( fodselsnummer ) ; validateDate ( fodselsnummer ) ; validateChecksums ( fodselsnummer ) ; return new no . bekk . bekkopen . person . Fodselsnummer ( fodselsnummer ) ; }
|
Returns an object that represents a Fodselsnummer .
|
5,087
|
public static boolean isValid ( String fodselsnummer ) { try { FodselsnummerValidator . getFodselsnummer ( fodselsnummer ) ; return true ; } catch ( IllegalArgumentException e ) { return false ; } }
|
Return true if the provided String is a valid Fodselsnummer .
|
5,088
|
public static boolean isValid ( String organisasjonsnummer ) { try { OrganisasjonsnummerValidator . getOrganisasjonsnummer ( organisasjonsnummer ) ; return true ; } catch ( IllegalArgumentException e ) { return false ; } }
|
Return true if the provided String is a valid Organisasjonsnummer .
|
5,089
|
public static Organisasjonsnummer getOrganisasjonsnummer ( String organisasjonsnummer ) throws IllegalArgumentException { validateSyntax ( organisasjonsnummer ) ; validateChecksum ( organisasjonsnummer ) ; return new Organisasjonsnummer ( organisasjonsnummer ) ; }
|
Returns an object that represents an Organisasjonsnummer .
|
5,090
|
public static Organisasjonsnummer getAndForceValidOrganisasjonsnummer ( String organisasjonsnummer ) { validateSyntax ( organisasjonsnummer ) ; try { validateChecksum ( organisasjonsnummer ) ; } catch ( IllegalArgumentException iae ) { Organisasjonsnummer onr = new Organisasjonsnummer ( organisasjonsnummer ) ; int checksum = calculateMod11CheckSum ( getMod11Weights ( onr ) , onr ) ; organisasjonsnummer = organisasjonsnummer . substring ( 0 , LENGTH - 1 ) + checksum ; } return new Organisasjonsnummer ( organisasjonsnummer ) ; }
|
Returns an object that represents a Organisasjonsnummer . The checksum of the supplied organisasjonsnummer is changed to a valid checksum if the original organisasjonsnummer has an invalid checksum .
|
5,091
|
public static Date [ ] getHolidays ( int year ) { Set < Date > days = getHolidaySet ( year ) ; Date [ ] dates = days . toArray ( new Date [ days . size ( ) ] ) ; Arrays . sort ( dates ) ; return dates ; }
|
Return a sorted array of holidays for a given year .
|
5,092
|
private static Set < Date > getHolidaySet ( int year ) { if ( holidays == null ) { holidays = new HashMap < Integer , Set < Date > > ( ) ; } if ( ! holidays . containsKey ( year ) ) { Set < Date > yearSet = new HashSet < Date > ( ) ; yearSet . add ( getDate ( 1 , Calendar . JANUARY , year ) ) ; yearSet . add ( getDate ( 1 , Calendar . MAY , year ) ) ; yearSet . add ( getDate ( 17 , Calendar . MAY , year ) ) ; yearSet . add ( getDate ( 25 , Calendar . DECEMBER , year ) ) ; yearSet . add ( getDate ( 26 , Calendar . DECEMBER , year ) ) ; Calendar easterDay = dateToCalendar ( getEasterDay ( year ) ) ; yearSet . add ( rollGetDate ( easterDay , - 7 ) ) ; yearSet . add ( rollGetDate ( easterDay , - 3 ) ) ; yearSet . add ( rollGetDate ( easterDay , - 2 ) ) ; yearSet . add ( easterDay . getTime ( ) ) ; yearSet . add ( rollGetDate ( easterDay , 1 ) ) ; yearSet . add ( rollGetDate ( easterDay , 39 ) ) ; yearSet . add ( rollGetDate ( easterDay , 49 ) ) ; yearSet . add ( rollGetDate ( easterDay , 50 ) ) ; holidays . put ( year , yearSet ) ; } return holidays . get ( year ) ; }
|
Get a set of holidays for a given year .
|
5,093
|
private static boolean isWorkingDay ( Calendar cal ) { return cal . get ( Calendar . DAY_OF_WEEK ) != Calendar . SATURDAY && cal . get ( Calendar . DAY_OF_WEEK ) != Calendar . SUNDAY && ! isHoliday ( cal ) ; }
|
Will check if the given date is a working day . That is check if the given date is a weekend day or a national holiday .
|
5,094
|
private static boolean isHoliday ( Calendar cal ) { int year = cal . get ( Calendar . YEAR ) ; Set < ? > yearSet = getHolidaySet ( year ) ; for ( Object aYearSet : yearSet ) { Date date = ( Date ) aYearSet ; if ( checkDate ( cal , dateToCalendar ( date ) ) ) { return true ; } } return false ; }
|
Check if given Calendar object represents a holiday .
|
5,095
|
private static boolean checkDate ( Calendar cal , Calendar other ) { return checkDate ( cal , other . get ( Calendar . DATE ) , other . get ( Calendar . MONTH ) ) ; }
|
Check if the given dates match on day and month .
|
5,096
|
private static boolean checkDate ( Calendar cal , int date , int month ) { return cal . get ( Calendar . DATE ) == date && cal . get ( Calendar . MONTH ) == month ; }
|
Check if the given date represents the given date and month .
|
5,097
|
private static Calendar dateToCalendar ( Date date ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( date ) ; return cal ; }
|
Convert the given Date object to a Calendar instance .
|
5,098
|
private static Date rollGetDate ( Calendar calendar , int days ) { Calendar easterSunday = ( Calendar ) calendar . clone ( ) ; easterSunday . add ( Calendar . DATE , days ) ; return easterSunday . getTime ( ) ; }
|
Add the given number of days to the calendar and convert to Date .
|
5,099
|
private static Date getDate ( int day , int month , int year ) { Calendar cal = Calendar . getInstance ( ) ; cal . set ( Calendar . YEAR , year ) ; cal . set ( Calendar . MONTH , month ) ; cal . set ( Calendar . DATE , day ) ; return cal . getTime ( ) ; }
|
Get the date for the given values .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.