idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
23,600
protected void extractBundleContent ( String bundleRootPath , String toDirRoot ) throws IOException { File toDir = new File ( toDirRoot ) ; if ( ! toDir . isDirectory ( ) ) { throw new RuntimeException ( "[" + toDir . getAbsolutePath ( ) + "] is not a valid directory or does not exist!" ) ; } toDir = new File ( toDir , bundle . getSymbolicName ( ) ) ; toDir = new File ( toDir , bundle . getVersion ( ) . toString ( ) ) ; FileUtils . forceMkdir ( toDir ) ; bundleExtractDir = toDir ; Enumeration < String > entryPaths = bundle . getEntryPaths ( bundleRootPath ) ; if ( entryPaths != null ) { while ( entryPaths . hasMoreElements ( ) ) { extractContent ( bundleRootPath , entryPaths . nextElement ( ) , bundleExtractDir ) ; } } }
Extracts content from the bundle to a directory .
211
11
23,601
protected void handleAnotherVersionAtStartup ( Bundle bundle ) throws BundleException { Version myVersion = this . bundle . getVersion ( ) ; Version otherVersion = bundle . getVersion ( ) ; if ( myVersion . compareTo ( otherVersion ) > 0 ) { handleNewerVersionAtStartup ( bundle ) ; } else { handleOlderVersionAtStartup ( bundle ) ; } }
Called when another version of this bundle is found in the bundle context .
82
15
23,602
public long getId ( final String agent ) { try { return worker . getId ( agent ) ; } catch ( final InvalidUserAgentError e ) { LOGGER . error ( "Invalid user agent ({})" , agent ) ; throw new SnowizardException ( Response . Status . BAD_REQUEST , "Invalid User-Agent header" , e ) ; } catch ( final InvalidSystemClock e ) { LOGGER . error ( "Invalid system clock" , e ) ; throw new SnowizardException ( Response . Status . INTERNAL_SERVER_ERROR , e . getMessage ( ) , e ) ; } }
Get a new ID and handle any thrown exceptions
129
9
23,603
@ GET @ Timed @ Produces ( MediaType . TEXT_PLAIN ) @ CacheControl ( mustRevalidate = true , noCache = true , noStore = true ) public String getIdAsString ( @ HeaderParam ( HttpHeaders . USER_AGENT ) final String agent ) { return String . valueOf ( getId ( agent ) ) ; }
Get a new ID as plain text
79
7
23,604
@ GET @ Timed @ JSONP ( callback = "callback" , queryParam = "callback" ) @ Produces ( { MediaType . APPLICATION_JSON , MediaTypeAdditional . APPLICATION_JAVASCRIPT } ) @ CacheControl ( mustRevalidate = true , noCache = true , noStore = true ) public Id getIdAsJSON ( @ HeaderParam ( HttpHeaders . USER_AGENT ) final String agent ) { return new Id ( getId ( agent ) ) ; }
Get a new ID as JSON
109
6
23,605
@ GET @ Timed @ Produces ( ProtocolBufferMediaType . APPLICATION_PROTOBUF ) @ CacheControl ( mustRevalidate = true , noCache = true , noStore = true ) public SnowizardResponse getIdAsProtobuf ( @ HeaderParam ( HttpHeaders . USER_AGENT ) final String agent , @ QueryParam ( "count" ) final Optional < IntParam > count ) { final List < Long > ids = Lists . newArrayList ( ) ; if ( count . isPresent ( ) ) { for ( int i = 0 ; i < count . get ( ) . get ( ) ; i ++ ) { ids . add ( getId ( agent ) ) ; } } else { ids . add ( getId ( agent ) ) ; } return SnowizardResponse . newBuilder ( ) . addAllId ( ids ) . build ( ) ; }
Get one or more IDs as a Google Protocol Buffer response
191
11
23,606
public RoutesMetadataPlugin flag ( String flagValue ) { for ( RouteBuilder routeBuilder : routeBuilders ) { routeBuilder . flag ( flagValue ) ; } return this ; }
RouteBuilder route augmentation delegates .
39
7
23,607
static int getBitsPerItemForFpRate ( double fpProb , double loadFactor ) { /* * equation from Cuckoo Filter: Practically Better Than Bloom Bin Fan, * David G. Andersen, Michael Kaminsky , Michael D. Mitzenmacher */ return DoubleMath . roundToInt ( DoubleMath . log2 ( ( 1 / fpProb ) + 3 ) / loadFactor , RoundingMode . UP ) ; }
Calculates how many bits are needed to reach a given false positive rate .
96
16
23,608
static long getBucketsNeeded ( long maxKeys , double loadFactor , int bucketSize ) { /* * force a power-of-two bucket count so hash functions for bucket index * can hashBits%numBuckets and get randomly distributed index. See wiki * "Modulo Bias". Only time we can get perfectly distributed index is * when numBuckets is a power of 2. */ long bucketsNeeded = DoubleMath . roundToLong ( ( 1.0 / loadFactor ) * maxKeys / bucketSize , RoundingMode . UP ) ; // get next biggest power of 2 long bitPos = Long . highestOneBit ( bucketsNeeded ) ; if ( bucketsNeeded > bitPos ) bitPos = bitPos << 1 ; return bitPos ; }
Calculates how many buckets are needed to hold the chosen number of keys taking the standard load factor into account .
164
23
23,609
private boolean trySwapVictimIntoEmptySpot ( ) { long curIndex = victim . getI2 ( ) ; // lock bucket. We always use I2 since victim tag is from bucket I1 bucketLocker . lockSingleBucketWrite ( curIndex ) ; long curTag = table . swapRandomTagInBucket ( curIndex , victim . getTag ( ) ) ; bucketLocker . unlockSingleBucketWrite ( curIndex ) ; // new victim's I2 is different as long as tag isn't the same long altIndex = hasher . altIndex ( curIndex , curTag ) ; // try to insert the new victim tag in it's alternate bucket bucketLocker . lockSingleBucketWrite ( altIndex ) ; try { if ( table . insertToBucket ( altIndex , curTag ) ) { hasVictim = false ; return true ; } else { // still have a victim, but a different one... victim . setTag ( curTag ) ; // new victim always shares I1 with previous victims' I2 victim . setI1 ( curIndex ) ; victim . setI2 ( altIndex ) ; } } finally { bucketLocker . unlockSingleBucketWrite ( altIndex ) ; } return false ; }
if we kicked a tag we need to move it to alternate position possibly kicking another tag there repeating the process until we succeed or run out of chances
262
29
23,610
private void insertIfVictim ( ) { long victimLockstamp = writeLockVictimIfSet ( ) ; if ( victimLockstamp == 0L ) return ; try { // when we get here we definitely have a victim and a write lock bucketLocker . lockBucketsWrite ( victim . getI1 ( ) , victim . getI2 ( ) ) ; try { if ( table . insertToBucket ( victim . getI1 ( ) , victim . getTag ( ) ) || table . insertToBucket ( victim . getI2 ( ) , victim . getTag ( ) ) ) { // set this here because we already have lock hasVictim = false ; } } finally { bucketLocker . unlockBucketsWrite ( victim . getI1 ( ) , victim . getI2 ( ) ) ; } } finally { victimLock . unlock ( victimLockstamp ) ; } }
Attempts to insert the victim item if it exists . Remember that inserting from the victim cache to the main table DOES NOT affect the count since items in the victim cache are technically still in the table
193
38
23,611
private static boolean isHashConfigurationIsSupported ( long numBuckets , int tagBits , int hashSize ) { int hashBitsNeeded = getTotalBitsNeeded ( numBuckets , tagBits ) ; switch ( hashSize ) { case 32 : case 64 : return hashBitsNeeded <= hashSize ; default : } if ( hashSize >= 128 ) return tagBits <= 64 && getIndexBitsUsed ( numBuckets ) <= 64 ; return false ; }
Determines if the chosen hash function is long enough for the table configuration used .
106
17
23,612
HashCode hashObjWithSalt ( T object , int moreSalt ) { Hasher hashInst = hasher . newHasher ( ) ; hashInst . putObject ( object , funnel ) ; hashInst . putLong ( seedNSalt ) ; hashInst . putInt ( moreSalt ) ; return hashInst . hash ( ) ; }
hashes the object with an additional salt . For purpose of the cuckoo filter this is used when the hash generated for an item is all zeros . All zeros is the same as an empty bucket so obviously it s not a valid tag .
70
51
23,613
static int oversize ( int minTargetSize , int bytesPerElement ) { if ( minTargetSize < 0 ) { // catch usage that accidentally overflows int throw new IllegalArgumentException ( "invalid array size " + minTargetSize ) ; } if ( minTargetSize == 0 ) { // wait until at least one element is requested return 0 ; } if ( minTargetSize > MAX_ARRAY_LENGTH ) { throw new IllegalArgumentException ( "requested array size " + minTargetSize + " exceeds maximum array in java (" + MAX_ARRAY_LENGTH + ")" ) ; } // asymptotic exponential growth by 1/8th, favors // spending a bit more CPU to not tie up too much wasted // RAM: int extra = minTargetSize >> 3 ; if ( extra < 3 ) { // for very small arrays, where constant overhead of // realloc is presumably relatively high, we grow // faster extra = 3 ; } int newSize = minTargetSize + extra ; // add 7 to allow for worst case byte alignment addition below: if ( newSize + 7 < 0 || newSize + 7 > MAX_ARRAY_LENGTH ) { // int overflowed, or we exceeded the maximum array length return MAX_ARRAY_LENGTH ; } if ( Constants . JRE_IS_64BIT ) { // round up to 8 byte alignment in 64bit env switch ( bytesPerElement ) { case 4 : // round up to multiple of 2 return ( newSize + 1 ) & 0x7ffffffe ; case 2 : // round up to multiple of 4 return ( newSize + 3 ) & 0x7ffffffc ; case 1 : // round up to multiple of 8 return ( newSize + 7 ) & 0x7ffffff8 ; case 8 : // no rounding default : // odd (invalid?) size return newSize ; } } else { // round up to 4 byte alignment in 64bit env switch ( bytesPerElement ) { case 2 : // round up to multiple of 2 return ( newSize + 1 ) & 0x7ffffffe ; case 1 : // round up to multiple of 4 return ( newSize + 3 ) & 0x7ffffffc ; case 4 : case 8 : // no rounding default : // odd (invalid?) size return newSize ; } } }
Returns an array size &gt ; = minTargetSize generally over - allocating exponentially to achieve amortized linear - time cost as the array grows .
491
31
23,614
long prevSetBit ( long index ) { assert index >= 0 && index < numBits : "index=" + index + " numBits=" + numBits ; int i = ( int ) ( index >> 6 ) ; final int subIndex = ( int ) ( index & 0x3f ) ; // index within the word long word = ( bits [ i ] << ( 63 - subIndex ) ) ; // skip all the bits to the // left of index if ( word != 0 ) { return ( i << 6 ) + subIndex - Long . numberOfLeadingZeros ( word ) ; // See // LUCENE-3197 } while ( -- i >= 0 ) { word = bits [ i ] ; if ( word != 0 ) { return ( i << 6 ) + 63 - Long . numberOfLeadingZeros ( word ) ; } } return - 1 ; }
Returns the index of the last set bit before or on the index specified . - 1 is returned if there are no more set bits .
187
27
23,615
void or ( LongBitSet other ) { assert other . numWords <= numWords : "numWords=" + numWords + ", other.numWords=" + other . numWords ; int pos = Math . min ( numWords , other . numWords ) ; while ( -- pos >= 0 ) { bits [ pos ] |= other . bits [ pos ] ; } }
this = this OR other
77
5
23,616
boolean intersects ( LongBitSet other ) { // Depends on the ghost bits being clear! int pos = Math . min ( numWords , other . numWords ) ; while ( -- pos >= 0 ) { if ( ( bits [ pos ] & other . bits [ pos ] ) != 0 ) return true ; } return false ; }
returns true if the sets have any elements in common
71
11
23,617
void andNot ( LongBitSet other ) { int pos = Math . min ( numWords , other . numWords ) ; while ( -- pos >= 0 ) { bits [ pos ] &= ~ other . bits [ pos ] ; } }
this = this AND NOT other
50
6
23,618
void flip ( long index ) { assert index >= 0 && index < numBits : "index=" + index + " numBits=" + numBits ; int wordNum = ( int ) ( index >> 6 ) ; // div 64 long bitmask = 1L << index ; // mod 64 is implicit bits [ wordNum ] ^= bitmask ; }
Flip the bit at the provided index .
75
9
23,619
static FilterTable create ( int bitsPerTag , long numBuckets ) { // why would this ever happen? checkArgument ( bitsPerTag < 48 , "tagBits (%s) should be less than 48 bits" , bitsPerTag ) ; // shorter fingerprints don't give us a good fill capacity checkArgument ( bitsPerTag > 4 , "tagBits (%s) must be > 4" , bitsPerTag ) ; checkArgument ( numBuckets > 1 , "numBuckets (%s) must be > 1" , numBuckets ) ; // checked so our implementors don't get too.... "enthusiastic" with // table size long bitsPerBucket = IntMath . checkedMultiply ( CuckooFilter . BUCKET_SIZE , bitsPerTag ) ; long bitSetSize = LongMath . checkedMultiply ( bitsPerBucket , numBuckets ) ; LongBitSet memBlock = new LongBitSet ( bitSetSize ) ; return new FilterTable ( memBlock , bitsPerTag , numBuckets ) ; }
Creates a FilterTable
234
5
23,620
boolean insertToBucket ( long bucketIndex , long tag ) { for ( int i = 0 ; i < CuckooFilter . BUCKET_SIZE ; i ++ ) { if ( checkTag ( bucketIndex , i , 0 ) ) { writeTagNoClear ( bucketIndex , i , tag ) ; return true ; } } return false ; }
inserts a tag into an empty position in the chosen bucket .
75
13
23,621
long swapRandomTagInBucket ( long curIndex , long tag ) { int randomBucketPosition = ThreadLocalRandom . current ( ) . nextInt ( CuckooFilter . BUCKET_SIZE ) ; return readTagAndSet ( curIndex , randomBucketPosition , tag ) ; }
Replaces a tag in a random position in the given bucket and returns the tag that was replaced .
63
20
23,622
boolean findTag ( long i1 , long i2 , long tag ) { for ( int i = 0 ; i < CuckooFilter . BUCKET_SIZE ; i ++ ) { if ( checkTag ( i1 , i , tag ) || checkTag ( i2 , i , tag ) ) return true ; } return false ; }
Finds a tag if present in two buckets .
73
10
23,623
boolean deleteFromBucket ( long i1 , long tag ) { for ( int i = 0 ; i < CuckooFilter . BUCKET_SIZE ; i ++ ) { if ( checkTag ( i1 , i , tag ) ) { deleteTag ( i1 , i ) ; return true ; } } return false ; }
Deletes an item from the table if it is found in the bucket
71
14
23,624
long readTag ( long bucketIndex , int posInBucket ) { long tagStartIdx = getTagOffset ( bucketIndex , posInBucket ) ; long tag = 0 ; long tagEndIdx = tagStartIdx + bitsPerTag ; // looping over true bits per nextBitSet javadocs for ( long i = memBlock . nextSetBit ( tagStartIdx ) ; i >= 0 && i < tagEndIdx ; i = memBlock . nextSetBit ( i + 1L ) ) { // set corresponding bit in tag tag |= 1 << ( i - tagStartIdx ) ; } return tag ; }
Works but currently only used for testing
139
7
23,625
long readTagAndSet ( long bucketIndex , int posInBucket , long newTag ) { long tagStartIdx = getTagOffset ( bucketIndex , posInBucket ) ; long tag = 0 ; long tagEndIdx = tagStartIdx + bitsPerTag ; int tagPos = 0 ; for ( long i = tagStartIdx ; i < tagEndIdx ; i ++ ) { if ( ( newTag & ( 1L << tagPos ) ) != 0 ) { if ( memBlock . getAndSet ( i ) ) { tag |= 1 << tagPos ; } } else { if ( memBlock . getAndClear ( i ) ) { tag |= 1 << tagPos ; } } tagPos ++ ; } return tag ; }
Reads a tag and sets the bits to a new tag at same time for max speedification
162
19
23,626
boolean checkTag ( long bucketIndex , int posInBucket , long tag ) { long tagStartIdx = getTagOffset ( bucketIndex , posInBucket ) ; final int bityPerTag = bitsPerTag ; for ( long i = 0 ; i < bityPerTag ; i ++ ) { if ( memBlock . get ( i + tagStartIdx ) != ( ( tag & ( 1L << i ) ) != 0 ) ) return false ; } return true ; }
Check if a tag in a given position in a bucket matches the tag you passed it . Faster than regular read because it stops checking if it finds a non - matching bit .
105
35
23,627
void writeTagNoClear ( long bucketIndex , int posInBucket , long tag ) { long tagStartIdx = getTagOffset ( bucketIndex , posInBucket ) ; // BIT BANGIN YEAAAARRHHHGGGHHH for ( int i = 0 ; i < bitsPerTag ; i ++ ) { // second arg just does bit test in tag if ( ( tag & ( 1L << i ) ) != 0 ) { memBlock . set ( tagStartIdx + i ) ; } } }
Writes a tag to a bucket position . Faster than regular write because it assumes tag starts with all zeros but doesn t work properly if the position wasn t empty .
112
34
23,628
private static Object invoke ( Object obj , String method , Object ... args ) throws NoSuchMethodException , InvocationTargetException , IllegalAccessException { Class < ? > [ ] argumentTypes = new Class [ args . length ] ; for ( int i = 0 ; i < args . length ; ++ i ) { argumentTypes [ i ] = args [ i ] . getClass ( ) ; } Method m = obj . getClass ( ) . getMethod ( method , argumentTypes ) ; m . setAccessible ( true ) ; return m . invoke ( obj , args ) ; }
Invoke a method using reflection
120
6
23,629
private void invokeIgnoreExceptions ( Object obj , String method , Object ... args ) { try { invoke ( obj , method , args ) ; } catch ( NoSuchMethodException e ) { logger . trace ( "Unable to log progress" , e ) ; } catch ( InvocationTargetException e ) { logger . trace ( "Unable to log progress" , e ) ; } catch ( IllegalAccessException e ) { logger . trace ( "Unable to log progress" , e ) ; } }
Invoke a method using reflection but don t throw any exceptions . Just log errors instead .
106
18
23,630
public static void optimizeTable ( FluoConfiguration fluoConfig , TableOptimizations tableOptim ) throws Exception { Connector conn = getConnector ( fluoConfig ) ; TreeSet < Text > splits = new TreeSet <> ( ) ; for ( Bytes split : tableOptim . getSplits ( ) ) { splits . add ( new Text ( split . toArray ( ) ) ) ; } String table = fluoConfig . getAccumuloTable ( ) ; conn . tableOperations ( ) . addSplits ( table , splits ) ; if ( tableOptim . getTabletGroupingRegex ( ) != null && ! tableOptim . getTabletGroupingRegex ( ) . isEmpty ( ) ) { // was going to call : // conn.instanceOperations().testClassLoad(RGB_CLASS, TABLET_BALANCER_CLASS) // but that failed. See ACCUMULO-4068 try { // setting this prop first intentionally because it should fail in 1.6 conn . tableOperations ( ) . setProperty ( table , RGB_PATTERN_PROP , tableOptim . getTabletGroupingRegex ( ) ) ; conn . tableOperations ( ) . setProperty ( table , RGB_DEFAULT_PROP , "none" ) ; conn . tableOperations ( ) . setProperty ( table , TABLE_BALANCER_PROP , RGB_CLASS ) ; } catch ( AccumuloException e ) { logger . warn ( "Unable to setup regex balancer (this is expected to fail in Accumulo 1.6.X) : " + e . getMessage ( ) ) ; logger . debug ( "Unable to setup regex balancer (this is expected to fail in Accumulo 1.6.X)" , e ) ; } } }
Make the requested table optimizations .
391
6
23,631
public void filteredAdd ( LogEntry entry , Predicate < LogEntry > filter ) { if ( filter . test ( entry ) ) { add ( entry ) ; } }
Adds LogEntry to TxLog if it passes filter
35
11
23,632
public Map < RowColumn , Bytes > getOperationMap ( LogEntry . Operation op ) { Map < RowColumn , Bytes > opMap = new HashMap <> ( ) ; for ( LogEntry entry : logEntries ) { if ( entry . getOp ( ) . equals ( op ) ) { opMap . put ( new RowColumn ( entry . getRow ( ) , entry . getColumn ( ) ) , entry . getValue ( ) ) ; } } return opMap ; }
Returns a map of RowColumn changes given an operation
104
10
23,633
private String getProjectStageNameFromJNDI ( ) { try { InitialContext context = new InitialContext ( ) ; Object obj = context . lookup ( ProjectStage . PROJECT_STAGE_JNDI_NAME ) ; if ( obj != null ) { return obj . toString ( ) . trim ( ) ; } } catch ( NamingException e ) { // ignore } return null ; }
Performs a JNDI lookup to obtain the current project stage . The method use the standard JNDI name for the JSF project stage for the lookup
84
32
23,634
public static RecordingTransactionBase wrap ( TransactionBase txb , Predicate < LogEntry > filter ) { return new RecordingTransactionBase ( txb , filter ) ; }
Creates a RecordingTransactionBase using the provided LogEntry filter function and existing TransactionBase
34
17
23,635
public @ Nonnull ThreadDumpRuntime fromCurrentProcess ( ) throws IOException , InterruptedException { final String jvmName = ManagementFactory . getRuntimeMXBean ( ) . getName ( ) ; final int index = jvmName . indexOf ( ' ' ) ; if ( index < 1 ) throw new IOException ( "Unable to extract PID from " + jvmName ) ; long pid ; try { pid = Long . parseLong ( jvmName . substring ( 0 , index ) ) ; } catch ( NumberFormatException e ) { throw new IOException ( "Unable to extract PID from " + jvmName ) ; } return fromProcess ( pid ) ; }
Extract runtime from current process .
145
7
23,636
@ SuppressWarnings ( { "unchecked" , "rawtypes" , "unused" } ) public void afterPhase ( final PhaseEvent event ) { if ( PhaseId . RENDER_RESPONSE . equals ( event . getPhaseId ( ) ) ) { RenderContext contextInstance = getContextInstance ( ) ; if ( contextInstance != null ) { Integer id = contextInstance . getId ( ) ; RenderContext removed = getRenderContextMap ( ) . remove ( id ) ; Map < Contextual < ? > , Object > componentInstanceMap = getComponentInstanceMap ( ) ; Map < Contextual < ? > , CreationalContext < ? > > creationalContextMap = getCreationalContextMap ( ) ; if ( ( componentInstanceMap != null ) && ( creationalContextMap != null ) ) { for ( Entry < Contextual < ? > , Object > componentEntry : componentInstanceMap . entrySet ( ) ) { Contextual contextual = componentEntry . getKey ( ) ; Object instance = componentEntry . getValue ( ) ; CreationalContext creational = creationalContextMap . get ( contextual ) ; contextual . destroy ( instance , creational ) ; } } } } }
Destroy the current context since Render Response has completed .
255
10
23,637
protected boolean elements ( String ... name ) { if ( name == null || name . length != stack . size ( ) ) { return false ; } for ( int i = 0 ; i < name . length ; i ++ ) { if ( ! name [ i ] . equals ( stack . get ( i ) ) ) { return false ; } } return true ; }
Checks whether the element stack currently contains exactly the elements supplied by the caller . This method can be used to find the current position in the document . The first argument is always the root element of the document the second is a child of the root element and so on . The method uses the local names of the elements only . Namespaces are ignored .
75
70
23,638
public static Predicate < LogEntry > getFilter ( ) { return le -> le . getOp ( ) . equals ( LogEntry . Operation . DELETE ) || le . getOp ( ) . equals ( LogEntry . Operation . SET ) ; }
Returns LogEntry filter for Accumulo replication .
53
10
23,639
public static void generateMutations ( long seq , TxLog txLog , Consumer < Mutation > consumer ) { Map < Bytes , Mutation > mutationMap = new HashMap <> ( ) ; for ( LogEntry le : txLog . getLogEntries ( ) ) { LogEntry . Operation op = le . getOp ( ) ; Column col = le . getColumn ( ) ; byte [ ] cf = col . getFamily ( ) . toArray ( ) ; byte [ ] cq = col . getQualifier ( ) . toArray ( ) ; byte [ ] cv = col . getVisibility ( ) . toArray ( ) ; if ( op . equals ( LogEntry . Operation . DELETE ) || op . equals ( LogEntry . Operation . SET ) ) { Mutation m = mutationMap . computeIfAbsent ( le . getRow ( ) , k -> new Mutation ( k . toArray ( ) ) ) ; if ( op . equals ( LogEntry . Operation . DELETE ) ) { if ( col . isVisibilitySet ( ) ) { m . putDelete ( cf , cq , new ColumnVisibility ( cv ) , seq ) ; } else { m . putDelete ( cf , cq , seq ) ; } } else { if ( col . isVisibilitySet ( ) ) { m . put ( cf , cq , new ColumnVisibility ( cv ) , seq , le . getValue ( ) . toArray ( ) ) ; } else { m . put ( cf , cq , seq , le . getValue ( ) . toArray ( ) ) ; } } } } mutationMap . values ( ) . forEach ( consumer ) ; }
Generates Accumulo mutations from a Transaction log . Used to Replicate Fluo table to Accumulo .
362
23
23,640
public UIForm locateForm ( ) { UIComponent parent = this . getParent ( ) ; while ( ! ( parent instanceof UIForm ) ) { if ( ( parent == null ) || ( parent instanceof UIViewRoot ) ) { throw new IllegalStateException ( "The UIValidateForm (<s:validateForm />) component must be placed within a UIForm (<h:form>)" ) ; } parent = parent . getParent ( ) ; } return ( UIForm ) parent ; }
Attempt to locate the form in which this component resides . If the component is not within a UIForm tag throw an exception .
112
26
23,641
private Bytes getMinimalRow ( ) { return Bytes . builder ( bucketRow . length ( ) + 1 ) . append ( bucketRow ) . append ( ' ' ) . toBytes ( ) ; }
Computes the minimal row for a bucket
44
8
23,642
public @ Nonnull ThreadType onlyThread ( ) throws IllegalStateException { if ( size ( ) != 1 ) throw new IllegalStateException ( "Exactly one thread expected in the set. Found " + size ( ) ) ; return threads . iterator ( ) . next ( ) ; }
Extract the only thread from set .
58
8
23,643
public @ Nonnull SetType getBlockedThreads ( ) { Set < ThreadLock > acquired = new HashSet < ThreadLock > ( ) ; for ( ThreadType thread : threads ) { acquired . addAll ( thread . getAcquiredLocks ( ) ) ; } Set < ThreadType > blocked = new HashSet < ThreadType > ( ) ; for ( ThreadType thread : runtime . getThreads ( ) ) { if ( acquired . contains ( thread . getWaitingToLock ( ) ) ) { blocked . add ( thread ) ; } } return runtime . getThreadSet ( blocked ) ; }
Get threads blocked by any of current threads .
128
9
23,644
public @ Nonnull SetType getBlockingThreads ( ) { Set < ThreadLock > waitingTo = new HashSet < ThreadLock > ( ) ; for ( ThreadType thread : threads ) { if ( thread . getWaitingToLock ( ) != null ) { waitingTo . add ( thread . getWaitingToLock ( ) ) ; } } Set < ThreadType > blocking = new HashSet < ThreadType > ( ) ; for ( ThreadType thread : runtime . getThreads ( ) ) { Set < ThreadLock > threadHolding = thread . getAcquiredLocks ( ) ; threadHolding . retainAll ( waitingTo ) ; if ( ! threadHolding . isEmpty ( ) ) { blocking . add ( thread ) ; } } return runtime . getThreadSet ( blocking ) ; }
Get threads blocking any of current threads .
170
8
23,645
public @ Nonnull SetType where ( ProcessThread . Predicate pred ) { HashSet < ThreadType > subset = new HashSet < ThreadType > ( size ( ) / 2 ) ; for ( ThreadType thread : threads ) { if ( pred . isValid ( thread ) ) subset . add ( thread ) ; } return runtime . getThreadSet ( subset ) ; }
Get subset of current threads .
77
6
23,646
public < T extends SingleThreadSetQuery . Result < SetType , RuntimeType , ThreadType > > T query ( SingleThreadSetQuery < T > query ) { return query . < SetType , RuntimeType , ThreadType > query ( ( SetType ) this ) ; }
Run query using this as an initial thread set .
57
10
23,647
@ SuppressWarnings ( "unused" ) private static MBeanServerConnection getServerConnection ( int pid ) { try { JMXServiceURL serviceURL = new JMXServiceURL ( connectorAddress ( pid ) ) ; return JMXConnectorFactory . connect ( serviceURL ) . getMBeanServerConnection ( ) ; } catch ( MalformedURLException ex ) { throw failed ( "JMX connection failed" , ex ) ; } catch ( IOException ex ) { throw failed ( "JMX connection failed" , ex ) ; } }
This has to be called by reflection so it can as well be private to stress this is not an API
118
21
23,648
private Monitor getMonitorJustAcquired ( List < ThreadLock . Monitor > monitors ) { if ( monitors . isEmpty ( ) ) return null ; Monitor monitor = monitors . get ( 0 ) ; if ( monitor . getDepth ( ) != 0 ) return null ; for ( Monitor duplicateCandidate : monitors ) { if ( monitor . equals ( duplicateCandidate ) ) continue ; // skip first - equality includes monitor depth if ( monitor . getLock ( ) . equals ( duplicateCandidate . getLock ( ) ) ) return null ; // Acquired earlier } return monitor ; }
get monitor acquired on current stackframe null when it was acquired earlier or not monitor is held
119
18
23,649
public void setupDecorateMethods ( ClassLoader cl ) { synchronized ( STAR_IMPORTS ) { if ( DECORATED ) return ; GroovyShell shell = new GroovyShell ( cl , new Binding ( ) , getCompilerConfiguration ( ) ) ; try { shell . run ( new InputStreamReader ( this . getClass ( ) . getResourceAsStream ( "extend.groovy" ) ) , "dumpling-metaclass-setup" , Collections . emptyList ( ) ) ; } catch ( Exception ex ) { AssertionError err = new AssertionError ( "Unable to decorate object model" ) ; err . initCause ( ex ) ; throw err ; // Java 6 } DECORATED = true ; } }
Decorate Dumpling API with groovy extensions .
160
10
23,650
private void performObservation ( PhaseEvent event , PhaseIdType phaseIdType ) { UIViewRoot viewRoot = ( UIViewRoot ) event . getFacesContext ( ) . getViewRoot ( ) ; List < ? extends Annotation > restrictionsForPhase = getRestrictionsForPhase ( phaseIdType , viewRoot . getViewId ( ) ) ; if ( restrictionsForPhase != null ) { log . debugf ( "Enforcing on phase %s" , phaseIdType ) ; enforce ( event . getFacesContext ( ) , viewRoot , restrictionsForPhase ) ; } }
Inspect the annotations in the ViewConfigStore enforcing any restrictions applicable to this phase
127
16
23,651
public boolean isAnnotationApplicableToPhase ( Annotation annotation , PhaseIdType currentPhase , PhaseIdType [ ] defaultPhases ) { Method restrictAtViewMethod = getRestrictAtViewMethod ( annotation ) ; PhaseIdType [ ] phasedIds = null ; if ( restrictAtViewMethod != null ) { log . warnf ( "Annotation %s is using the restrictAtViewMethod. Use a @RestrictAtPhase qualifier on the annotation instead." ) ; phasedIds = getRestrictedPhaseIds ( restrictAtViewMethod , annotation ) ; } RestrictAtPhase restrictAtPhaseQualifier = AnnotationInspector . getAnnotation ( annotation . annotationType ( ) , RestrictAtPhase . class , beanManager ) ; if ( restrictAtPhaseQualifier != null ) { log . debug ( "Using Phases found in @RestrictAtView qualifier on the annotation." ) ; phasedIds = restrictAtPhaseQualifier . value ( ) ; } if ( phasedIds == null ) { log . debug ( "Falling back on default phase ids" ) ; phasedIds = defaultPhases ; } if ( Arrays . binarySearch ( phasedIds , currentPhase ) >= 0 ) { return true ; } return false ; }
Inspect an annotation to see if it specifies a view in which it should be . Fall back on default view otherwise .
265
24
23,652
public Method getRestrictAtViewMethod ( Annotation annotation ) { Method restrictAtViewMethod ; try { restrictAtViewMethod = annotation . annotationType ( ) . getDeclaredMethod ( "restrictAtPhase" ) ; } catch ( NoSuchMethodException ex ) { restrictAtViewMethod = null ; } catch ( SecurityException ex ) { throw new IllegalArgumentException ( "restrictAtView method must be accessible" , ex ) ; } return restrictAtViewMethod ; }
Utility method to extract the restrictAtPhase method from an annotation
101
13
23,653
public PhaseIdType [ ] getRestrictedPhaseIds ( Method restrictAtViewMethod , Annotation annotation ) { PhaseIdType [ ] phaseIds ; try { phaseIds = ( PhaseIdType [ ] ) restrictAtViewMethod . invoke ( annotation ) ; } catch ( IllegalAccessException ex ) { throw new IllegalArgumentException ( "restrictAtView method must be accessible" , ex ) ; } catch ( InvocationTargetException ex ) { throw new RuntimeException ( ex ) ; } return phaseIds ; }
Retrieve the default PhaseIdTypes defined by the restrictAtViewMethod in the annotation
111
17
23,654
public static TableOptimizations getConfiguredOptimizations ( FluoConfiguration fluoConfig ) { try ( FluoClient client = FluoFactory . newClient ( fluoConfig ) ) { SimpleConfiguration appConfig = client . getAppConfiguration ( ) ; TableOptimizations tableOptim = new TableOptimizations ( ) ; SimpleConfiguration subset = appConfig . subset ( PREFIX . substring ( 0 , PREFIX . length ( ) - 1 ) ) ; Iterator < String > keys = subset . getKeys ( ) ; while ( keys . hasNext ( ) ) { String key = keys . next ( ) ; String clazz = subset . getString ( key ) ; try { TableOptimizationsFactory factory = Class . forName ( clazz ) . asSubclass ( TableOptimizationsFactory . class ) . newInstance ( ) ; tableOptim . merge ( factory . getTableOptimizations ( key , appConfig ) ) ; } catch ( InstantiationException | IllegalAccessException | ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } } return tableOptim ; } }
A utility method to get all registered table optimizations . Many recipes will automatically register table optimizations when configured .
235
20
23,655
public void addTransientRange ( String id , RowRange range ) { String start = DatatypeConverter . printHexBinary ( range . getStart ( ) . toArray ( ) ) ; String end = DatatypeConverter . printHexBinary ( range . getEnd ( ) . toArray ( ) ) ; appConfig . setProperty ( PREFIX + id , start + ":" + end ) ; }
This method is expected to be called before Fluo is initialized to register transient ranges .
93
17
23,656
public List < RowRange > getTransientRanges ( ) { List < RowRange > ranges = new ArrayList <> ( ) ; Iterator < String > keys = appConfig . getKeys ( PREFIX . substring ( 0 , PREFIX . length ( ) - 1 ) ) ; while ( keys . hasNext ( ) ) { String key = keys . next ( ) ; String val = appConfig . getString ( key ) ; String [ ] sa = val . split ( ":" ) ; RowRange rowRange = new RowRange ( Bytes . of ( DatatypeConverter . parseHexBinary ( sa [ 0 ] ) ) , Bytes . of ( DatatypeConverter . parseHexBinary ( sa [ 1 ] ) ) ) ; ranges . add ( rowRange ) ; } return ranges ; }
This method is expected to be called after Fluo is initialized to get the ranges that were registered before initialization .
178
22
23,657
@ SuppressWarnings ( "unchecked" ) protected List < T > getEnabledListeners ( Class < ? extends T > ... classes ) { List < T > listeners = new ArrayList < T > ( ) ; for ( Class < ? extends T > clazz : classes ) { Set < Bean < ? > > beans = getBeanManager ( ) . getBeans ( clazz ) ; if ( ! beans . isEmpty ( ) ) { Bean < T > bean = ( Bean < T > ) getBeanManager ( ) . resolve ( beans ) ; CreationalContext < T > context = getBeanManager ( ) . createCreationalContext ( bean ) ; listeners . add ( ( T ) getBeanManager ( ) . getReference ( bean , clazz , context ) ) ; } } return listeners ; }
Create contextual instances for the specified listener classes excluding any listeners that do not correspond to an enabled bean .
175
20
23,658
public void update ( TransactionBase tx , Map < K , V > updates ) { combineQ . addAll ( tx , updates ) ; }
Queues updates for a collision free map . These updates will be made by an Observer executing another transaction . This method will not collide with other transaction queuing updates for the same keys .
29
37
23,659
public static void configure ( FluoConfiguration fluoConfig , Options opts ) { org . apache . fluo . recipes . core . combine . CombineQueue . FluentOptions cqopts = CombineQueue . configure ( opts . mapId ) . keyType ( opts . keyType ) . valueType ( opts . valueType ) . buckets ( opts . numBuckets ) ; if ( opts . bucketsPerTablet != null ) { cqopts . bucketsPerTablet ( opts . bucketsPerTablet ) ; } if ( opts . bufferSize != null ) { cqopts . bufferSize ( opts . bufferSize ) ; } cqopts . save ( fluoConfig ) ; opts . save ( fluoConfig . getAppConfiguration ( ) ) ; fluoConfig . addObserver ( new org . apache . fluo . api . config . ObserverSpecification ( CollisionFreeMapObserver . class . getName ( ) , ImmutableMap . of ( "mapId" , opts . mapId ) ) ) ; }
This method configures a collision free map for use . It must be called before initializing Fluo .
233
21
23,660
@ Deprecated public static void configure ( FluoConfiguration fluoConfig , Options opts ) { SimpleConfiguration appConfig = fluoConfig . getAppConfiguration ( ) ; opts . save ( appConfig ) ; fluoConfig . addObserver ( new org . apache . fluo . api . config . ObserverSpecification ( ExportObserver . class . getName ( ) , Collections . singletonMap ( "queueId" , opts . fluentCfg . queueId ) ) ) ; }
Call this method before initializing Fluo .
105
9
23,661
public static RecordingTransaction wrap ( Transaction tx , Predicate < LogEntry > filter ) { return new RecordingTransaction ( tx , filter ) ; }
Creates a RecordingTransaction using the provided LogEntry filter and existing Transaction
29
14
23,662
protected InputContainerElements scan ( final UIComponent component , InputContainerElements elements , final FacesContext context ) { if ( elements == null ) { elements = new InputContainerElements ( ) ; } // NOTE we need to walk the tree ignoring rendered attribute because it's condition // could be based on what we discover if ( ( elements . getLabel ( ) == null ) && ( component instanceof HtmlOutputLabel ) ) { elements . setLabel ( ( HtmlOutputLabel ) component ) ; } else if ( component instanceof EditableValueHolder ) { elements . registerInput ( ( EditableValueHolder ) component , getDefaultValidator ( context ) , context ) ; } else if ( component instanceof UIMessage ) { elements . registerMessage ( ( UIMessage ) component ) ; } // may need to walk smarter to ensure "element of least suprise" for ( UIComponent child : component . getChildren ( ) ) { scan ( child , elements , context ) ; } return elements ; }
Walk the component tree branch built by the composite component and locate the input container elements .
215
17
23,663
public void assignIds ( final InputContainerElements elements , final FacesContext context ) { boolean refreshIds = false ; if ( getId ( ) . startsWith ( UIViewRoot . UNIQUE_ID_PREFIX ) ) { setId ( elements . getPropertyName ( context ) ) ; refreshIds = true ; } UIComponent label = elements . getLabel ( ) ; if ( label != null ) { if ( label . getId ( ) . startsWith ( UIViewRoot . UNIQUE_ID_PREFIX ) ) { label . setId ( getDefaultLabelId ( ) ) ; } else if ( refreshIds ) { label . setId ( label . getId ( ) ) ; } } for ( int i = 0 , len = elements . getInputs ( ) . size ( ) ; i < len ; i ++ ) { UIComponent input = ( UIComponent ) elements . getInputs ( ) . get ( i ) ; if ( input . getId ( ) . startsWith ( UIViewRoot . UNIQUE_ID_PREFIX ) ) { input . setId ( getDefaultInputId ( ) + ( i == 0 ? "" : ( i + 1 ) ) ) ; } else if ( refreshIds ) { input . setId ( input . getId ( ) ) ; } } for ( int i = 0 , len = elements . getMessages ( ) . size ( ) ; i < len ; i ++ ) { UIComponent msg = elements . getMessages ( ) . get ( i ) ; if ( msg . getId ( ) . startsWith ( UIViewRoot . UNIQUE_ID_PREFIX ) ) { msg . setId ( getDefaultMessageId ( ) + ( i == 0 ? "" : ( i + 1 ) ) ) ; } else if ( refreshIds ) { msg . setId ( msg . getId ( ) ) ; } } }
assigning ids seems to break form submissions but I don t know why
422
15
23,664
private Validator getDefaultValidator ( final FacesContext context ) throws FacesException { if ( ! beanValidationPresent ) { return null ; } ValidatorFactory validatorFactory ; Object cachedObject = context . getExternalContext ( ) . getApplicationMap ( ) . get ( BeanValidator . VALIDATOR_FACTORY_KEY ) ; if ( cachedObject instanceof ValidatorFactory ) { validatorFactory = ( ValidatorFactory ) cachedObject ; } else { try { validatorFactory = Validation . buildDefaultValidatorFactory ( ) ; } catch ( ValidationException e ) { throw new FacesException ( "Could not build a default Bean Validator factory" , e ) ; } context . getExternalContext ( ) . getApplicationMap ( ) . put ( BeanValidator . VALIDATOR_FACTORY_KEY , validatorFactory ) ; } return validatorFactory . getValidator ( ) ; }
Get the default Bean Validation Validator to read the contraints for a property .
193
17
23,665
public @ Nonnull SetType getBlockedThreads ( ) { Set < ThreadType > blocked = new LinkedHashSet < ThreadType > ( ) ; for ( ThreadType thread : runtime . getThreads ( ) ) { if ( thread == this ) continue ; if ( getAcquiredLocks ( ) . contains ( thread . getWaitingToLock ( ) ) ) { blocked . add ( thread ) ; } } return runtime . getThreadSet ( blocked ) ; }
Get threads that are waiting for lock held by this thread .
101
12
23,666
public @ Nonnull SetType getBlockingThreads ( ) { final ThreadType blocking = getBlockingThread ( ) ; if ( blocking == null ) return runtime . getEmptyThreadSet ( ) ; return runtime . getThreadSet ( Collections . singleton ( blocking ) ) ; }
Get threads holding lock this thread is trying to acquire .
59
11
23,667
public @ CheckForNull ThreadType getBlockingThread ( ) { if ( state . waitingToLock == null && state . waitingOnLock == null ) { return null ; } for ( ThreadType thread : runtime . getThreads ( ) ) { if ( thread == this ) continue ; Set < ThreadLock > acquired = thread . getAcquiredLocks ( ) ; if ( acquired . isEmpty ( ) ) continue ; if ( acquired . contains ( state . waitingToLock ) || acquired . contains ( state . waitingOnLock ) ) { return thread ; } } return null ; }
Get thread blocking this threads execution .
123
7
23,668
private void init ( String xmlPath ) throws MalformedURLException , IOException { XML xml = new XML ( true , xmlPath ) ; if ( ! xml . isInheritedMapped ( configuredClass ) ) Error . classNotMapped ( configuredClass ) ; for ( Class < ? > classe : getClasses ( xml ) ) { relationalManyToOneMapper . put ( classe . getName ( ) , new JMapper ( configuredClass , classe , ChooseConfig . DESTINATION , xmlPath ) ) ; relationalOneToManyMapper . put ( classe . getName ( ) , new JMapper ( classe , configuredClass , ChooseConfig . SOURCE , xmlPath ) ) ; } }
This method initializes relational maps starting from XML .
155
10
23,669
private Set < Class < ? > > getClasses ( XML xml ) { HashSet < Class < ? > > result = new HashSet < Class < ? > > ( ) ; // in case of override only the last global configuration must be analyzed Global global = null ; for ( Class < ? > clazz : getAllsuperClasses ( configuredClass ) ) { // only if global configuration is null will be searched global configuration on super classes if ( isNull ( global ) ) { global = xml . loadGlobals ( ) . get ( clazz . getName ( ) ) ; if ( ! isNull ( global ) ) { addClasses ( global . getClasses ( ) , result ) ; if ( global . getExcluded ( ) != null ) for ( Attribute attribute : xml . loadAttributes ( ) . get ( clazz . getName ( ) ) ) for ( String fieldName : global . getExcluded ( ) ) if ( attribute . getName ( ) . equals ( fieldName ) ) addClasses ( attribute . getClasses ( ) , result , attribute . getName ( ) ) ; } } List < Attribute > attributes = xml . loadAttributes ( ) . get ( clazz . getName ( ) ) ; if ( ! isNull ( attributes ) ) for ( Attribute attribute : attributes ) if ( isNull ( global ) || isPresent ( global . getExcluded ( ) , attribute . getName ( ) ) || ( ! isEmpty ( global . getAttributes ( ) ) && ! isPresent ( global . getAttributes ( ) , new SimplyAttribute ( attribute . getName ( ) ) ) ) ) addClasses ( attribute . getClasses ( ) , result , attribute . getName ( ) ) ; } return result ; }
Returns all Target Classes contained in the XML .
370
9
23,670
private void init ( ) { if ( ! Annotation . isInheritedMapped ( configuredClass ) ) Error . classNotMapped ( configuredClass ) ; for ( Class < ? > classe : getClasses ( ) ) { relationalManyToOneMapper . put ( classe . getName ( ) , new JMapper ( configuredClass , classe , ChooseConfig . DESTINATION ) ) ; relationalOneToManyMapper . put ( classe . getName ( ) , new JMapper ( classe , configuredClass , ChooseConfig . SOURCE ) ) ; } }
This method initializes relational maps
124
6
23,671
private Set < Class < ? > > getClasses ( ) { HashSet < Class < ? > > result = new HashSet < Class < ? > > ( ) ; // in case of override only the last global configuration must be analyzed JGlobalMap jGlobalMap = null ; for ( Class < ? > clazz : getAllsuperClasses ( configuredClass ) ) { // only if global configuration is null will be searched global configuration on super classes if ( isNull ( jGlobalMap ) ) { jGlobalMap = clazz . getAnnotation ( JGlobalMap . class ) ; //if the field configuration is defined in the global map if ( ! isNull ( jGlobalMap ) ) { addClasses ( jGlobalMap . classes ( ) , result ) ; if ( ! isNull ( jGlobalMap . excluded ( ) ) ) for ( Field field : getListOfFields ( configuredClass ) ) { JMap jMap = field . getAnnotation ( JMap . class ) ; if ( ! isNull ( jMap ) ) for ( String fieldName : jGlobalMap . excluded ( ) ) if ( field . getName ( ) . equals ( fieldName ) ) addClasses ( jMap . classes ( ) , result , field . getName ( ) ) ; } return result ; } } } for ( Field field : getListOfFields ( configuredClass ) ) { JMap jMap = field . getAnnotation ( JMap . class ) ; if ( ! isNull ( jMap ) ) addClasses ( jMap . classes ( ) , result , field . getName ( ) ) ; } return result ; }
Returns all Target Classes
344
4
23,672
private < I > I destinationClassControl ( Exception exception , Class < I > clazz ) { try { if ( clazz == null ) throw new IllegalArgumentException ( "it's mandatory define the destination class" ) ; } catch ( Exception e ) { JmapperLog . error ( e ) ; return null ; } return logAndReturnNull ( exception ) ; }
This method verifies that the destinationClass exists .
78
10
23,673
private < D , S > JMapper < D , S > getJMapper ( HashMap < String , JMapper > map , Object source ) { Class < ? > sourceClass = source instanceof Class ? ( ( Class < ? > ) source ) : source . getClass ( ) ; JMapper < D , S > jMapper = map . get ( sourceClass . getName ( ) ) ; if ( jMapper == null ) Error . classNotMapped ( source , configuredClass ) ; return jMapper ; }
Returns the desired JMapper instance .
111
7
23,674
public Global excludedAttributes ( String ... attributes ) { for ( String attribute : attributes ) global . excluded . ( new XmlExcludedAttribute ( attribute ) ) ; return this ; }
Attributes to exclude from mapping .
37
6
23,675
public Global targetClasses ( Class < ? > ... classes ) { for ( Class < ? > targetClass : classes ) global . classes . ( new TargetClass ( targetClass ) . toXStream ( ) ) ; return this ; }
Target classes .
49
3
23,676
public boolean isUndefined ( final Field destination , final Field source ) { info = null ; for ( IOperationAnalyzer analyzer : analyzers ) if ( analyzer . verifyConditions ( destination , source ) ) info = analyzer . getInfoOperation ( destination , source ) ; // if the operation has not been identified if ( isNull ( info ) ) info = undefinedOperation ( ) ; boolean conversionMethodExists = conversionAnalyzer . fieldsToCheck ( destination , source ) ; OperationType operationType = info . getOperationType ( ) ; if ( operationType . isUndefined ( ) && ! conversionMethodExists ) return true ; if ( conversionMethodExists ) // explicit conversion between primitive types info . setInstructionType ( operationType . isBasic ( ) ? OperationType . BASIC_CONVERSION // explicit conversion between complex types : OperationType . CONVERSION ) ; return false ; }
This method analyzes the fields calculates the info and returns true if operation is undefined .
188
17
23,677
private String getValue ( final String value , final String mappedFieldName ) { if ( isNull ( value ) ) return null ; return value . equals ( DEFAULT_FIELD_VALUE ) ? mappedFieldName : value ; }
This method compare the name of the target field with the DEFAULT_FIELD_VALUE and returns the final value .
47
23
23,678
private String getValue ( final List < String > attributes , final List < Class < ? > > classes , String value , final String mappedFieldName , final Class < ? > configuredClass , final Class < ? > targetClass ) { String regex = getValue ( value , mappedFieldName ) ; String mappedClassName = configuredClass . getSimpleName ( ) ; String targetClassName = targetClass . getSimpleName ( ) ; /* IF ATTRIBUTES AND CLASSES ARE EMPTY */ if ( attributes . isEmpty ( ) && classes . isEmpty ( ) ) { String targetFieldName = fieldName ( targetClass , regex ) ; if ( ! isNull ( targetFieldName ) ) return targetFieldName ; Error . mapping ( mappedFieldName , mappedClassName , regex , targetClassName ) ; } /* IF ATTRIBUTES IS EMPTY AND CLASSES NOT */ if ( attributes . isEmpty ( ) && ! classes . isEmpty ( ) ) { if ( classes . contains ( targetClass ) ) { String targetFieldName = fieldName ( targetClass , regex ) ; if ( ! isNull ( targetFieldName ) ) return targetFieldName ; } Error . mapping ( mappedFieldName , mappedClassName , regex , targetClassName ) ; } /* IF ATTRIBUTES AND CLASSES ARE VALUED AND THEY HAVE THE SAME LENGTH */ if ( ! attributes . isEmpty ( ) && ! classes . isEmpty ( ) ) if ( attributes . size ( ) == classes . size ( ) ) if ( classes . contains ( targetClass ) ) { // get the attribute from attributes, positioned at the same index of targetClass in classes String targetClassValue = attributes . get ( classes . indexOf ( targetClass ) ) ; regex = getValue ( targetClassValue , mappedFieldName ) ; String targetFieldName = fieldName ( targetClass , regex ) ; if ( ! isNull ( targetFieldName ) ) return targetFieldName ; Error . mapping ( mappedFieldName , mappedClassName , regex , targetClassName ) ; } else Error . mapping ( mappedFieldName , mappedClassName , targetClassName ) ; else Error . mapping ( mappedFieldName , mappedClassName ) ; /* IF ATTRIBUTES IS FULL AND CLASSES IS EMPTY */ if ( ! attributes . isEmpty ( ) && classes . isEmpty ( ) ) for ( String str : attributes ) { regex = getValue ( str , mappedFieldName ) ; // if exist the target field in targetClass String targetFieldName = fieldName ( targetClass , regex ) ; if ( ! isNull ( targetFieldName ) ) //returns the corresponding name return targetFieldName ; } Error . mapping ( mappedFieldName , configuredClass , targetClass ) ; return "this return is never used" ; }
This method finds the target field name from mapped parameters .
587
11
23,679
public void loadAccessors ( Class < ? > targetClass , MappedField configuredField , MappedField targetField ) { // First checks xml configuration xml . fillMappedField ( configuredClass , configuredField ) . fillMappedField ( targetClass , targetField ) // fill target field with custom methods defined in the configured field . fillOppositeField ( configuredClass , configuredField , targetField ) ; // If no present custom methods in XML, it checks annotations Annotation . fillMappedField ( configuredClass , configuredField ) ; Annotation . fillMappedField ( targetClass , targetField ) ; // fill target field with custom methods defined in the configured field Annotation . fillOppositeField ( configuredClass , configuredField , targetField ) ; }
Fill fields with they custom methods .
157
7
23,680
public List < ConversionMethod > getConversionMethods ( Class < ? > clazz ) { List < ConversionMethod > conversions = new ArrayList < ConversionMethod > ( ) ; Map < String , List < ConversionMethod > > conversionsMap = this . conversionsLoad ( ) ; for ( Class < ? > classToCheck : getAllsuperClasses ( clazz ) ) { List < ConversionMethod > methods = conversionsMap . get ( classToCheck . getName ( ) ) ; if ( methods != null ) conversions . addAll ( methods ) ; } return conversions ; }
Returns the conversions method belonging to clazz .
118
9
23,681
public List < String > getClasses ( ) { List < String > classes = new ArrayList < String > ( ) ; for ( XmlClass xmlClass : xmlJmapper . classes ) classes . ( xmlClass . name ) ; return classes ; }
Returns a list with the classes names presents in xml mapping file .
54
13
23,682
public XML write ( ) { try { FilesManager . write ( xmlJmapper , xmlPath ) ; } catch ( IOException e ) { JmapperLog . error ( e ) ; } return this ; }
Writes the xml mapping file starting from xmlJmapper object .
45
14
23,683
public XML deleteClass ( Class < ? > aClass ) { boolean isRemoved = xmlJmapper . classes . remove ( new XmlClass ( aClass . getName ( ) ) ) ; if ( ! isRemoved ) Error . xmlClassInexistent ( this . xmlPath , aClass ) ; return this ; }
This method remove a specific Class from Xml Configuration File
68
11
23,684
public XML addGlobal ( Class < ? > aClass , Global global ) { checksGlobalAbsence ( aClass ) ; findXmlClass ( aClass ) . global = Converter . toXmlGlobal ( global ) ; return this ; }
This method adds the global to an existing Class .
51
10
23,685
public XML deleteGlobal ( Class < ? > aClass ) { checksGlobalExistence ( aClass ) ; XmlClass xmlClass = findXmlClass ( aClass ) ; if ( isEmpty ( xmlClass . attributes ) ) deleteClass ( aClass ) ; else xmlClass . global = null ; return this ; }
This method deletes the global to an existing Class .
67
11
23,686
public XML addAttributes ( Class < ? > aClass , Attribute [ ] attributes ) { checksAttributesExistence ( aClass , attributes ) ; for ( Attribute attribute : attributes ) { if ( attributeExists ( aClass , attribute ) ) Error . xmlAttributeExistent ( this . xmlPath , attribute , aClass ) ; findXmlClass ( aClass ) . attributes . add ( Converter . toXmlAttribute ( attribute ) ) ; } return this ; }
This method adds the attributes to an existing Class .
99
10
23,687
public XML deleteAttributes ( Class < ? > aClass , String [ ] attributes ) { checksAttributesExistence ( aClass , attributes ) ; if ( isEmpty ( findXmlClass ( aClass ) . attributes ) || findXmlClass ( aClass ) . attributes . size ( ) <= 1 ) Error . xmlWrongMethod ( aClass ) ; for ( String attributeName : attributes ) { XmlAttribute attribute = null ; for ( XmlAttribute xmlAttribute : findXmlClass ( aClass ) . attributes ) if ( xmlAttribute . name . equals ( attributeName ) ) attribute = xmlAttribute ; if ( attribute == null ) Error . xmlAttributeInexistent ( this . xmlPath , attributeName , aClass ) ; findXmlClass ( aClass ) . attributes . remove ( attribute ) ; } return this ; }
This method deletes the attributes to an existing Class .
174
11
23,688
private XML addClass ( Class < ? > aClass ) { xmlJmapper . classes . add ( Converter . toXmlClass ( aClass ) ) ; return this ; }
Adds an annotated Class to xmlJmapper structure .
39
12
23,689
private XML checksClassAbsence ( Class < ? > aClass ) { if ( classExists ( aClass ) ) Error . xmlClassExistent ( this . xmlPath , aClass ) ; return this ; }
Throws an exception if the class exist .
45
9
23,690
private boolean classExists ( Class < ? > aClass ) { if ( xmlJmapper . classes == null ) return false ; return findXmlClass ( aClass ) != null ? true : false ; }
verifies that this class exist in Xml Configuration File .
45
12
23,691
private boolean attributeExists ( Class < ? > aClass , Attribute attribute ) { if ( ! classExists ( aClass ) ) return false ; for ( XmlAttribute xmlAttribute : findXmlClass ( aClass ) . attributes ) if ( xmlAttribute . name . equals ( attribute . getName ( ) ) ) return true ; return false ; }
This method returns true if the attribute exist in the Class given in input returns false otherwise .
75
18
23,692
private XmlClass findXmlClass ( Class < ? > aClass ) { for ( XmlClass xmlClass : xmlJmapper . classes ) if ( xmlClass . name . equals ( aClass . getName ( ) ) ) return xmlClass ; return null ; }
Finds the Class given in input in the xml mapping file and returns a XmlClass instance if exist null otherwise .
58
24
23,693
public boolean isMapped ( Class < ? > classToCheck ) { return ! isNull ( loadGlobals ( ) . get ( classToCheck . getName ( ) ) ) || ! isEmpty ( loadAttributes ( ) . get ( classToCheck . getName ( ) ) ) ; }
Returns true if the class is configured in xml false otherwise .
63
12
23,694
public XML fillMappedField ( Class < ? > configuredClass , MappedField configuredField ) { Attribute attribute = getGlobalAttribute ( configuredField , configuredClass ) ; if ( isNull ( attribute ) ) attribute = getAttribute ( configuredField , configuredClass ) ; if ( ! isNull ( attribute ) ) { if ( isEmpty ( configuredField . getMethod ( ) ) ) configuredField . getMethod ( attribute . getGet ( ) ) ; if ( isEmpty ( configuredField . setMethod ( ) ) ) configuredField . setMethod ( attribute . getSet ( ) ) ; } return this ; }
Enrich configuredField with get and set define in xml configuration .
127
13
23,695
public XML fillOppositeField ( Class < ? > configuredClass , MappedField configuredField , MappedField targetField ) { Attribute attribute = null ; Global global = loadGlobals ( ) . get ( configuredClass . getName ( ) ) ; if ( ! isNull ( global ) ) { String value = global . getValue ( ) ; if ( ! isEmpty ( value ) && value . equals ( targetField . getValue ( ) . getName ( ) ) ) { String get = global . getGet ( ) ; String set = global . getSet ( ) ; if ( ! isNull ( get ) || ! isNull ( set ) ) attribute = new Attribute ( null , new Value ( global . getValue ( ) , get , set ) ) ; } } if ( isNull ( attribute ) ) attribute = getAttribute ( configuredField , configuredClass ) ; if ( ! isNull ( attribute ) ) { Value value = attribute . getValue ( ) ; // verifies value if ( ! isNull ( value ) ) if ( targetField . getValue ( ) . getName ( ) . equals ( value . getName ( ) ) ) { if ( isEmpty ( targetField . getMethod ( ) ) ) targetField . getMethod ( value . getGet ( ) ) ; if ( isEmpty ( targetField . setMethod ( ) ) ) targetField . setMethod ( value . getSet ( ) ) ; } SimplyAttribute [ ] attributes = attribute . getAttributes ( ) ; // verifies attributes if ( ! isNull ( attributes ) ) for ( SimplyAttribute targetAttribute : attributes ) if ( targetField . getValue ( ) . getName ( ) . equals ( targetAttribute . getName ( ) ) ) { if ( isEmpty ( targetField . getMethod ( ) ) ) targetField . getMethod ( targetAttribute . getGet ( ) ) ; if ( isEmpty ( targetField . setMethod ( ) ) ) targetField . setMethod ( targetAttribute . getSet ( ) ) ; } } return this ; }
Enrich targetField with get and set define in xml configuration .
426
13
23,696
public static boolean safeNavigationOperatorDefined ( String nestedFieldName ) { if ( nestedFieldName . contains ( SAFE_NAVIGATION_OPERATOR ) ) if ( ! nestedFieldName . startsWith ( SAFE_NAVIGATION_OPERATOR ) ) //TODO standardizzare exception throw new MappingException ( "Safe navigation operator must be the first symbol after dot notation" ) ; else return true ; return false ; }
It checks the presence of the elvis operator and how it is used .
96
15
23,697
private static MappedField checkGetAccessor ( XML xml , Class < ? > aClass , Field nestedField ) { MappedField field = new MappedField ( nestedField ) ; xml . fillMappedField ( aClass , field ) ; Annotation . fillMappedField ( aClass , field ) ; verifyGetterMethods ( aClass , field ) ; return field ; }
Checks only get accessor of this field .
81
10
23,698
private static MappedField checkAccessors ( XML xml , Class < ? > aClass , Field nestedField ) { MappedField field = checkGetAccessor ( xml , aClass , nestedField ) ; verifySetterMethods ( aClass , field ) ; return field ; }
Checks get and set accessors of this field .
58
11
23,699
public static NestedMappingInfo loadNestedMappingInformation ( XML xml , Class < ? > targetClass , String nestedMappingPath , Class < ? > sourceClass , Class < ? > destinationClass , Field configuredField ) { boolean isSourceClass = targetClass == sourceClass ; NestedMappingInfo info = new NestedMappingInfo ( isSourceClass ) ; info . setConfiguredClass ( isSourceClass ? destinationClass : sourceClass ) ; info . setConfiguredField ( configuredField ) ; try { Class < ? > nestedClass = targetClass ; String [ ] nestedFields = nestedFields ( nestedMappingPath ) ; Field field = null ; for ( int i = 0 ; i < nestedFields . length ; i ++ ) { String nestedFieldName = nestedFields [ i ] ; boolean elvisOperatorDefined = false ; // the safe navigation operator is not valid for the last field if ( i < nestedFields . length - 1 ) { String nextNestedFieldName = nestedFields [ i + 1 ] ; elvisOperatorDefined = safeNavigationOperatorDefined ( nextNestedFieldName ) ; } // name filtering nestedFieldName = safeNavigationOperatorFilter ( nestedFieldName ) ; field = retrieveField ( nestedClass , nestedFieldName ) ; if ( isNull ( field ) ) Error . inexistentField ( nestedFieldName , nestedClass . getSimpleName ( ) ) ; // verifies if is exists a get method for this nested field // in case of nested mapping relative to source, only get methods will be checked // in case of nested mapping relative to destination, get and set methods will be checked MappedField nestedField = isSourceClass ? checkGetAccessor ( xml , nestedClass , field ) //TODO Nested Mapping -> in caso di avoidSet qui potremmo avere un problema : checkAccessors ( xml , nestedClass , field ) ; // storage information relating to the piece of path info . addNestedField ( new NestedMappedField ( nestedField , nestedClass , elvisOperatorDefined ) ) ; nestedClass = field . getType ( ) ; } } catch ( MappingException e ) { InvalidNestedMappingException exception = new InvalidNestedMappingException ( nestedMappingPath ) ; exception . getMessages ( ) . put ( InvalidNestedMappingException . FIELD , e . getMessage ( ) ) ; throw exception ; } return info ; }
This method returns a bean with nested mapping information .
528
10