signature: public class ToDataFieldResolveClassByGemFireProcessor { public String process ( XProperty field ) { } }

implementation: String fieldName = field . getName ( ) ; String getter = "get" + CodeGenUtils . firstLetterToUpperCase ( fieldName ) + "()" ; String allowJavaSerialization = Boolean . toString ( Configuration . get ( ) . isJavaSerializationEnabled ( ) ) ; return "if (concrete." + getter + " == null) {\n" + tab ( "out.writeByte(0);\n" ) + "} else {\n" + tab ( "out.writeByte(1);\n" ) + tab ( "com.gemstone.gemfire.DataSerializer.writeObject(concrete." + getter + ", out, " + allowJavaSerialization + ");\n" ) + "}\n" ;


signature:
public class GetKeysFunction { /** * todo : how to customize this parameter . also it exists in regioninfofunction . ugly . */
@ Override public void execute ( FunctionContext functionContext ) { } }

implementation:
Map < String , Object > args = ( HashMap ) functionContext . getArguments ( ) ; String regionName = ( String ) args . get ( "regionName" ) ; Region region = CacheFactory . getAnyInstance ( ) . getRegion ( regionName ) ; if ( region == null ) { functionContext . getResultSender ( ) . lastResult ( new HashSet ( ) ) ; return ; } int bucket = 0 ; if ( PartitionRegionHelper . isPartitionedRegion ( region ) ) { bucket = ( Integer ) args . get ( "bucket" ) ; // todo : NPE if actual region is different from parameter ( replicate vs partition )
PartitionedRegion pr = ( PartitionedRegion ) region ; Set keys = new HashSet ( ) ; if ( pr . getDataStore ( ) . getAllLocalPrimaryBucketIds ( ) . contains ( bucket ) ) { try { keys . addAll ( pr . getDataStore ( ) . getKeysLocally ( bucket ) ) ; } catch ( Exception e ) { throw new RuntimeException ( "error getting local keys for bucket " + bucket , e ) ; } } functionContext . getResultSender ( ) . lastResult ( ( HashSet ) keys ) ; return ; } // todo : it ' s ugly . better : to ask a particular batch of keys ( between oldBatch upper bound and nextBatch lower bound )
Set keys = region . keySet ( ) ; Iterator iterator = keys . iterator ( ) ; Set keysBatch = new HashSet ( BATCH_SIZE ) ; while ( iterator . hasNext ( ) ) { keysBatch . add ( iterator . next ( ) ) ; if ( ( keysBatch . size ( ) + 1 ) % BATCH_SIZE == 0 ) { functionContext . getResultSender ( ) . sendResult ( ( HashSet ) keysBatch ) ; keysBatch = new HashSet ( BATCH_SIZE ) ; } } functionContext . getResultSender ( ) . lastResult ( ( HashSet ) keysBatch ) ;


signature:
public class AbstractStringRenderer { /** * { @ inheritDoc } */
@ Override public final String render ( final RenderConfiguration configuration , final Object entity ) { } }

implementation:
// Check sanity
if ( configuration == null ) { throw new IllegalArgumentException ( "Cannot handle null 'configuration' argument." ) ; } if ( entity == null ) { throw new IllegalArgumentException ( "Cannot handle null 'entity' argument." ) ; } if ( ! accept ( entity ) ) { throw new IllegalArgumentException ( "Entity of type [" + entity . getClass ( ) . getName ( ) + "] was not accepted for rendering. Only [" + acceptedType . getName ( ) + "] types can be rendered by this " + getClass ( ) . getSimpleName ( ) + " renderer." ) ; } // Find out the combination of newline and ' ; ' which should be emitted after rendering .
String epilogue = "" ; if ( entity instanceof Subgraph ) { epilogue = configuration . getNewline ( ) ; } else if ( entity instanceof Statement ) { epilogue = " ;" + configuration . getNewline ( ) ; } // All Done .
final T castEntity = acceptedType . cast ( entity ) ; return doRender ( configuration , castEntity ) + epilogue ;


signature:
public class AbstractStringRenderer { /** * { @ inheritDoc } */
@ Override public boolean accept ( final Object entity ) { } }

implementation: return entity != null && acceptedType . isAssignableFrom ( entity . getClass ( ) ) ;


signature:
public class ReflectionUtils { /** * Set the property identified by name to the provided value .
 * @ param target
 * @ param name
 * @ param value
 * @ return true on success , false if property wasn ' t found . */
public static boolean setProperty ( Object target , String name , Object value ) { } }

implementation: try { for ( PropertyDescriptor pd : Introspector . getBeanInfo ( target . getClass ( ) ) . getPropertyDescriptors ( ) ) { if ( pd . getWriteMethod ( ) != null && pd . getName ( ) . equals ( name ) ) { pd . getWriteMethod ( ) . invoke ( target , value ) ; return true ; } } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } return false ;


signature:
public class ReflectionUtils { /** * Set the field identified by name to the given value .
 * @ param target
 * @ param name
 * @ param value
 * @ return true on success , false if field wasn ' t found . */
public static boolean setField ( Object target , String name , Object value ) { } }

implementation: try { Field field = target . getClass ( ) . getDeclaredField ( name ) ; field . setAccessible ( true ) ; field . set ( target , value ) ; return true ; } catch ( NoSuchFieldException e ) { return false ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class ReflectionUtils { /** * Get all methods on the given class that are annotated with the given annotation type .
 * @ param targetClass
 * @ param annotationType
 * @ return */
public static List < Method > getAnnotatedMethods ( Class targetClass , Class < ? extends Annotation > annotationType ) { } }

implementation: List < Method > annotatedMethods = new ArrayList < Method > ( ) ; for ( Method method : targetClass . getDeclaredMethods ( ) ) { if ( method . isAnnotationPresent ( annotationType ) ) { annotatedMethods . add ( method ) ; } } return annotatedMethods ;


signature:
public class ReflectionUtils { /** * Invoke the given method on the given target using the given arguments .
 * Allows to call private and protected methods .
 * @ throws RuntimeException if method could not be invoked .
 * @ param target
 * @ param method
 * @ param arguments */
public static void invokeMethod ( Object target , Method method , Object ... arguments ) { } }

implementation:
method . setAccessible ( true ) ; // so we can call private and protected methods too
try { method . invoke ( target , arguments ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class ReflectionUtils { /** * Create an empty object of the given class .
 * @ param clazz
 * @ param constructorArgs arguments to pass to the matching constructor
 * @ param < T >
 * @ return */
public static < T > T createObject ( Class < T > clazz , Object ... constructorArgs ) { } }

implementation: if ( constructorArgs == null ) return createObject ( clazz ) ; T object ; Class [ ] parameterTypes = new Class [ constructorArgs . length ] ; for ( int i = 0 ; i < constructorArgs . length ; i ++ ) { parameterTypes [ i ] = constructorArgs [ i ] . getClass ( ) ; } try { Constructor ctor = clazz . getConstructor ( parameterTypes ) ; object = ( T ) ctor . newInstance ( constructorArgs ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } return object ;


signature:
public class ReflectionUtils { /** * Create an empty object of the given class .
 * @ throws RuntimeException if object could not be created .
 * @ param clazz
 * @ param < T >
 * @ return */
public static < T > T createObject ( Class < T > clazz ) { } }

implementation: T object ; try { object = clazz . newInstance ( ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } return object ;


signature:
public class ServerTemplate { /** * Server entry point .
 * @ param args
 * of type String [ ] */
public static void main ( String [ ] args ) throws Exception { } }

implementation: if ( args . length > 0 ) { loadClasses ( args [ 0 ] ) ; } startCacheServer ( ) ; ConsoleUtils . waitForEnter ( JavaProcessLauncher . PROCESS_STARTUP_COMPLETED ) ; stopCacheServer ( ) ;


signature:
public class CheckstyleReportGenerator { /** * Get the value of the specified attribute from the Checkstyle configuration .
 * If parentConfigurations is non - null and non - empty , the parent
 * configurations are searched if the attribute cannot be found in the
 * current configuration . If the attribute is still not found , the
 * specified default value will be returned .
 * @ param config The current Checkstyle configuration
 * @ param parentConfiguration The configuration of the parent of the current configuration
 * @ param attributeName The name of the attribute
 * @ param defaultValue The default value to use if the attribute cannot be found in any configuration
 * @ return The value of the specified attribute */
private String getConfigAttribute ( Configuration config , ChainedItem < Configuration > parentConfiguration , String attributeName , String defaultValue ) { } }

implementation:
String ret ; try { ret = config . getAttribute ( attributeName ) ; } catch ( CheckstyleException e ) { // Try to find the attribute in a parent , if there are any
if ( parentConfiguration != null ) { ret = getConfigAttribute ( parentConfiguration . value , parentConfiguration . parent , attributeName , defaultValue ) ; } else { ret = defaultValue ; } } return ret ;


signature:
public class CheckstyleReportGenerator { /** * Create the rules summary section of the report .
 * @ param results The results to summarize */
private void doRulesSummary ( CheckstyleResults results ) { } }

implementation:
if ( checkstyleConfig == null ) { return ; } sink . section1 ( ) ; sink . sectionTitle1 ( ) ; sink . text ( bundle . getString ( "report.checkstyle.rules" ) ) ; sink . sectionTitle1_ ( ) ; sink . table ( ) ; sink . tableRow ( ) ; sink . tableHeaderCell ( ) ; sink . text ( bundle . getString ( "report.checkstyle.rule.category" ) ) ; sink . tableHeaderCell_ ( ) ; sink . tableHeaderCell ( ) ; sink . text ( bundle . getString ( "report.checkstyle.rule" ) ) ; sink . tableHeaderCell_ ( ) ; sink . tableHeaderCell ( ) ; sink . text ( bundle . getString ( "report.checkstyle.violations" ) ) ; sink . tableHeaderCell_ ( ) ; sink . tableHeaderCell ( ) ; sink . text ( bundle . getString ( "report.checkstyle.column.severity" ) ) ; sink . tableHeaderCell_ ( ) ; sink . tableRow_ ( ) ; // Top level should be the checker .
if ( "checker" . equalsIgnoreCase ( checkstyleConfig . getName ( ) ) ) { String category = null ; for ( ConfReference ref : sortConfiguration ( results ) ) { doRuleRow ( ref , results , category ) ; category = ref . category ; } } else { sink . tableRow ( ) ; sink . tableCell ( ) ; sink . text ( bundle . getString ( "report.checkstyle.norule" ) ) ; sink . tableCell_ ( ) ; sink . tableRow_ ( ) ; } sink . table_ ( ) ; sink . section1_ ( ) ;


signature:
public class CheckstyleReportGenerator { /** * Create a summary for one Checkstyle rule .
 * @ param ref The configuration reference for the row
 * @ param results The results to summarize
 * @ param previousCategory The previous row ' s category */
private void doRuleRow ( ConfReference ref , CheckstyleResults results , String previousCategory ) { } }

implementation:
Configuration checkerConfig = ref . configuration ; ChainedItem < Configuration > parentConfiguration = ref . parentConfiguration ; String ruleName = checkerConfig . getName ( ) ; sink . tableRow ( ) ; // column 1 : rule category
sink . tableCell ( ) ; String category = ref . category ; if ( ! category . equals ( previousCategory ) ) { sink . text ( category ) ; } sink . tableCell_ ( ) ; // column 2 : Rule name + configured attributes
sink . tableCell ( ) ; if ( ! "extension" . equals ( category ) ) { sink . link ( "http://checkstyle.sourceforge.net/config_" + category + ".html#" + ruleName ) ; sink . text ( ruleName ) ; sink . link_ ( ) ; } else { sink . text ( ruleName ) ; } List < String > attribnames = new ArrayList < > ( Arrays . asList ( checkerConfig . getAttributeNames ( ) ) ) ; attribnames . remove ( "severity" ) ; // special value ( deserves unique column )
if ( ! attribnames . isEmpty ( ) ) { sink . list ( ) ; for ( String name : attribnames ) { sink . listItem ( ) ; sink . text ( name ) ; String value = getConfigAttribute ( checkerConfig , null , name , "" ) ; // special case , Header . header and RegexpHeader . header
if ( "header" . equals ( name ) && ( "Header" . equals ( ruleName ) || "RegexpHeader" . equals ( ruleName ) ) ) { String [ ] lines = StringUtils . split ( value , "\\n" ) ; int linenum = 1 ; for ( String line : lines ) { sink . lineBreak ( ) ; sink . rawText ( "" ) ; sink . text ( linenum + ":" ) ; sink . rawText ( "" ) ; sink . nonBreakingSpace ( ) ; sink . monospaced ( ) ; sink . text ( line ) ; sink . monospaced_ ( ) ; linenum ++ ; } } else if ( "headerFile" . equals ( name ) && "RegexpHeader" . equals ( ruleName ) ) { sink . text ( ": " ) ; sink . monospaced ( ) ; sink . text ( "\"" ) ; if ( basedir != null ) { // Make the headerFile value relative to $ { basedir }
String path = siteTool . getRelativePath ( value , basedir . getAbsolutePath ( ) ) ; sink . text ( path . replace ( '\\' , '/' ) ) ; } else { sink . text ( value ) ; } sink . text ( "\"" ) ; sink . monospaced_ ( ) ; } else { sink . text ( ": " ) ; sink . monospaced ( ) ; sink . text ( "\"" ) ; sink . text ( value ) ; sink . text ( "\"" ) ; sink . monospaced_ ( ) ; } sink . listItem_ ( ) ; } sink . list_ ( ) ; } sink . tableCell_ ( ) ; // column 3 : rule violation count
sink . tableCell ( ) ; sink . text ( String . valueOf ( ref . violations ) ) ; sink . tableCell_ ( ) ; // column 4 : severity
sink . tableCell ( ) ; // Grab the severity from the rule configuration , this time use error as default value
// Also pass along all parent configurations , so that we can try to find the severity there
String severity = getConfigAttribute ( checkerConfig , parentConfiguration , "severity" , "error" ) ; iconTool . iconSeverity ( severity , IconTool . TEXT_SIMPLE ) ; sink . tableCell_ ( ) ; sink . tableRow_ ( ) ;


signature:
public class CheckstyleReportGenerator { /** * Check if a violation matches a rule .
 * @ param event the violation to check
 * @ param ruleName The name of the rule
 * @ param expectedMessage A message that , if it ' s not null , will be matched to the message from the violation
 * @ param expectedSeverity A severity that , if it ' s not null , will be matched to the severity from the violation
 * @ return The number of rule violations */
public boolean matchRule ( AuditEvent event , String ruleName , String expectedMessage , String expectedSeverity ) { } }

implementation:
if ( ! ruleName . equals ( RuleUtil . getName ( event ) ) ) { return false ; } // check message too , for those that have a specific one .
// like GenericIllegalRegexp and Regexp
if ( expectedMessage != null ) { // event . getMessage ( ) uses java . text . MessageFormat in its implementation .
// Read MessageFormat Javadoc about single quote :
// http : / / java . sun . com / j2se / 1.4.2 / docs / api / java / text / MessageFormat . html
String msgWithoutSingleQuote = StringUtils . replace ( expectedMessage , "'" , "" ) ; return expectedMessage . equals ( event . getMessage ( ) ) || msgWithoutSingleQuote . equals ( event . getMessage ( ) ) ; } // Check the severity . This helps to distinguish between
// different configurations for the same rule , where each
// configuration has a different severity , like JavadocMetod .
// See also http : / / jira . codehaus . org / browse / MCHECKSTYLE - 41
if ( expectedSeverity != null ) { return expectedSeverity . equals ( event . getSeverityLevel ( ) . getName ( ) ) ; } return true ;


signature:
public class CodeGenUtils { /** * < p > Integer [ ] [ ] . class - > " Integer [ ] [ ] "
 * < p > int [ ] [ ] . class - > " int [ ] [ ] "
 * < p > Naive : Integer [ ] [ ] . class . getName ( ) - > " [ [ Ljava . lang . Integer ; "
 * < p > Naive : int [ ] [ ] . class . getName ( ) - > " [ [ LI ; " */
public static String className ( Class < ? > clazz ) { } }

implementation:
// todo : rename
// todo : is that correct algorithm ?
final String naiveName = clazz . getName ( ) ; if ( ! clazz . isArray ( ) ) { // todo : what about enum
return naiveName ; } else { int count = 0 ; String ending = "" ; while ( clazz . isArray ( ) ) { count ++ ; ending += "[]" ; clazz = clazz . getComponentType ( ) ; } if ( clazz . isPrimitive ( ) ) { String primitiveClassName ; if ( clazz == boolean . class ) { primitiveClassName = "boolean" ; } else if ( clazz == byte . class ) { primitiveClassName = "byte" ; } else if ( clazz == char . class ) { primitiveClassName = "char" ; } else if ( clazz == short . class ) { primitiveClassName = "short" ; } else if ( clazz == int . class ) { primitiveClassName = "int" ; } else if ( clazz == long . class ) { primitiveClassName = "long" ; } else if ( clazz == float . class ) { primitiveClassName = "float" ; } else if ( clazz == double . class ) { primitiveClassName = "double" ; } else { throw new RuntimeException ( "Never here! - You try to generate code for Void[]...[]: clazz = " + clazz ) ; } return primitiveClassName + ending ; } else { return naiveName . substring ( count + 1 , naiveName . length ( ) - 1 ) + ending ; } }


signature:
public class GuestNode { /** * Creates the receivedAt key
 * @ param fromClusterName
 * - the name of cluster from which the entry received
 * @ param toClusterName
 * - the name of cluster on which the entry received
 * @ return - the receivedAt key */
private String createReceivedAtKey ( String fromClusterName , String toClusterName ) { } }

implementation: return KEY_PREFIX + fromClusterName + "-" + toClusterName + KEY_POSTFIX_DURATION ;


signature:
public class GuestNode { /** * Initializes the technical region */
private void init ( ) { } }

implementation: try { debug ( "GuestNode#init(): Creating Cache" ) ; ClientCacheFactory clientCacheFactory = new ClientCacheFactory ( ) ; Properties gemfireProperties = PropertiesHelper . filterProperties ( System . getProperties ( ) , GEMFIRE_PREFIX ) ; for ( Object keyObject : gemfireProperties . keySet ( ) ) { String key = ( String ) keyObject ; String value = gemfireProperties . getProperty ( key ) ; String name = key . substring ( GEMFIRE_PREFIX . length ( ) ) ; debug ( "GuestNode#init(): Configuring ClientCacheFactory with key = " + name + ", value = " + value ) ; clientCacheFactory . set ( name , value ) ; } clientCacheFactory . setPoolSubscriptionEnabled ( true ) ; String locators = clustersProperties . getProperty ( localClusterName ) ; String [ ] locatorsArray = locators . split ( "," ) ; for ( String locator : locatorsArray ) { String locatorHost = locator . substring ( 0 , locator . indexOf ( "[" ) ) ; String locatorPortString = locator . substring ( locator . indexOf ( "[" ) + 1 , locator . indexOf ( "]" ) ) ; int locatorPort = Integer . parseInt ( locatorPortString ) ; debug ( "GuestNode#init(): Adding locator to pool: locatorHost = " + locatorHost + ", locatorPort = " + locatorPort ) ; clientCacheFactory . addPoolLocator ( locatorHost , locatorPort ) ; } clientCache = clientCacheFactory . create ( ) ; ClientRegionFactory < String , Long > clientRegionFactory = clientCache . createClientRegionFactory ( ClientRegionShortcut . PROXY ) ; region = clientCache . getRegion ( regionName ) ; debug ( "GuestNode#init(): Get region with name = " + regionName + ": region = " + region ) ; if ( region == null ) { region = clientRegionFactory . create ( regionName ) ; } debug ( "GuestNode#init(): Create region with name = " + regionName + ": region = " + region ) ; } catch ( Throwable t ) { debug ( "GuestNode#init(): Throwable caught with message = " + t . getMessage ( ) , t ) ; }


signature:
public class GuestNode { /** * Wait until the other clients started */
private void waitForStarted ( ) { } }

implementation: debug ( "GuestNode#waitForStarted(): Waiting for other clusters started" ) ; while ( true ) { boolean othersStarted = true ; for ( Object key : clustersProperties . keySet ( ) ) { String clusterName = ( String ) key ; Long startedAt = region . get ( createStartedAtKey ( clusterName ) ) ; debug ( "GuestNode#waitForStarted(): Checking startedAt: startedAt = " + startedAt + ", processingStartedAt = " + processingStartedAt ) ; if ( ( startedAt == null ) || ( startedAt . longValue ( ) < processingStartedAt ) ) { othersStarted = false ; break ; } } if ( othersStarted ) { break ; } try { TimeUnit . MILLISECONDS . sleep ( CHECK_PERIOD ) ; } catch ( InterruptedException e ) { } } debug ( "GuestNode#waitForStarted(): Other clusters started" ) ;


signature:
public class GuestNode { /** * Wait until received all the entries from other clients . Put the
 * receivedAt entries to cache . */
private void waitForSent ( ) { } }

implementation: debug ( "GuestNode#waitForSent(): Waiting for other clusters sent" ) ; while ( true ) { boolean othersSent = true ; Map < String , Long > clusterNameToReceivedAtMap = new HashMap < String , Long > ( ) ; for ( Object key : clustersProperties . keySet ( ) ) { String clusterName = ( String ) key ; if ( localClusterName . equals ( clusterName ) ) { continue ; } Long sentAt = region . get ( createSentAtKey ( clusterName ) ) ; long receivedAt = System . currentTimeMillis ( ) ; if ( ( sentAt != null ) && ( sentAt . longValue ( ) > processingStartedAt ) ) { clusterNameToReceivedAtMap . put ( clusterName , receivedAt ) ; } } for ( Object key : clustersProperties . keySet ( ) ) { String clusterName = ( String ) key ; if ( localClusterName . equals ( clusterName ) ) { continue ; } Long receivedAt = clusterNameToReceivedAtMap . get ( clusterName ) ; if ( receivedAt == null ) { if ( othersSent ) { othersSent = false ; } } else { region . put ( createReceivedAtKey ( clusterName , localClusterName ) , receivedAt ) ; } } if ( othersSent ) { break ; } try { TimeUnit . MILLISECONDS . sleep ( CHECK_PERIOD ) ; } catch ( InterruptedException e ) { } } debug ( "GuestNode#waitForSent(): Other clusters sent" ) ;


signature:
public class GuestNode { /** * Wait until all the clients received all the receivedAt entries . */
private void waitForConnected ( ) { } }

implementation: debug ( "GuestNode#waitForConnected(): Waiting for all the clusters connected" ) ; while ( true ) { boolean connected = true ; for ( Object fromKey : clustersProperties . keySet ( ) ) { String fromClusterName = ( String ) fromKey ; for ( Object toKey : clustersProperties . keySet ( ) ) { String toClusterName = ( String ) toKey ; if ( fromClusterName . equals ( toClusterName ) ) { continue ; } Long receivedAt = region . get ( createReceivedAtKey ( fromClusterName , toClusterName ) ) ; if ( receivedAt == null ) { connected = false ; break ; } } } if ( connected ) { break ; } try { TimeUnit . MILLISECONDS . sleep ( CHECK_PERIOD ) ; } catch ( InterruptedException e ) { } } debug ( "GuestNode#waitForConnected(): All the clusters connected" ) ;


signature:
public class GuestNode { /** * Waits for processing finished .
 * @ param timeout
 * - the timeout in milliseconds
 * @ return - true if the connection process finished successfully , false
 * otherwise */
public boolean waitFor ( long timeout ) { } }

implementation: debug ( "GuestNode#waitFor(long): Waiting for task finish with timeout = " + timeout ) ; ProcessingTask connectionCheckTask = new ProcessingTask ( ) ; Utils . execute ( connectionCheckTask , timeout ) ; boolean connected = connectionCheckTask . isConnected ( ) ; debug ( "GuestNode#waitFor(long): Task finished connected = " + connected ) ; return connected ;


signature:
public class GuestNode { /** * Finalizes work with the guest node */
public void close ( ) { } }

implementation: try { debug ( "GuestNode#close(): Closing the cache" ) ; clientCache . close ( ) ; debug ( "GuestNode#close(): Cache closed = " + clientCache . isClosed ( ) ) ; } catch ( Throwable t ) { debug ( "GuestNode#close(): Throwable caught with message = " + t . getMessage ( ) , t ) ; }


signature:
public class GuestNode { /** * Prints the current state of connections
 * @ param connected */
public void printState ( boolean connected ) { } }

implementation: if ( ! quiet ) { StringBuilder sb = new StringBuilder ( ) ; if ( connected ) { sb . append ( localClusterName ) . append ( " <= " ) ; Iterator < Object > it = clustersProperties . keySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { String clusterName = ( String ) it . next ( ) ; if ( localClusterName . equals ( clusterName ) ) { continue ; } Long sentAt = region . get ( createSentAtKey ( clusterName ) ) ; Long receivedAt = region . get ( createReceivedAtKey ( clusterName , localClusterName ) ) ; long duration = receivedAt - sentAt ; sb . append ( "[" ) . append ( clusterName ) . append ( ", " ) . append ( duration ) . append ( "ms]" ) ; } } else { sb . append ( "Connection process is not finished for " ) . append ( localClusterName ) ; } System . out . println ( sb . toString ( ) ) ; }


signature:
public class GuestNode { /** * Configures and starts the guest node
 * @ param args
 * - the configuration arguments */
public static void main ( String [ ] args ) { } }

implementation: try { if ( args . length != 7 ) { Utils . exitWithFailure ( ) ; } String cluster = args [ 0 ] ; Properties clustersProperties = PropertiesHelper . stringToProperties ( args [ 1 ] ) ; long timeout = Long . parseLong ( args [ 2 ] ) ; String regionName = args [ 3 ] ; boolean debugEnabled = ( "true" . equals ( args [ 4 ] ) ? true : false ) ; boolean quiet = ( "true" . equals ( args [ 5 ] ) ? true : false ) ; long processingStartedAt = Long . parseLong ( args [ 6 ] ) ; GuestNode guestNode = new GuestNode ( cluster , clustersProperties , regionName , debugEnabled , quiet , processingStartedAt ) ; boolean connected = guestNode . waitFor ( timeout ) ; guestNode . printState ( connected ) ; guestNode . close ( ) ; if ( connected ) { Utils . exitWithSuccess ( ) ; } Utils . exitWithFailure ( ) ; } catch ( Throwable t ) { Utils . exitWithFailure ( ) ; }


signature:
public class GuestNode { /** * Prints debug information if the debug is enabled
 * @ param message
 * - the debug message
 * @ param t
 * - the instance of Throwable */
private void debug ( String message , Throwable t ) { } }

implementation: if ( debugEnabled ) { long currentTime = System . currentTimeMillis ( ) ; long timeSinceProcessingStart = currentTime - processingStartedAt ; System . err . println ( timeSinceProcessingStart + " [" + localClusterName + "] " + message ) ; if ( t != null ) { t . printStackTrace ( System . err ) ; } }


signature:
public class AttributeRenderer { /** * { @ inheritDoc } */
@ Override @ SuppressWarnings ( "PMD" ) protected String doRender ( final RenderConfiguration config , final AbstractAttributes entity ) { } }

implementation:
// Collect all non - null properties into a SortedMap using reflection .
final SortedMap < String , String > dotAttributes = new TreeMap < > ( ) ; for ( Class < ? > current = entity . getClass ( ) ; current != null && current != Object . class ; current = current . getSuperclass ( ) ) { for ( Field currentField : current . getDeclaredFields ( ) ) { if ( isConfigurationField ( currentField ) ) { String key = null ; Object value = null ; try { // #1 ) Do we have a non - null value in the Field ?
value = currentField . get ( entity ) ; if ( value == null ) { continue ; } // #2 ) Do we have @ DotProperty annotation on the Field ?
final DotProperty dotPropertyAnnotation = currentField . getAnnotation ( DotProperty . class ) ; if ( dotPropertyAnnotation == null ) { continue ; } // #3 ) Does this field need special treatment ?
if ( dotPropertyAnnotation . specialTreatment ( ) ) { if ( "labelSize" . equals ( currentField . getName ( ) ) && PointOrRectangle . class . equals ( currentField . getType ( ) ) ) { final PointOrRectangle rect = ( PointOrRectangle ) value ; dotAttributes . put ( quote ( "lwidth" ) , BigDecimal . valueOf ( rect . getxOrWidth ( ) ) . toPlainString ( ) ) ; dotAttributes . put ( quote ( "lheight" ) , BigDecimal . valueOf ( rect . getyOrHeight ( ) ) . toPlainString ( ) ) ; // All Done for this Field .
continue ; } } // #4 ) Use the DotProperty " name " attribute , or fallback to the field name .
key = dotPropertyAnnotation . name ( ) ; if ( key . isEmpty ( ) || "##default" . equalsIgnoreCase ( key ) ) { key = currentField . getName ( ) ; } // #5 ) Transform the value if required , and add the key / value pair to the outbound Map .
dotAttributes . put ( key , getDotConfigValueFor ( value ) ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Could not add configuration for field [" + currentField + "] --> [" + key + "] in class [" + entity . getClass ( ) . getSimpleName ( ) + "]" , e ) ; } } } } // Check sanity
if ( dotAttributes . isEmpty ( ) ) { return "" ; } // Synthesize the required attribute List form .
final StringBuilder builder = new StringBuilder ( START_TOKEN ) ; for ( Map . Entry < String , String > current : dotAttributes . entrySet ( ) ) { builder . append ( current . getKey ( ) + SEPARATOR + "\"" + current . getValue ( ) + "\"" + DELIMITER ) ; } // Remove the last delimiter
builder . delete ( builder . length ( ) - DELIMITER . length ( ) , builder . length ( ) ) ; // All Done .
builder . append ( END_TOKEN ) ; return builder . toString ( ) ;


signature:
public class AbstractExecutableFacade { /** * < p > This method should be invoked from within subclasses ' worker methods , to validate that the executable found
 * is actually a GraphViz program . < / p >
 * < p > The method fires the command < b > < code > < i > executableNameOrPath < / i > - V < / code > < / b > , capturing the output to determine
 * if it contains the pattern { @ link # GRAPHVIZ _ EXECUTABLE _ FIRST _ LINE _ CHECK } , in which case it is deemed to be a
 * proper GraphViz executable . For instance , the two executables dot and neato responds as follows : < / p >
 * < ul >
 * < li > < i > dot - V < / i > : < code > dot - graphviz version 2.36.0 ( 20140111.2315 ) < / code > < / li >
 * < li > < i > neato - V < / i > : < code > neato - graphviz version 2.36.0 ( 20140111.2315 ) < / code > < / li >
 * < / ul >
 * @ param rootDoc The non - null RootDoc received from the JavaDoc execution context .
 * @ return { @ link true } if this { @ link AbstractExecutableFacade } is properly initialized and can accept commands . */
protected boolean initialize ( final RootDoc rootDoc ) { } }

implementation:
// #0 ) Don ' t initialize twice , unless required to .
if ( isInitializedOK ) { return true ; } // #1 ) Output the discovery log .
for ( String current : discoveryLog ) { rootDoc . printNotice ( current ) ; } rootDoc . printNotice ( "GraphViz home: " + getHomeDirectory ( ) . getAbsolutePath ( ) ) ; rootDoc . printNotice ( "Executable   : " + getExecutableNameOrPath ( ) ) ; // #2 ) Create a ProcessBuilder which synthesizes a call to the executable and determine its version .
final ProcessBuilder pb = new ProcessBuilder ( getExecutableNameOrPath ( ) , "-V" ) ; pb . redirectErrorStream ( true ) ; if ( homeDirectory != null ) { pb . directory ( homeDirectory ) ; } Process p ; try { // Launch the executable
p = pb . start ( ) ; } catch ( IOException e ) { rootDoc . printWarning ( e . getMessage ( ) ) ; return false ; } try ( BufferedReader in = new BufferedReader ( new InputStreamReader ( p . getInputStream ( ) ) ) ; OutputStream out = p . getOutputStream ( ) ; ) { // We don ' t need to send any more commands to the process , so close the output stream .
out . close ( ) ; // Read all input from the process , searching for the pattern " graphviz " ignoring case .
String line = null ; while ( ( line = in . readLine ( ) ) != null ) { if ( line . matches ( GRAPHVIZ_EXECUTABLE_FIRST_LINE_CHECK ) ) { // We found the expected output from the executable .
rootDoc . printNotice ( "GraphViz Version: " + line ) ; isInitializedOK = true ; return true ; } else { // Unknown output . Printout a warning and die .
rootDoc . printWarning ( "Unknown GraphViz output: " + line ) ; } } // Cache the result .
isInitializedOK = false ; return false ; } catch ( IOException e ) { // Nopes .
rootDoc . printWarning ( "Problem detecting GraphViz: " + e . getMessage ( ) ) ; isInitializedOK = false ; return false ; } finally { for ( ; ; ) { try { p . waitFor ( ) ; break ; } catch ( InterruptedException e ) { // Ignore this
} } }


signature:
public class IdentifierRenderer { /** * { @ inheritDoc } */
@ Override protected String doRender ( final RenderConfiguration config , final Identifier entity ) { } }

implementation: return config . getIndent ( ) + quote ( entity . getId ( ) ) + " = " + quote ( entity . getTargetIdentifier ( ) ) ;


signature:
public class DotFacade { /** * < p > Creates and writes PNG and HTML imagemap files by executing ' dot ' , with the following arguments : < / p >
 * < pre >
 * < code >
 * dot - Tcmapx - o [ outputDir / filename ] . map - Tpng - o [ outputDir / filename ] . png
 * < / code >
 * < / pre >
 * < p > The { @ code diagram } string is fed to the dot process . < / p >
 * @ param rootDoc The active { @ link RootDoc } instance .
 * @ param dotDiagram The diagram source to feed into ' dot ' for rendering .
 * @ param outputDirectory The directory where the result should be sent .
 * @ param filename The filename of the PNG and MAP files generated .
 * @ throws IOException If the files could not be properly generated . */
public void writePngImageAndImageMap ( final RootDoc rootDoc , final String dotDiagram , final File outputDirectory , final String filename ) throws IOException { } }

implementation:
// Check sanity
if ( filename == null || filename . isEmpty ( ) ) { throw new IllegalArgumentException ( "Cannot handle null or empty 'filename' argument." ) ; } if ( rootDoc == null ) { throw new IllegalArgumentException ( "Cannot handle null 'rootDoc' argument." ) ; } // #0 ) Initialize
if ( ! initialize ( rootDoc ) ) { rootDoc . printWarning ( "Could not initialize DotFacade. Aborting writing PNG image and ImageMap files." ) ; } // #1 ) Ensure that the PNG and MAP files can be written to .
final File pngFile = new File ( outputDirectory , filename + ".png" ) ; final File mapFile = new File ( outputDirectory , filename + ".map" ) ; pngFile . delete ( ) ; mapFile . delete ( ) ; // #2 ) Compile the arguments used to launch Graphviz .
final ProcessBuilder pb = new ProcessBuilder ( getExecutableNameOrPath ( ) , "-Tcmapx" , "-o" , mapFile . getAbsolutePath ( ) , "-Tpng" , "-o" , pngFile . getAbsolutePath ( ) ) ; pb . redirectErrorStream ( true ) ; if ( getHomeDirectory ( ) != null ) { pb . directory ( getHomeDirectory ( ) ) ; } // #3 ) Launch Graphviz . Harvest output .
final Process p = pb . start ( ) ; try ( final BufferedReader in = new BufferedReader ( new InputStreamReader ( p . getInputStream ( ) ) ) ; final Writer out = new OutputStreamWriter ( p . getOutputStream ( ) , AbstractExecutableFacade . UTF8_ENCODING ) ) { // Send the diagram to the process , and close the stream after that .
out . write ( dotDiagram ) ; out . close ( ) ; // Got error output ?
String line = null ; while ( ( line = in . readLine ( ) ) != null ) { System . err . println ( line ) ; } } finally { while ( true ) { try { int result = p . waitFor ( ) ; if ( result != 0 ) { throw new IllegalStateException ( "GraphViz exited with a non-zero return value: " + result ) ; } break ; } catch ( InterruptedException e ) { // Ignore
} } }


signature:
public class XClass { /** * Returns properties in " natural " order , i . e . & quot ; ORDER BY VERSION , DECLARING CLASS , NAME & quot ;
 * @ return */
public List < XProperty > getOrderedProperties ( ) { } }

implementation: final List < XProperty > result = Introspector . getProperties ( clazz ) ; Collections . sort ( result , new XProperty . NaturalOrder ( ) ) ; return result ;


signature:
public class XClass { /** * Returns a hash code of class model for specified bean version based on fields that this model contains .
 * @ param version bean version to get metadata hashcode .
 * @ return the hashcode ( 16bits ) */
public short getVersionModelHashCode ( int version ) { } }

implementation: List < XProperty > classFields = getOrderedProperties ( ) ; StringBuilder builder = new StringBuilder ( ) ; for ( XProperty field : classFields ) { if ( version == - 1 || version >= field . getPropertyVersion ( ) ) { builder . append ( field . getType ( ) ) . append ( field . getName ( ) ) ; } } int hashCode = builder . toString ( ) . hashCode ( ) ; return ( short ) ( ( hashCode & 0xFFFF ) ^ ( ( hashCode & 0xFFFF0000 ) >> 16 ) ) ;


signature:
public class PaginatedQuery { /** * Returns a total number of query pages .
 * @ return total number of pages
 * @ throws com . gemstone . gemfire . cache . query . QueryException
 * during query execution */
public int getTotalNumberOfPages ( ) throws QueryException { } }

implementation: prepareResultData ( false ) ; if ( isEmpty ( ) ) { return 1 ; } int total = totalNumberOfEntries / this . pageSize ; if ( totalNumberOfEntries % this . pageSize > 0 ) { total += 1 ; } return total ;


signature:
public class PaginatedQuery { /** * Returns entries for a specified page number . Use getTotalNumberOfPages ( )
 * method to know how many pages this query has .
 * @ param pageNumber
 * number of page to return
 * @ throws com . gemstone . gemfire . cache . query . QueryException
 * during query execution
 * @ return List < V > list of entries */
public List < V > page ( int pageNumber ) throws QueryException { } }

implementation: List < Object > pageKeys = null ; boolean firstTry = true ; while ( pageKeys == null ) { prepareResultData ( ! firstTry ) ; if ( ! pageExists ( pageNumber ) ) { throw new IndexOutOfBoundsException ( "The page " + pageNumber + "does not exists. " + + getTotalNumberOfPages ( ) + " pages available." ) ; } PageKey pageKey = newKey ( pageNumber ) ; pageKeys = paginatedQueryInfoRegion . get ( pageKey ) ; if ( pageKeys == null && firstTry ) { firstTry = false ; } else { break ; } } if ( pageKeys != null ) { return getValues ( pageKeys ) ; } else { throw new RuntimeException ( "Unable to load keys from cache. Too aggressive expiration policy?" ) ; }


signature:
public class PaginatedQuery { /** * Returns values for given keys .
 * @ param entriesKeysForPage
 * of type List < Object >
 * @ return List < V > */
@ SuppressWarnings ( "unchecked" ) private List < V > getValues ( List < Object > entriesKeysForPage ) { } }

implementation: if ( entriesKeysForPage . isEmpty ( ) ) { return Collections . emptyList ( ) ; } Map < Object , V > entriesMap = queryRegion . getAll ( entriesKeysForPage ) ; List < V > entries = new ArrayList < V > ( entriesKeysForPage . size ( ) ) ; for ( Object key : entriesKeysForPage ) { entries . add ( entriesMap . get ( key ) ) ; } return entries ;


signature:
public class PaginatedQuery { /** * Stores paginated query info if it has not been stored yet .
 * @ param force
 * @ throws com . gemstone . gemfire . cache . query . QueryException
 * during query execution */
@ SuppressWarnings ( { } }

implementation: "unchecked" } ) private void prepareResultData ( boolean force ) throws QueryException { if ( this . infoLoaded && ! force ) { return ; } PageKey pageKey = newKey ( PAGE_NUMBER_FOR_GENERAL_INFO ) ; List < Object > queryInfo = null ; if ( ! force ) { queryInfo = paginatedQueryInfoRegion . get ( pageKey ) ; } if ( queryInfo == null ) { Query query = queryService . newQuery ( this . queryString ) ; SelectResults < Object > results = null ; try { results = ( SelectResults < Object > ) query . execute ( pageKey . getQueryParameters ( ) ) ; } catch ( FunctionDomainException e ) { handleException ( e ) ; } catch ( TypeMismatchException e ) { handleException ( e ) ; } catch ( NameResolutionException e ) { handleException ( e ) ; } catch ( QueryInvocationTargetException e ) { handleException ( e ) ; } if ( results . size ( ) > queryLimit ) { this . limitExceeded = true ; this . totalNumberOfEntries = queryLimit ; String msg = "Size of query results has exceeded limit (" + queryLimit + "). Truncated." ; logger . warn ( msg ) ; } else { limitExceeded = false ; this . totalNumberOfEntries = results . size ( ) ; } queryInfo = Arrays . asList ( new Object [ ] { results . size ( ) , limitExceeded } ) ; storePage ( PAGE_NUMBER_FOR_GENERAL_INFO , queryInfo ) ; List < Object > keys = extractKeys ( results ) ; storeResults ( keys ) ; } else { this . totalNumberOfEntries = ( Integer ) queryInfo . get ( 0 ) ; this . limitExceeded = ( Boolean ) queryInfo . get ( 1 ) ; } this . infoLoaded = true ;


signature:
public class PaginatedQuery { /** * Stores paginated query pages and general info .
 * @ param resultKeys
 * of type List < Object > */
private void storeResults ( List < Object > resultKeys ) { } }

implementation: if ( resultKeys . size ( ) > queryLimit ) { resultKeys = resultKeys . subList ( 0 , queryLimit ) ; } int keyNumber = 0 ; int pageNumber = 0 ; List < Object > page = new ArrayList < Object > ( ) ; for ( Object key : resultKeys ) { if ( keyNumber % getPageSize ( ) == 0 && keyNumber != 0 ) { storePage ( ++ pageNumber , page ) ; page . clear ( ) ; } page . add ( key ) ; keyNumber ++ ; } if ( page . size ( ) > 0 || pageNumber == 0 ) { storePage ( ++ pageNumber , page ) ; }


signature:
public class PortRenderer { /** * { @ inheritDoc } */
@ Override protected String doRender ( final RenderConfiguration config , final Port entity ) { } }

implementation:
final String prefix = entity . getId ( ) != null && ! entity . getId ( ) . isEmpty ( ) ? ": " + quote ( entity . getId ( ) ) + " " : "" ; // ALl Done .
return prefix + ": " + entity . getCompassPoint ( ) . getDotToken ( ) ;


signature:
public class PersistableObjectFactory { /** * Create an object with the given attributes .
 * First builds the object , than persists it .
 * @ param attributes
 * @ return */
public T create ( Object ... attributes ) { } }

implementation:
// build
T object = build ( attributes ) ; // excute beforeCreate callback
executeCallbacks ( BeforeFactoryCreate . class , object ) ; // persist
persist ( object ) ; // execute after create callback
executeCallbacks ( AfterFactoryCreate . class , object ) ; // return
return object ;


signature:
public class TagToCategorySortingComparator { /** * Sorting order is preferentially used to sort TagToCategory ' s , or the name of the Tag that
 * the TagToCategory ' s point to are used if both TagToCategory ' s sorting orders are null . */
@ Override public int compare ( final TagToCategory o1 , final TagToCategory o2 ) { } }

implementation: if ( o1 == null && o2 == null ) return 0 ; if ( o1 == null ) return lessThan ; if ( o2 == null ) return greaterThan ; if ( o1 . getSorting ( ) == null && o2 . getSorting ( ) == null ) return compareSecondLevel ( o1 , o2 ) ; if ( o1 . getSorting ( ) == null ) return greaterThan ; if ( o2 . getSorting ( ) == null ) return lessThan ; if ( o1 . getSorting ( ) . equals ( o2 . getSorting ( ) ) ) return compareSecondLevel ( o1 , o2 ) ; return o1 . getSorting ( ) . compareTo ( o2 . getSorting ( ) ) * greaterThan ;


signature:
public class FromDataFieldDateProcessor { /** * todo : LocalGregorianCalendar */
public String process ( XProperty field ) { } }

implementation: String fieldName = field . getName ( ) ; return "if (in.readByte() != 0) {\n" + tab ( "result.set" + firstLetterToUpperCase ( fieldName ) + "(new java.util.Date(in.readLong()));\n" ) + "}\n" ;


signature:
public class AbstractMigrateLocales { /** * Migrates locales from a very early version of PressGang that was using the wrong locale value .
 * @ param preparedStmt
 * @ param localeMap
 * @ throws SQLException */
private void migrateBrokenLocales ( final PreparedStatement preparedStmt , final Map < String , Integer > localeMap ) throws SQLException { } }

implementation: final Integer enUSLocaleID = localeMap . get ( "en-US" ) ; if ( enUSLocaleID != null && enUSLocaleID > 0 ) { migrateBrokenLocale ( preparedStmt , localeMap , "es_US" , enUSLocaleID ) ; migrateBrokenLocale ( preparedStmt , localeMap , "en_AU" , enUSLocaleID ) ; migrateBrokenLocale ( preparedStmt , localeMap , "ar" , enUSLocaleID ) ; migrateBrokenLocale ( preparedStmt , localeMap , "as" , enUSLocaleID ) ; }


signature:
public class TopicUtilities { /** * Recalculate the min hash signature for a topic .
 * @ param topic The topic to generate a signature for
 * @ param minHashXORs The list of XOR values to apply to the hash code
 * @ return true if the minhashes were updated , false otherwise */
public static boolean recalculateMinHash ( final Topic topic , final List < MinHashXOR > minHashXORs ) { } }

implementation: boolean retValue = false ; final Set < MinHash > existingMinHashes = topic . getMinHashes ( ) ; final Map < Integer , Integer > minHashes = getMinHashes ( topic . getTopicXML ( ) , minHashXORs ) ; for ( final Integer funcId : minHashes . keySet ( ) ) { boolean found = false ; for ( final MinHash minHash : existingMinHashes ) { if ( minHash . getMinHashFuncID ( ) . equals ( funcId ) ) { if ( ! minHash . getMinHash ( ) . equals ( minHashes . get ( funcId ) ) ) { minHash . setMinHash ( minHashes . get ( funcId ) ) ; retValue = true ; } found = true ; break ; } } if ( ! found ) { retValue = true ; final MinHash minHash = new MinHash ( ) ; minHash . setMinHashFuncID ( funcId ) ; minHash . setMinHash ( minHashes . get ( funcId ) ) ; topic . addMinHash ( minHash ) ; } } return retValue ;


signature:
public class TopicUtilities { /** * Generate the min hashes
 * @ param xml The content to apply the signature to
 * @ param minHashXORs The list of XOR values to apply to the hash code
 * @ return */
public static Map < Integer , Integer > getMinHashes ( final String xml , final List < MinHashXOR > minHashXORs ) { } }

implementation:
final Map < Integer , Integer > retValue = new HashMap < Integer , Integer > ( ) ; // Clean the XML to remove element names and other useless data
final String cleanedXML = cleanXMLForMinHash ( xml ) ; // the first minhash uses the builtin hashcode only
final Integer baseMinHash = getMinHashInternal ( cleanedXML , null ) ; if ( baseMinHash != null ) { retValue . put ( 0 , baseMinHash ) ; } for ( int funcId = 1 ; funcId < org . jboss . pressgang . ccms . model . constants . Constants . NUM_MIN_HASHES ; ++ funcId ) { boolean foundMinHash = false ; for ( final MinHashXOR minHashXOR : minHashXORs ) { if ( minHashXOR . getMinHashXORFuncId ( ) == funcId ) { final Integer minHash = getMinHashInternal ( cleanedXML , minHashXOR . getMinHashXOR ( ) ) ; if ( minHash != null ) { retValue . put ( funcId , minHash ) ; } foundMinHash = true ; break ; } } if ( ! foundMinHash ) { throw new IllegalStateException ( "Did not find a minhash xor int for function " + funcId ) ; } } return retValue ;


signature:
public class TopicUtilities { /** * Returns the minimum hash of the sentences in an XML file .
 * @ param xml The xml to analyse
 * @ param xor the number to xor the hash against . Null if the standard hashCode ( ) method should be used alone .
 * @ return The minimum hash */
public static Integer getMinHash ( final String xml , final Integer xor ) { } }

implementation: return getMinHashInternal ( cleanXMLForMinHash ( xml ) , xor ) ;


signature:
public class TopicUtilities { /** * Cleans the provided XML by removing element names and other useless data .
 * @ param xml The xml to be cleaned .
 * @ return The cleaned xml . */
protected static String cleanXMLForMinHash ( final String xml ) { } }

implementation:
// Treat null and empty strings the same
final String fixedXML = xml == null ? "" : xml ; String text = null ; try { final Document doc = XMLUtilities . convertStringToDocument ( fixedXML ) ; if ( doc != null ) { text = doc . getDocumentElement ( ) . getTextContent ( ) ; } } catch ( final Exception ex ) { // Do nothing
} // the xml was invalid , so just strip out xml elements manually
if ( text == null ) { text = fixedXML . replaceAll ( "</?.*?/?>" , " " ) ; } return text ;


signature:
public class TopicUtilities { /** * Returns the minimum hash of the sentences in an XML file .
 * @ param cleanedXML The cleaned xml to analyse
 * @ param xor the number to xor the hash against . Null if the standard hashCode ( ) method should be used alone .
 * @ return The minimum hash */
protected static Integer getMinHashInternal ( final String cleanedXML , final Integer xor ) { } }

implementation:
// now generate the minhashes
String [ ] words = cleanedXML . replaceAll ( "\\p{Punct}" , " " ) . split ( "\\s+" ) ; if ( words . length == 0 ) { words = new String [ ] { "" } ; } final List < String > shingles = new ArrayList < String > ( ) ; if ( words . length < SHINGLE_WORD_COUNT ) { final StringBuilder shingle = new StringBuilder ( ) ; for ( int i = 0 ; i < words . length ; ++ i ) { if ( shingle . length ( ) != 0 ) { shingle . append ( " " ) ; } shingle . append ( words [ i ] ) ; } final int hash = shingle . toString ( ) . hashCode ( ) ; if ( xor != null ) { return hash ^ xor ; } else { return hash ; } } else { for ( int i = 0 ; i < words . length - SHINGLE_WORD_COUNT + 1 ; ++ i ) { final StringBuilder shingle = new StringBuilder ( ) ; for ( int j = i ; j < words . length && j < i + SHINGLE_WORD_COUNT ; ++ j ) { if ( shingle . length ( ) != 0 ) { shingle . append ( " " ) ; } shingle . append ( words [ j ] ) ; } shingles . add ( shingle . toString ( ) ) ; } Integer minHash = null ; for ( final String string : shingles ) { final int hash = string . hashCode ( ) ; final int finalHash = xor != null ? hash ^ xor : hash ; if ( minHash == null || finalHash < minHash ) { minHash = finalHash ; } } return minHash ; }


signature:
public class TopicUtilities { /** * Matching the minhash signature of a document relies on a process known as locality sensitive hashing .
 * A good explaination of this process can be found at http : / / infolab . stanford . edu / ~ ullman / mmds / ch3 . pdf .
 * To implement this feature , we need to group the minhash signatures into bands . When two topics share
 * the same minhash in a single band , they are considered a candidate pair for further testing .
 * The documentation above suggests hashing the minhash values that fall into a band , and then comparing
 * these hashed band values to find candidates . Our implementation will defer this to the database by
 * finding the number of topics that have matching minhash values in all rows in a band .
 * The number of rows and bands is calculated such that the threshold is approximately Math . pow ( 1 / b , 1 / r ) . This
 * formula means that increasing the threshold results in an increased number of rows and a decreased number
 * of bands . We get a close approximation by running through a bunch of combinations and seeing what fits best .
 * @ param entityManager The entity manager to use for queries
 * @ param minhashes The minhash signature to match topics to
 * @ param threshold How similar we want two documents to be to be considered a match . This will be forced to a value
 * between 0.6 and 0.9.
 * @ return */
public static List < Integer > getMatchingMinHash ( final EntityManager entityManager , final Map < Integer , Integer > minhashes , final Float threshold ) { } }

implementation:
try { if ( minhashes . size ( ) == 0 ) { /* If the source does not have a minhash signature , force the search query to
 match a non existent topic id so no results are returned . */
return new ArrayList < Integer > ( ) { { add ( - 1 ) ; } } ; } Float fixedThreshold = Constants . MIN_DOCUMENT_SIMILARITY ; if ( threshold > Constants . MAX_DOCUMENT_SIMILARITY ) { fixedThreshold = Constants . MAX_DOCUMENT_SIMILARITY ; } else if ( threshold >= Constants . MIN_DOCUMENT_SIMILARITY ) { fixedThreshold = threshold ; } final CriteriaBuilder criteriaBuilder = entityManager . getCriteriaBuilder ( ) ; final CriteriaQuery < Integer > criteriaQuery = criteriaBuilder . createQuery ( Integer . class ) ; final Root < MinHash > minHashRoot = criteriaQuery . from ( MinHash . class ) ; final Set < Integer > candidates = new HashSet < Integer > ( ) ; /* Note to self - It may be possible to perform these band queries as one big query through something like
 cb . having ( cb . equal ( cb . toInteger ( cb . prod ( minHashRoot . < Integer > get ( " minHashFuncID " ) , 1.0 / lhsRows ) , band ) .
 However , unless lhsRows * bands exactly equals Constants . NUM _ MIN _ HASHES there needs to be some additional
 logic for the last band , which will have less than lhsRows rows in it . */
for ( int band = 0 ; band < Constants . MIN_HASH_BANDS ; ++ band ) { final List < Predicate > rowMatches = new ArrayList < Predicate > ( ) ; for ( int row = band * Constants . MIN_HASH_ROWS ; row < ( band * Constants . MIN_HASH_ROWS ) + Constants . MIN_HASH_ROWS ; ++ row ) { Integer sourceMinHash = null ; if ( minhashes . containsKey ( row ) ) { sourceMinHash = minhashes . get ( row ) ; } else { throw new IllegalArgumentException ( "minhashes did not contain a minhash for function " + row ) ; } rowMatches . add ( criteriaBuilder . and ( criteriaBuilder . equal ( minHashRoot . < Integer > get ( "minHashFuncID" ) , row ) , criteriaBuilder . equal ( minHashRoot . < Integer > get ( "minHash" ) , sourceMinHash ) ) ) ; } final Predicate minHashOrs = criteriaBuilder . or ( rowMatches . toArray ( new Predicate [ ] { } ) ) ; final CriteriaQuery < Integer > query = criteriaQuery . select ( minHashRoot . < Topic > get ( "topic" ) . < Integer > get ( "topicId" ) ) . distinct ( true ) . where ( minHashOrs ) . groupBy ( minHashRoot . < Integer > get ( "topic" ) . < Integer > get ( "topicId" ) ) . having ( criteriaBuilder . equal ( criteriaBuilder . count ( minHashRoot . < Integer > get ( "topic" ) . < Integer > get ( "topicId" ) ) , rowMatches . size ( ) ) ) ; candidates . addAll ( entityManager . createQuery ( query ) . getResultList ( ) ) ; } final List < Integer > matchingTopics = new ArrayList < Integer > ( ) ; if ( candidates . size ( ) != 0 ) { // at this point candidates should now list topic ids that are a potential match to the source topic .
final CriteriaQuery < Topic > topicCQ = criteriaBuilder . createQuery ( Topic . class ) ; final Root < Topic > topicRoot = topicCQ . from ( Topic . class ) ; final CriteriaBuilder . In < Integer > in = criteriaBuilder . in ( topicRoot . < Integer > get ( "topicId" ) ) ; for ( final Integer candidate : candidates ) { in . value ( candidate ) ; } final CriteriaQuery < Topic > topicQuery = topicCQ . select ( topicRoot ) . where ( in ) ; final List < Topic > topics = entityManager . createQuery ( topicQuery ) . getResultList ( ) ; // we now have a list of topics that are possible candidates for a match . Now we compare the minhash values
// to see what the similarity actually is .
for ( final Topic topic : topics ) { int matches = 0 ; for ( final MinHash otherMinHash : topic . getMinHashes ( ) ) { if ( minhashes . containsKey ( otherMinHash . getMinHashFuncID ( ) ) ) { if ( minhashes . get ( otherMinHash . getMinHashFuncID ( ) ) . equals ( otherMinHash . getMinHash ( ) ) ) { ++ matches ; } } else { throw new IllegalArgumentException ( "minhashes did not contain a minhash for function " + otherMinHash . getMinHashFuncID ( ) ) ; } } if ( ( float ) matches / Constants . NUM_MIN_HASHES >= fixedThreshold ) { matchingTopics . add ( topic . getId ( ) ) ; } } if ( matchingTopics . size ( ) != 0 ) { return matchingTopics ; } } return Arrays . asList ( - 1 ) ; } catch ( final Exception ex ) { return null ; }


signature:
public class TopicUtilities { /** * Validate and Fix a topics relationships to ensure that the topics related topics are still matched by the Related Topics
 * themselves .
 * @ param topic The topic to validate and fix the relationships for . */
public static void validateAndFixRelationships ( final Topic topic ) { } }

implementation:
/* remove relationships to this topic in the parent collection */
final ArrayList < TopicToTopic > removeList = new ArrayList < TopicToTopic > ( ) ; for ( final TopicToTopic topicToTopic : topic . getParentTopicToTopics ( ) ) if ( topicToTopic . getRelatedTopic ( ) . getTopicId ( ) . equals ( topic . getTopicId ( ) ) ) removeList . add ( topicToTopic ) ; for ( final TopicToTopic topicToTopic : removeList ) topic . getParentTopicToTopics ( ) . remove ( topicToTopic ) ; /* remove relationships to this topic in the child collection */
final ArrayList < TopicToTopic > removeChildList = new ArrayList < TopicToTopic > ( ) ; for ( final TopicToTopic topicToTopic : topic . getChildTopicToTopics ( ) ) if ( topicToTopic . getMainTopic ( ) . getTopicId ( ) . equals ( topic . getTopicId ( ) ) ) removeChildList . add ( topicToTopic ) ; for ( final TopicToTopic topicToTopic : removeChildList ) topic . getChildTopicToTopics ( ) . remove ( topicToTopic ) ;


signature:
public class TopicUtilities { /** * Set the content hash on the topic .
 * @ param topic The topic to update */
public static void updateContentHash ( final Topic topic ) { } }

implementation: if ( topic . getTopicXML ( ) != null ) { topic . setTopicContentHash ( HashUtilities . generateSHA256 ( topic . getTopicXML ( ) ) . toCharArray ( ) ) ; }


signature:
public class TopicUtilities { /** * Validate and Fix a topics tags so that mutually exclusive tags are enforced and also remove any tags that may have been
 * duplicated .
 * @ param topic The topic to fix the tags for . */
public static void validateAndFixTags ( final Topic topic ) { } }

implementation:
/* * validate the tags that are applied to this topic . generally the gui should enforce these rules , with the exception of
 * the bulk tag apply function */
// Create a collection of Categories mapped to TagToCategories , sorted by the Category sorting order
final TreeMap < Category , ArrayList < TagToCategory > > tagDB = new TreeMap < Category , ArrayList < TagToCategory > > ( Collections . reverseOrder ( ) ) ; for ( final TopicToTag topicToTag : topic . getTopicToTags ( ) ) { final Tag tag = topicToTag . getTag ( ) ; for ( final TagToCategory tagToCategory : tag . getTagToCategories ( ) ) { final Category category = tagToCategory . getCategory ( ) ; if ( ! tagDB . containsKey ( category ) ) tagDB . put ( category , new ArrayList < TagToCategory > ( ) ) ; tagDB . get ( category ) . add ( tagToCategory ) ; } } // now remove conflicting tags
for ( final Category category : tagDB . keySet ( ) ) { /* sort by the tags position in the category */
Collections . sort ( tagDB . get ( category ) , new TagToCategorySortingComparator ( false ) ) ; /* * because of the way we have ordered the tagDB collections , and the ArrayLists it contains , this process will
 * remove those tags that belong to lower priority categories , and lower priority tags in those categories */
final ArrayList < TagToCategory > tagToCategories = tagDB . get ( category ) ; // remove tags in the same mutually exclusive categories
if ( category . isMutuallyExclusive ( ) && tagToCategories . size ( ) > 1 ) { while ( tagToCategories . size ( ) > 1 ) { final TagToCategory tagToCategory = tagToCategories . get ( 1 ) ; /* get the lower priority tag */
final Tag removeTag = tagToCategory . getTag ( ) ; /* remove it from the tagDB collection */
tagToCategories . remove ( tagToCategory ) ; /* and remove it from the tag collection */
final ArrayList < TopicToTag > removeTopicToTagList = new ArrayList < TopicToTag > ( ) ; for ( final TopicToTag topicToTag : topic . getTopicToTags ( ) ) { if ( topicToTag . getTag ( ) . equals ( removeTag ) ) removeTopicToTagList . add ( topicToTag ) ; } for ( final TopicToTag removeTopicToTag : removeTopicToTagList ) { topic . getTopicToTags ( ) . remove ( removeTopicToTag ) ; } } } /* remove tags that are explicitly defined as mutually exclusive */
for ( final TagToCategory tagToCategory : tagToCategories ) { final Tag tag = tagToCategory . getTag ( ) ; for ( final Tag exclusionTag : tag . getExcludedTags ( ) ) { if ( filter ( having ( on ( TopicToTag . class ) . getTag ( ) , equalTo ( tagToCategory . getTag ( ) ) ) , topic . getTopicToTags ( ) ) . size ( ) != 0 && // make
/* * sure that we have not removed this tag already */
filter ( having ( on ( TopicToTag . class ) . getTag ( ) , equalTo ( exclusionTag ) ) , topic . getTopicToTags ( ) ) . size ( ) != 0 && // make
/* * sure the exclusion tag exists */
! exclusionTag . equals ( tagToCategory . getTag ( ) ) ) // make
/* * sure we are not trying to remove ourselves */
{ with ( topic . getTopicToTags ( ) ) . remove ( having ( on ( TopicToTag . class ) . getTag ( ) , equalTo ( exclusionTag ) ) ) ; } } } }


signature:
public class Comparators { /** * Sorts all given ClassDocs into a SortedMap keyed by their respective PackageDocs .
 * @ param classDocs an array of ClassDoc objects .
 * @ return A SortedMap relating all ClassDocs to their respective PackageDoc . */
public static SortedMap < PackageDoc , SortedSet < ClassDoc > > sortClassesPerPackage ( final ClassDoc ... classDocs ) { } }

implementation:
final SortedMap < PackageDoc , SortedSet < ClassDoc > > toReturn = new TreeMap < > ( Comparators . PACKAGE_NAME_COMPARATOR ) ; if ( classDocs != null ) { Arrays . stream ( classDocs ) . forEach ( current -> { // Retrieve ( or create ) the SortedSet of ClassDocs for the current PackageDocs .
final SortedSet < ClassDoc > classDocsForCurrentPackage = toReturn . computeIfAbsent ( current . containingPackage ( ) , k -> new TreeSet < > ( Comparators . CLASS_NAME_COMPARATOR ) ) ; // Add the current ClassDoc to the SortedSet .
classDocsForCurrentPackage . add ( current ) ; } ) ; } // All Done .
return toReturn ;


signature:
public class AbstractEnforcerRule { /** * This is the interface into the rule . This method should throw an exception
 * containing a reason message if the rule fails the check . The plugin will
 * then decide based on the fail flag if it should stop or just log the
 * message as a warning .
 * @ param helper The helper provides access to the log , MavenSession and has
 * helpers to get common components . It is also able to lookup components
 * by class name .
 * @ throws org . apache . maven . enforcer . rule . api . EnforcerRuleException the enforcer rule exception */
@ Override @ SuppressWarnings ( "PMD.PreserveStackTrace" ) public final void execute ( final EnforcerRuleHelper helper ) throws EnforcerRuleException { } }

implementation:
final MavenProject project ; try { project = ( MavenProject ) helper . evaluate ( "${project}" ) ; } catch ( final ExpressionEvaluationException e ) { // Whoops .
final String msg = "Could not acquire MavenProject. (Expression lookup failure for: " + e . getLocalizedMessage ( ) + ")" ; throw new EnforcerRuleException ( msg , e ) ; } // Delegate .
try { performValidation ( project , helper ) ; } catch ( RuleFailureException e ) { // Create a somewhat verbose failure message .
String message = "\n" + "\n#" + "\n# Structure rule failure:" + "\n# " + getShortRuleDescription ( ) + "\n# " + "\n# Message: " + e . getLocalizedMessage ( ) + "\n# " + "\n# Offending project [" + project . getGroupId ( ) + ":" + project . getArtifactId ( ) + ":" + project . getVersion ( ) + "]" + "\n#" ; final Artifact art = e . getOffendingArtifact ( ) ; if ( art != null ) { message += "\n# Offending artifact [" + art . getGroupId ( ) + ":" + art . getArtifactId ( ) + ":" + art . getVersion ( ) + "]" + "\n#" ; } message += "\n" ; // Re - throw for pretty print
throw new EnforcerRuleException ( message ) ; }


signature:
public class AbstractEnforcerRule { /** * Helper method which splices the provided string into a List , separating on commas .
 * @ param toSplice The string to splice
 * @ return A list holding the elements of the spliced string . */
protected static List < String > splice ( final String toSplice ) { } }

implementation: final List < String > toReturn = new ArrayList < String > ( ) ; final StringTokenizer tok = new StringTokenizer ( toSplice , "," , false ) ; while ( tok . hasMoreTokens ( ) ) { toReturn . add ( tok . nextToken ( ) ) ; } return toReturn ;


signature:
public class AbstractEnforcerRule { /** * Helper method which splices the provided String into a List of Pattern instances .
 * @ param toSplice The string to splice
 * @ return A List holding the elements of the spliced string , converted to Patterns
 * @ throws PatternSyntaxException if the { @ code Pattern . compile } method could not compile the provided string . */
protected static List < Pattern > splice2Pattern ( final String toSplice ) throws PatternSyntaxException { } }

implementation: final List < Pattern > toReturn = new ArrayList < Pattern > ( ) ; for ( final String current : splice ( toSplice ) ) { toReturn . add ( Pattern . compile ( current ) ) ; } return toReturn ;


signature:
public class AbstractEnforcerRule { /** * Matches the provided { @ code toMatch } string with all Patterns in the patternList .
 * If one pattern matches , this method returns { @ code true } .
 * @ param toMatch The string to match to every Pattern in the supplied patternList .
 * @ param patternList The List of Patterns to use in matching .
 * @ return { @ code true } if one pattern in the patternList matches , this method returns { @ code true } . */
protected static boolean matches ( final String toMatch , final List < Pattern > patternList ) { } }

implementation: for ( final Pattern current : patternList ) { if ( current . matcher ( toMatch ) . matches ( ) ) { return true ; } } return false ;


signature:
public class AbstractEnforcerRule { /** * Checks if any element within source startsWith the provided toCheck string .
 * @ param source The list of strings which could possibly contain toCheck .
 * @ param toCheck The string to validate .
 * @ return < code > true < / code > if any element within source returns true to
 * < code > toCheck . startsWith ( element ) < / code > . */
protected static boolean containsPrefix ( final List < String > source , final String toCheck ) { } }

implementation:
if ( source != null ) { for ( final String current : source ) { if ( toCheck . startsWith ( current ) ) { return true ; } } } // The prefix was not found within the provided string toCheck .
return false ;


signature:
public class Factory { /** * Get the class of the Factory for the given factoryClass .
 * @ param factoryClass
 * @ return */
private static Class < ? extends ObjectFactory > getFactoryClass ( Class < ? > factoryClass ) { } }

implementation:
if ( factoryPackages . size ( ) == 0 ) throw new IllegalArgumentException ( "No package provide to look for factories." ) ; if ( factoryClasses == null ) { factoryClasses = new HashMap < Class < ? > , Class < ? extends ObjectFactory > > ( ) ; Set < Class < ? extends ObjectFactory > > classes = ReflectionUtils . getSubclassesOf ( ObjectFactory . class , factoryPackages ) ; for ( Class < ? extends ObjectFactory > clazz : classes ) { if ( ! Modifier . isAbstract ( clazz . getModifiers ( ) ) ) { try { Constructor constructor = clazz . getConstructor ( ) ; ObjectFactory factory = ( ObjectFactory ) constructor . newInstance ( ) ; factoryClasses . put ( factory . getFactoryClass ( ) , factory . getClass ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; // should not happen , compiler forces factory classes to implement correct constructor .
} } } } return factoryClasses . get ( factoryClass ) ;


signature:
public class GraphRenderer { /** * { @ inheritDoc } */
@ Override protected String doRender ( final RenderConfiguration config , final Graph graph ) { } }

implementation:
// First , configure the RenderConfiguration for directed - ness .
config . setDirectedGraph ( graph . isDigraph ( ) ) ; // We should use a 3 - step rendering strategy .
final String prologue = config . getIndent ( ) + ( graph . isStrict ( ) ? "strict " : "" ) + ( graph . isDigraph ( ) ? "digraph" : "graph" ) + " " + quote ( graph . getId ( ) ) + " {" + config . getNewline ( ) ; // Render all the statements within the supplied Graph .
// Increase the indentation level to achieve pretty printing .
// Also , note that the render ( ) method appends a NEWLINE to the result .
final String renderedStatements = statementsRenderer . render ( config . cloneAndChangeIndentation ( 1 ) , graph . getStatements ( ) ) ; // Render the epilogue .
final String epilogue = config . getIndent ( ) + "}" ; // All Done .
return prologue + renderedStatements + epilogue ;


signature:
public class EmailService { /** * Sends email with subject and content to receivers specified in property file after key " mail . to "
 * @ param subject - the subject
 * @ param content - the content
 * @ throws MessagingException */
public void send ( String subject , String content ) throws MessagingException { } }

implementation: MimeMessage message = compose ( subject , content , propertiesHelper . getStringProperty ( "mail.to" ) ) ; transport ( message ) ;


signature:
public class EmailService { /** * Sends email with subject and content to receivers specified by argument " to "
 * @ param subject - the subject
 * @ param content - the content
 * @ param to - the CSV list of receivers
 * @ throws MessagingException */
public void send ( String subject , String content , String to ) throws MessagingException { } }

implementation: MimeMessage message = compose ( subject , content , to ) ; transport ( message ) ;


signature:
public class FunctionExecutionThread { /** * Executes the " zero " function using pool for the concrete server .
 * @ param pool
 * - the pool for the concrete server
 * @ return 0 in case of function executed without problems , - 1 otherwise
 * @ throws FunctionException
 * @ throws InterruptedException */
private int executeZeroFunction ( Pool pool ) throws FunctionException , InterruptedException { } }

implementation: int result = - 1 ; ResultCollector < ? , ? > collector = FunctionService . onServer ( pool ) . execute ( new ZeroFunction ( ) ) ; List < ? > functionResult = ( List < ? > ) collector . getResult ( ) ; if ( ( functionResult != null ) && ( functionResult . size ( ) == 1 ) && ( functionResult . get ( 0 ) instanceof Integer ) ) { result = ( Integer ) functionResult . get ( 0 ) ; } return result ;


signature:
public class RightSideEdgeRenderer { /** * < p > Renders this { @ link RightSideEdge } according to the structure : < / p >
 * < pre > edgeop ( node _ id | subgraph ) [ edgeRHS ] < / pre >
 * { @ inheritDoc } */
@ Override protected String doRender ( final RenderConfiguration config , final RightSideEdge entity ) { } }

implementation:
final String prefix = RightSideEdge . getEdgeSeparator ( config . isDirectedGraph ( ) ) + " " + ( entity . getNodeID ( ) != null ? nodeIdRenderer . doRender ( config , entity . getNodeID ( ) ) : entity . getSubgraph ( ) . getId ( ) ) ; // Recurse if this RightSideEdge has a RightSideEdge in turn .
String renderedRightSideOfThisEdge = "" ; if ( entity . getRightSideEdge ( ) != null ) { renderedRightSideOfThisEdge = " " + doRender ( config , entity . getRightSideEdge ( ) ) ; } // All Done .
return prefix + renderedRightSideOfThisEdge ;


signature:
public class BucketOrientedQueryFunction { /** * Executes query using arguments query string and query parameters .
 * @ param functionContext Function context . */
@ Override @ SuppressWarnings ( { } }

implementation: "ThrowableInstanceNeverThrown" , "unchecked" } ) public void execute ( FunctionContext functionContext ) { ResultSender < Serializable > resultSender = functionContext . getResultSender ( ) ; RegionFunctionContext regionFunctionContext = ( RegionFunctionContext ) functionContext ; if ( functionContext . getArguments ( ) == null ) { handleException ( new FunctionException ( "You must specify function argument for query execution." ) , resultSender , null ) ; return ; } if ( ! ( functionContext . getArguments ( ) instanceof BucketOrientedQueryFunctionArgument ) ) { handleException ( new FunctionException ( "Function arguments must be of type " + BucketOrientedQueryFunctionArgument . class . getName ( ) + "." ) , resultSender , null ) ; return ; } BucketOrientedQueryFunctionArgument argument = ( BucketOrientedQueryFunctionArgument ) functionContext . getArguments ( ) ; LocalDataSet localData = ( LocalDataSet ) PartitionRegionHelper . getLocalDataForContext ( regionFunctionContext ) ; QueryService queryService = localData . getCache ( ) . getQueryService ( ) ; String queryStr = argument . getQueryString ( ) ; try { Query query = queryService . newQuery ( queryStr ) ; SelectResults < ? > result = ( SelectResults < ? > ) localData . executeQuery ( ( DefaultQuery ) query , argument . getQueryParameters ( ) , localData . getBucketSet ( ) ) ; resultSender . lastResult ( ( Serializable ) formatResults ( result ) ) ; } catch ( Exception e ) { handleException ( e , resultSender , queryStr ) ; }


signature:
public class BucketOrientedQueryFunction { /** * Handles exceptions during query execution .
 * @ param e Exception to handle .
 * @ param resultSender of type ResultSender < Serializable > */
@ SuppressWarnings ( { } }

implementation: "ThrowableInstanceNeverThrown" } ) private void handleException ( Throwable e , ResultSender < Serializable > resultSender , String queryString ) { logger . error ( "Failed to execute bucket oriented query" + ( queryString != null ? ": " + queryString : "." ) , e ) ; resultSender . sendException ( new FunctionException ( e . getMessage ( ) ) ) ;


signature:
public class BucketOrientedQueryFunction { /** * Formats results of query execution .
 * @ param selectResults of type SelectResults
 * @ return List < Object > */
private List < Object > formatResults ( SelectResults < ? > selectResults ) { } }

implementation: List < Object > results = new ArrayList < Object > ( selectResults . size ( ) + 1 ) ; results . addAll ( selectResults . asList ( ) ) ; results . add ( selectResults . getCollectionType ( ) . getElementType ( ) ) ; return results ;


signature:
public class AbstractErrorMessageContainer { /** * Adds the provided error message to this ErrorMessageContainer .
 * @ param message The message to add , provided that the message is neither null nor empty . */
@ Override public final void addErrorMessage ( final String message ) { } }

implementation:
if ( message == null || "" . equals ( message ) ) { return ; } // All done .
errorMessages . add ( message ) ;


signature:
public class AbstractErrorMessageContainer { /** * Returns the detail message string of this throwable .
 * @ return the detail message string of this < tt > Throwable < / tt > instance ( which may be < tt > null < / tt > ) . */
@ Override public String getMessage ( ) { } }

implementation:
final StringBuilder builder = new StringBuilder ( ) ; for ( final String current : errorMessages ) { builder . append ( current ) . append ( "\n" ) ; } // All done .
return builder . toString ( ) ;


signature:
public class StatementsRenderer { /** * { @ inheritDoc } */
@ Override protected String doRender ( final RenderConfiguration config , final Statements statements ) { } }

implementation:
final StringBuilder builder = new StringBuilder ( config . getIndent ( ) ) ; // #1 ) Render the AttributeStatements plus comment , if they exist .
final boolean hasAttributeStatements = statements . getCommonGraphAttributes ( ) != null || statements . getCommonNodeAttributes ( ) != null || statements . getCommonEdgeAttributes ( ) != null ; if ( hasAttributeStatements ) { // Add the comment first .
builder . append ( commentRenderer . render ( config , statements . getCommonAttributesComment ( ) ) ) ; // Add the attributes in order
if ( statements . getCommonGraphAttributes ( ) != null ) { builder . append ( commonGraphAttributesRenderer . render ( config , statements . getCommonGraphAttributes ( ) ) ) ; } if ( statements . getCommonNodeAttributes ( ) != null ) { builder . append ( commonNodeAttributesRenderer . render ( config , statements . getCommonNodeAttributes ( ) ) ) ; } if ( statements . getCommonEdgeAttributes ( ) != null ) { builder . append ( commonEdgeAttributesRenderer . render ( config , statements . getCommonEdgeAttributes ( ) ) ) ; } } // #2 ) Render the other Statements in order , namely
// Node statements
// Identifier statements
// Edge statements
// Subgraph statements
final List < Node > nodes = statements . getNodes ( ) ; if ( ! nodes . isEmpty ( ) ) { builder . append ( commentRenderer . render ( config , statements . getNodesComment ( ) ) ) ; // Render all Nodes in order .
nodes . forEach ( n -> builder . append ( nodeRenderer . render ( config , n ) ) ) ; } final List < Identifier > identifiers = statements . getIdentifiers ( ) ; if ( ! identifiers . isEmpty ( ) ) { builder . append ( commentRenderer . render ( config , statements . getIdentifiersComment ( ) ) ) ; // Render all Identifiers in order .
identifiers . forEach ( i -> builder . append ( identifierRenderer . render ( config , i ) ) ) ; } final List < Edge > edges = statements . getEdges ( ) ; if ( edges != null && ! edges . isEmpty ( ) ) { builder . append ( commentRenderer . render ( config , statements . getEdgesComment ( ) ) ) ; // Render all Edges in order .
edges . forEach ( i -> builder . append ( edgeRenderer . render ( config , i ) ) ) ; } final List < Subgraph > subgraphs = statements . getSubgraphs ( ) ; if ( ! subgraphs . isEmpty ( ) ) { builder . append ( commentRenderer . render ( config , statements . getSubgraphComment ( ) ) ) ; // Render all Subgraphs in order .
subgraphs . forEach ( s -> builder . append ( subgraphRenderer . render ( config , s ) ) ) ; } // All Done .
return builder . toString ( ) ;


signature:
public class ToDataFieldEnumProcessor { /** * todo : warn if enum contains mutable fields ? */
public String process ( XProperty field ) { } }

implementation: String fieldName = field . getName ( ) ; String getter = "get" + firstLetterToUpperCase ( fieldName ) + "()" ; return "if (concrete." + getter + " == null) {\n" + "    out.writeByte(0);\n" + "} else {\n" + "    out.writeByte(1);\n" + "    out.writeUTF(concrete." + getter + ".getClass().getName());\n" + "    com.gemstone.gemfire.DataSerializer.writeEnum(concrete." + getter + ", out);\n" + "}\n" ;


signature:
public class NodeRenderer { /** * { @ inheritDoc } */
@ Override protected String doRender ( final RenderConfiguration config , final Node node ) { } }

implementation:
// Do we have a non - empty NodeAttributes within the supplied Node ?
// Don ' t add the extra newline after the attributes - so call doRender directly .
final NodeAttributes nodeAttributes = node . getAttributes ( ) ; final String renderedNodeAttributes = attributeRenderer . doRender ( config , nodeAttributes ) ; // All Done .
return config . getIndent ( ) + nodeIdRenderer . doRender ( config , node . getNodeID ( ) ) + ( renderedNodeAttributes . isEmpty ( ) ? "" : " " + renderedNodeAttributes ) ;


signature:
public class Graph { /** * Convenience method to add and return an Edge between a Node / Subgraph and another Node / Subgraph within the
 * immediate Statements in this Graph .
 * @ param fromId The non - empty ID of the Node / Subgraph from which the Edge should originate .
 * @ param toId The non - empty ID of the Node / Subgraph to which the Edge should be directed .
 * @ return The newly created Edge - or { @ code null } if the Edge could not be created . */
public Edge addEdge ( final String fromId , final String toId ) { } }

implementation: return getStatements ( ) . addEdge ( fromId , toId , this ) ;


signature:
public class Utils { /** * Checks if the socket of specified host and port is alive .
 * @ param host
 * - the host .
 * @ param port
 * - the port .
 * @ return - true if alive , false otherwise . */
public static boolean isSocketAlive ( String host , int port ) { } }

implementation:
boolean socketAlive = false ; Socket socket = null ; try { socket = new Socket ( host , port ) ; socketAlive = socket . isConnected ( ) ; } catch ( Throwable t ) { // do nothing
} finally { if ( socket != null ) { try { socket . close ( ) ; } catch ( IOException e ) { // do nothing
} } } return socketAlive ;


signature:
public class Utils { /** * Executes the thread with specified timeout .
 * @ param thread
 * - the thread to execute .
 * @ param timeout
 * - the timeout . */
public static void execute ( Thread thread , long timeout ) { } }

implementation:
thread . start ( ) ; try { thread . join ( timeout ) ; } catch ( InterruptedException e ) { // Should not be interrupted normally .
} if ( thread . isAlive ( ) ) { thread . interrupt ( ) ; }


signature:
public class RightSideEdge { /** * Factory method creating a { @ link RightSideEdge } which terminates in the Node or Subgraph with the supplied ID
 * and within the supplied Graph .
 * @ param id A non - null identifier of a NodeID or Subgraph to which this { @ link RightSideEdge }
 * should go .
 * @ param withinGraph The non - null Graph which is the ultimate parent of the { @ link RightSideEdge } to create .
 * @ return A newly constructed { @ link RightSideEdge } which < strong > is not yet added to any { @ link Edge } or
 * { @ link RightSideEdge } < / strong > - or null if no Node or Subgraph with the supplied id was
 * found in the withinGraph . */
public static RightSideEdge to ( final String id , final Graph withinGraph ) { } }

implementation:
// Check sanity
if ( id == null ) { throw new IllegalArgumentException ( "Cannot handle null 'id' argument." ) ; } if ( withinGraph == null ) { throw new IllegalArgumentException ( "Cannot handle null 'withinGraph' argument." ) ; } // First , assume that the ID is a NodeID .
// final Statements statements = immediateParent . getStatements ( ) ;
final Node node = withinGraph . getStatements ( ) . findNode ( id , true ) ; if ( node != null ) { return new RightSideEdge ( node . getNodeID ( ) ) ; } // Next , assume that the ID is a Subgraph .
final Subgraph subgraph = withinGraph . getStatements ( ) . findSubgraph ( id , true ) ; if ( subgraph != null ) { return new RightSideEdge ( subgraph ) ; } // All Done .
return null ;


signature:
public class DelegatingDoclet { /** * Creates a SimpleDoclet instance by calling a no - argument constructor within the Class of the supplied ClassName .
 * Falls back to { @ link VisualizationDoclet } .
 * @ param className A fully qualified classname of a SimpleDoclet implementation .
 * @ return An instance of the supplied ClassName - or an { @ link VisualizationDoclet } as a fallback . */
public static SimpleDoclet createSimpleDoclet ( final String className ) { } }

implementation:
final String effectiveClassName = className != null && ! className . isEmpty ( ) ? className : VisualizationDoclet . class . getName ( ) ; final ClassLoader [ ] classLoaders = new ClassLoader [ ] { Thread . currentThread ( ) . getContextClassLoader ( ) , DelegatingDoclet . class . getClassLoader ( ) } ; SimpleDoclet toReturn = null ; for ( ClassLoader current : classLoaders ) { try { final Class < ? > loadedClass = current . loadClass ( effectiveClassName ) ; if ( SimpleDoclet . class . isAssignableFrom ( loadedClass ) ) { toReturn = ( SimpleDoclet ) loadedClass . newInstance ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } // All Done .
return toReturn == null ? new VisualizationDoclet ( ) : toReturn ;


signature:
public class Comment { /** * If non - null , adds one or more lines to this comment .
 * Also , { @ link # NEWLINE } strings are removed from each line .
 * @ param lines one or more lines to add to this comment . */
public final void add ( final String ... lines ) { } }

implementation: if ( lines != null ) { for ( String current : lines ) { commentLines . add ( current . replace ( NEWLINE , "" ) ) ; } }


signature:
public class DotDiagramValidator { /** * Validates that the supplied InputStream contains well - formed Graph data , complying to the
 * < a href = " http : / / www . graphviz . org / content / dot - language " > DOT language specification < / a > . If the
 * @ param dotDiagramData A non - null InputStream containing a Graph or DiGraph definition .
 * @ return A { @ link se . jguru . nazgul . tools . visualization . spi . dot . grammars . DotParser . GraphContext } containing the
 * parsed Graph from the parsed DOT data .
 * @ throws DotDiagramSyntaxException if the supplied InputStream contained syntax errors . */
public static DotParser . GraphContext validate ( final InputStream dotDiagramData ) throws DotDiagramSyntaxException { } }

implementation:
// Check sanity
if ( dotDiagramData == null ) { throw new IllegalArgumentException ( "Cannot handle null 'dotDiagramData' argument." ) ; } // Create the parser
final DotLexer lexer = createLexer ( dotDiagramData ) ; final DotParser parser = createParser ( lexer ) ; // Ensure we can harvest all syntax errors .
final DotSyntaxErrorListener errorListener = new DotSyntaxErrorListener ( ) ; parser . addErrorListener ( errorListener ) ; final DotParser . GraphContext toReturn = parser . graph ( ) ; // Check sanity
if ( errorListener . isErrorState ( ) ) { throw new DotDiagramSyntaxException ( errorListener . getErrorDataList ( ) ) ; } // All Done .
return toReturn ;


signature:
public class DotDiagramValidator { /** * Factory method creating a DotLexer from the supplied InputStream , assumed to contain Graphviz / DOT diagram data .
 * @ param dotDiagramData The InputStream containing Graphviz / DOT data , complying
 * with < a href = " http : / / www . graphviz . org / content / dot - language " > DOT language specification < / a > .
 * @ return A { @ link DotLexer } using the supplied InputStream as source of tokens . */
public static DotLexer createLexer ( final InputStream dotDiagramData ) { } }

implementation:
// Check sanity
if ( dotDiagramData == null ) { throw new IllegalArgumentException ( "Cannot handle null 'dotDiagramData' argument." ) ; } try { // All Done .
return new DotLexer ( new ANTLRInputStream ( dotDiagramData ) ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( "Could not create DotLexer" , e ) ; }


signature:
public class DotDiagramValidator { /** * Creates a { @ link DotParser } reading data from the supplied { @ link DotLexer } .
 * @ param lexer A non - null { @ link DotLexer } instance holding all Graphviz / DOT diagram data .
 * @ return a { @ link DotParser } hooked up with a { @ link org . antlr . v4 . runtime . TokenStream } to the
 * supplied { @ link DotLexer } . */
public static DotParser createParser ( final DotLexer lexer ) { } }

implementation:
// Check sanity
if ( lexer == null ) { throw new IllegalArgumentException ( "Cannot handle null 'lexer' argument." ) ; } // All Done .
return new DotParser ( new CommonTokenStream ( lexer ) ) ;


signature:
public class CheckstyleAggregateReport { /** * { @ inheritDoc } */
protected CheckstyleExecutorRequest createRequest ( ) throws MavenReportException { } }

implementation: CheckstyleExecutorRequest request = new CheckstyleExecutorRequest ( ) ; request . setAggregate ( true ) . setReactorProjects ( reactorProjects ) . setConsoleListener ( getConsoleListener ( ) ) . setConsoleOutput ( consoleOutput ) . setExcludes ( excludes ) . setFailsOnError ( failsOnError ) . setIncludes ( includes ) . setIncludeResources ( includeResources ) . setIncludeTestResources ( includeTestResources ) . setResourceIncludes ( resourceIncludes ) . setResourceExcludes ( resourceExcludes ) . setIncludeTestSourceDirectory ( includeTestSourceDirectory ) . setListener ( getListener ( ) ) . setProject ( project ) . setSourceDirectories ( getSourceDirectories ( ) ) . setResources ( resources ) . setTestResources ( testResources ) . setStringOutputStream ( stringOutputStream ) . setSuppressionsLocation ( suppressionsLocation ) . setTestSourceDirectories ( getTestSourceDirectories ( ) ) . setConfigLocation ( configLocation ) . setPropertyExpansion ( propertyExpansion ) . setHeaderLocation ( headerLocation ) . setCacheFile ( cacheFile ) . setSuppressionsFileExpression ( suppressionsFileExpression ) . setEncoding ( encoding ) . setPropertiesLocation ( propertiesLocation ) ; return request ;


signature:
public class NodeIdRenderer { /** * { @ inheritDoc } */
@ Override protected String doRender ( final RenderConfiguration config , final NodeID entity ) { } }

implementation: final Port port = entity . getPort ( ) ; final String renderedPort = port == null ? "" : portRenderer . doRender ( config , entity . getPort ( ) ) ; return quote ( entity . getId ( ) ) + renderedPort ;


signature:
public class CheckstyleReport { /** * { @ inheritDoc } */
public boolean canGenerateReport ( ) { } }

implementation:
if ( skip ) { return false ; } // TODO : would be good to scan the files here
for ( File sourceDirectory : getSourceDirectories ( ) ) { if ( sourceDirectory . exists ( ) ) { return true ; } } if ( includeTestSourceDirectory ) { for ( File testSourceDirectory : getTestSourceDirectories ( ) ) { if ( testSourceDirectory . exists ( ) ) { return true ; } } } return ( ( includeResources && hasResources ( resources ) ) || ( includeTestResources && hasResources ( testResources ) ) ) ;


signature:
public class CheckstyleReport { /** * Check if any of the resources exist .
 * @ param resources The resources to check
 * @ return < code > true < / code > if the resource directory exist */
private boolean hasResources ( List < Resource > resources ) { } }

implementation: for ( Resource resource : resources ) { if ( new File ( resource . getDirectory ( ) ) . exists ( ) ) { return true ; } } return false ;


signature:
public class CheckstyleReport { /** * Merge in the deprecated parameters to the new ones , unless the new
 * parameters have values .
 * @ throws MavenReportException
 * @ deprecated Remove when deprecated params are removed . */
private void mergeDeprecatedInfo ( ) throws MavenReportException { } }

implementation: if ( "sun_checks.xml" . equals ( configLocation ) && ! "sun" . equals ( format ) ) { configLocation = FORMAT_TO_CONFIG_LOCATION . get ( format ) ; throw new MavenReportException ( "'format' parameter is deprecated: please replace with <configLocation>" + configLocation + "</configLocation>." ) ; } if ( StringUtils . isEmpty ( propertiesLocation ) ) { if ( propertiesFile != null ) { propertiesLocation = propertiesFile . getPath ( ) ; throw new MavenReportException ( "'propertiesFile' parameter is deprecated: please replace with " + "<propertiesLocation>" + propertiesLocation + "</propertiesLocation>." ) ; } else if ( propertiesURL != null ) { propertiesLocation = propertiesURL . toExternalForm ( ) ; throw new MavenReportException ( "'propertiesURL' parameter is deprecated: please replace with " + "<propertiesLocation>" + propertiesLocation + "</propertiesLocation>." ) ; } } if ( "LICENSE.txt" . equals ( headerLocation ) ) { File defaultHeaderFile = new File ( project . getBasedir ( ) , "LICENSE.txt" ) ; if ( ! defaultHeaderFile . equals ( headerFile ) ) { headerLocation = headerFile . getPath ( ) ; } } if ( StringUtils . isEmpty ( suppressionsLocation ) ) { suppressionsLocation = suppressionsFile ; if ( StringUtils . isNotEmpty ( suppressionsFile ) ) { throw new MavenReportException ( "'suppressionsFile' parameter is deprecated: please replace with " + "<suppressionsLocation>" + suppressionsLocation + "</suppressionsLocation>." ) ; } } if ( StringUtils . isEmpty ( packageNamesLocation ) ) { packageNamesLocation = packageNamesFile ; if ( StringUtils . isNotEmpty ( packageNamesFile ) ) { throw new MavenReportException ( "'packageNamesFile' parameter is deprecated: please replace with " + "<packageNamesFile>" + suppressionsLocation + "</packageNamesFile>." ) ; } }


signature:
public class CacheUtils { /** * Limits query results .
 * @ param queryString
 * Query string .
 * @ return Query string with injected " LIMIT " clause . */
public static String addQueryLimit ( String queryString , int queryLimit ) { } }

implementation: int limitIndex = queryString . lastIndexOf ( "limit" ) ; if ( limitIndex == - 1 ) { limitIndex = queryString . lastIndexOf ( "LIMIT" ) ; } if ( limitIndex == - 1 ) { return queryString + " LIMIT " + ( queryLimit + 1 ) ; } int limitNumber = Integer . parseInt ( queryString . substring ( limitIndex + 5 ) . trim ( ) ) ; return ( limitNumber > queryLimit ) ? queryString . substring ( 0 , limitIndex ) + " LIMIT " + ( queryLimit + 1 ) : queryString ;


signature:
public class CacheUtils { /** * Clears all types of regions . This method can clean both types of regions
 * ( REPLICATED , PARTITIONED ) . It can be used both on client and server side .
 * @ param region
 * the region .
 * @ param wanCompatible
 * if true , WAN replication compatible method will be used which
 * is considerably slower on REPLICATE regions .
 * @ param cleanLocal
 * if true , local cached replicate shall be cleared . */
public static void clearRegion ( Region < ? , ? > region , boolean wanCompatible , boolean cleanLocal ) { } }

implementation: ClearRegionFunction cleaner = new ClearRegionFunction ( ) ; FunctionService . registerFunction ( cleaner ) ; FunctionService . onRegion ( region ) . withArgs ( wanCompatible ) . execute ( cleaner ) . getResult ( ) ; if ( cleanLocal && isGemFireClient ( ) ) { region . localClear ( ) ; }


signature:
public class CacheUtils { /** * Returns first locator host and port from locators string .
 * @ param locatorsString
 * of type String
 * @ return String [ 0 ] - locator host String [ 1 ] - locator port */
public static String [ ] getFirstLocatorFromLocatorsString ( String locatorsString ) { } }

implementation: if ( locatorsString == null || locatorsString . length ( ) == 0 ) { return new String [ 2 ] ; } String [ ] firstLocator = new String [ 2 ] ; firstLocator [ 0 ] = locatorsString . substring ( 0 , locatorsString . indexOf ( '[' ) ) . trim ( ) ; locatorsString = locatorsString . substring ( locatorsString . indexOf ( '[' ) + 1 ) ; firstLocator [ 1 ] = locatorsString . substring ( 0 , locatorsString . indexOf ( ']' ) ) ; return firstLocator ;


signature:
public class CacheUtils { /** * Returns approximate number of entries in the region . As the function
 * counts number of entries on different nodes in parallel , per node values
 * may be captured on different moments . So the value may never be valid .
 * @ param region
 * the region .
 * @ returns approximate number of objects in the given region . */
public static int getRegionSize ( Region < ? , ? > region ) { } }

implementation: Function function = new RegionSizeFunction ( ) ; FunctionService . registerFunction ( function ) ; ResultCollector < ? , ? > rc = FunctionService . onRegion ( region ) . withCollector ( new RegionSizeResultCollector ( ) ) . execute ( function ) ; return ( Integer ) rc . getResult ( ) ;


signature:
public class CacheUtils { /** * Checks if the current GemFire is a client instance .
 * @ return true if the cache instance is client . */
public static boolean isGemFireClient ( ) { } }

implementation: GemFireCacheImpl impl = ( GemFireCacheImpl ) CacheFactory . getAnyInstance ( ) ; return impl != null && impl . isClient ( ) ;


signature:
public class CacheUtils { /** * Removes several entries from region in a single hop . On partitioned
 * region execution is done simultaneously on all partitions .
 * @ param < K >
 * key type .
 * @ param region
 * the region to remove entries .
 * @ param keys
 * the keys of entries to remove . */
public static < K > void removeAll ( Region < K , ? > region , Set < K > keys ) { } }

implementation:
if ( keys == null ) { throw new NullPointerException ( ) ; } if ( keys . isEmpty ( ) ) { // Nothing to do
return ; } Function function = new RemoveAllFunction ( ) ; FunctionService . registerFunction ( function ) ; ResultCollector < ? , ? > rc = FunctionService . onRegion ( region ) . withFilter ( keys ) . withArgs ( region . getName ( ) ) . execute ( function ) ; // Obtain result from the collector to return
// only after everything is done .
rc . getResult ( ) ;


signature:
public class CacheUtils { /** * Retries passed operation with random exponential back off delay .
 * @ param < T >
 * Type of returned value .
 * @ param runnable
 * the operation .
 * @ param maxRetries
 * the maximum number of retries .
 * @ return the value returned by operation
 * @ throws OperationRetryFailedException
 * @ throws InterruptedException */
public static < T > T retryWithExponentialBackoff ( Retryable < T > runnable , int maxRetries ) throws InterruptedException , OperationRetryFailedException { } }

implementation:
int retry = 0 ; while ( retry < maxRetries ) { retry ++ ; try { return runnable . execute ( ) ; } catch ( OperationRequireRetryException e ) { // No - op .
} catch ( InterruptedException e ) { throw e ; } if ( retry > 1 ) { long delay = ( long ) ( ( BACKOFF_BASE << retry ) * Math . random ( ) ) ; log . debug ( "Operation requested retry. Sleep for {} millis" , delay ) ; Thread . sleep ( delay ) ; } } throw new OperationRetryFailedException ( "Maximum number of operation retries reached" ) ;


signature:
public class SVGIcon { /** * Generate the BufferedImage . */
protected void generateBufferedImage ( TranscoderInput in , int w , int h ) throws TranscoderException { } }

implementation: BufferedImageTranscoder t = new BufferedImageTranscoder ( ) ; if ( w != 0 && h != 0 ) { t . setDimensions ( w , h ) ; } t . transcode ( in , null ) ; bufferedImage = t . getBufferedImage ( ) ; width = bufferedImage . getWidth ( ) ; height = bufferedImage . getHeight ( ) ;


signature:
public class SVGIcon { /** * Draw the icon at the specified location . */
@ Override public void paintIcon ( Component c , Graphics g , int x , int y ) { } }

implementation: if ( backgroundColour == null ) g . drawImage ( bufferedImage , x , y , null ) ; else g . drawImage ( bufferedImage , x , y , backgroundColour , null ) ;