signature:
public class RestrictImplDependencies { /** * Delegate method , implemented by concrete subclasses .
 * @ param project The active MavenProject .
 * @ param helper The EnforcerRuleHelper instance , from which the MavenProject has been retrieved .
 * @ throws RuleFailureException If the enforcer rule was not satisfied . */
@ SuppressWarnings ( { } }

implementation:
"unchecked" } ) @ Override protected void performValidation ( final MavenProject project , final EnforcerRuleHelper helper ) throws RuleFailureException { // Acquire the ProjectType
final ProjectType projectType ; try { projectType = ProjectType . getProjectType ( project ) ; } catch ( IllegalArgumentException e ) { throw new RuleFailureException ( "Incorrect project definition for " + project , e ) ; } // Don ' t evaluate for ignored project types .
if ( IGNORED_PROJECT_TYPES . contains ( projectType ) ) { return ; } // Don ' t evaluate if told not to .
if ( matches ( project . getGroupId ( ) , dontEvaluateGroupIds ) ) { // Log somewhat
helper . getLog ( ) . debug ( "Ignored [" + project . getGroupId ( ) + ":" + project . getArtifactId ( ) + "] since its groupId was excluded from enforcement." ) ; return ; } // Don ' t evaluate if not told to .
if ( ! matches ( project . getGroupId ( ) , evaluateGroupIds ) ) { // Log somewhat
helper . getLog ( ) . debug ( "Ignored [" + project . getGroupId ( ) + ":" + project . getArtifactId ( ) + "] since its groupId was not included in enforcement." ) ; return ; } // Acquire all project dependencies .
for ( final Artifact current : project . getDependencyArtifacts ( ) ) { // Don ' t evaluate for test - scope dependencies .
if ( Artifact . SCOPE_TEST . equalsIgnoreCase ( current . getScope ( ) ) ) { continue ; } // Should this Artifact be evaluated ?
final boolean isIncludedInEvaluation = matches ( current . getGroupId ( ) , evaluateGroupIds ) ; final boolean isNotExplicitlyExcludedFromEvaluation = ! matches ( current . getGroupId ( ) , dontEvaluateGroupIds ) ; if ( isIncludedInEvaluation && isNotExplicitlyExcludedFromEvaluation ) { final ProjectType artifactProjectType = ProjectType . getProjectType ( current ) ; final String prefix = "Don't use " + artifactProjectType + " dependencies " ; if ( artifactProjectType == ProjectType . IMPLEMENTATION ) { throw new RuleFailureException ( prefix + "outside of application projects." , current ) ; } if ( artifactProjectType == ProjectType . TEST ) { throw new RuleFailureException ( prefix + "in compile scope for non-test artifacts." , current ) ; } if ( artifactProjectType == ProjectType . JEE_APPLICATION || artifactProjectType == ProjectType . PROOF_OF_CONCEPT ) { throw new RuleFailureException ( prefix + "in bundles." , current ) ; } } }


signature:
public class ConsoleUtils { /** * Method getReader returns the reader of this ConsoleUtils object .
 * @ return the reader ( type BufferedReader ) of this ConsoleUtils object . */
private static BufferedReader getReader ( ) { } }

implementation: if ( bufferedReader == null ) { bufferedReader = new BufferedReader ( new InputStreamReader ( System . in ) ) ; } return bufferedReader ;


signature:
public class ConsoleUtils { /** * Waits for enter with specified message .
 * @ param message of type String */
public static void waitForEnter ( String message ) { } }

implementation:
System . out . println ( message ) ; try { getReader ( ) . readLine ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; // To change body of catch statement use File | Settings | File Templates .
}


signature:
public class CheckReplicationTool { /** * Runs the tool . All the tools run in this way . */
public void execute ( String [ ] args , boolean debugEnabled , boolean quiet ) { } }

implementation: try { this . debugEnabled = debugEnabled ; debug ( "CheckReplicationTool#execute(String[]): args = " + Arrays . asList ( args ) ) ; parseCommandLineArguments ( args ) ; System . out . println ( "Connecting..." ) ; debug ( "CheckReplicationTool#execute(String[]): Creating CheckReplicationTool.ProcessorTask with parameters: clustersProperties = " + clustersProperties + ", timeout = " + timeout + ", regionName = " + regionName ) ; ProcessorTask task = new ProcessorTask ( clustersProperties , timeout , regionName , debugEnabled , quiet ) ; debug ( "CheckReplicationTool#execute(String[]): Starting CheckReplicationTool.ProcessorTask" ) ; Utils . execute ( task , timeout + DELTA_TIMEOUT ) ; int exitCode = task . getExitCode ( ) ; debug ( "CheckReplicationTool#execute(String[]): CheckReplicationTool.ProcessorTask finished with exitCode = " + exitCode ) ; if ( exitCode == 0 ) { Utils . exitWithSuccess ( ) ; } Utils . exitWithFailure ( ) ; } catch ( Throwable t ) { debug ( "CheckReplicationTool#execute(String[]): Throwable caught with message = " + t . getMessage ( ) , t ) ; Utils . exitWithFailure ( "Unexpected throwable" , t ) ; }


signature:
public class CheckReplicationTool { /** * Parses command - line arguments and sets the local variables
 * @ param commandLineArguments
 * - the list of command - line arguments */
protected void parseCommandLineArguments ( String [ ] commandLineArguments ) { } }

implementation: Options options = constructGnuOptions ( ) ; if ( commandLineArguments . length < 1 ) { printHelp ( options ) ; } CommandLineParser parser = new GnuParser ( ) ; try { CommandLine line = parser . parse ( options , commandLineArguments ) ; if ( line . hasOption ( HELP_OPTION ) ) { printHelp ( options ) ; } if ( line . hasOption ( REGION_OPTION ) ) { regionName = line . getOptionValue ( REGION_OPTION ) ; } if ( line . hasOption ( TIMEOUT_OPTION ) ) { String timeoutString = line . getOptionValue ( TIMEOUT_OPTION ) ; timeout = Long . parseLong ( timeoutString ) ; } if ( line . hasOption ( CLUSTER_OPTION ) ) { clustersProperties = line . getOptionProperties ( CLUSTER_OPTION ) ; if ( clustersProperties . keySet ( ) . size ( ) < 2 ) { Utils . exitWithFailure ( "At least two clusters should be defined" ) ; } } else { Utils . exitWithFailure ( "No clusters defined" ) ; } } catch ( Throwable t ) { Utils . exitWithFailure ( "Throwable caught during the command-line arguments parsing" , t ) ; }


signature:
public class CheckReplicationTool { /** * Prints help if requested , or in case of any misconfiguration
 * @ param options
 * - the GNU options */
protected void printHelp ( final Options options ) { } }

implementation: HelpFormatter formatter = new HelpFormatter ( ) ; formatter . printHelp ( "check-replication [options]" , options ) ; Utils . exitWithFailure ( ) ;


signature:
public class CheckReplicationTool { /** * Constructs the set of GNU options
 * @ return - the constructed options */
protected Options constructGnuOptions ( ) { } }

implementation: final Options gnuOptions = new Options ( ) ; gnuOptions . addOption ( "t" , TIMEOUT_OPTION , true , "Timeout, ms. Default timeout is " + DEFAULT_TIMEOUT ) . addOption ( "r" , REGION_OPTION , true , "The name of region for this test. Default name is \"" + DEFAULT_REGION_NAME + "\"" ) . addOption ( "h" , HELP_OPTION , false , "Print usage information" ) ; @ SuppressWarnings ( "static-access" ) Option locatorsOption = OptionBuilder . hasArgs ( ) . withDescription ( "Cluster name and list of its locators. " + "There should be at least two clusters. " + "Example: -c cluster1=host1[port1],host2[port2] -c cluster2=host3[port3]" ) . withValueSeparator ( ) . withArgName ( "cluster=locators" ) . withLongOpt ( CLUSTER_OPTION ) . create ( "c" ) ; gnuOptions . addOption ( locatorsOption ) ; return gnuOptions ;


signature:
public class HashCodeCollector { /** * todo : insert from cli */
public static void main ( String [ ] args ) throws AdminException { } }

implementation:
AdminDistributedSystem adminDs = AdminDistributedSystemFactory . getDistributedSystem ( AdminDistributedSystemFactory . defineDistributedSystem ( ) ) ; adminDs . connect ( ) ; // connect to different clusters . test data todo : insert cli usage
Pool poolForCluster1 = PoolManager . createFactory ( ) . addLocator ( "localhost" , 10330 ) . create ( "cluster1" ) ; Pool poolForCluster2 = PoolManager . createFactory ( ) . addLocator ( "localhost" , 10332 ) . create ( "cluster2" ) ; // Pool poolForServer = PoolManager . createFactory ( ) . addServer ( " localhost " , 40405 ) . create ( " node " ) ;
List < Pool > poolList = new ArrayList < Pool > ( ) ; poolList . add ( poolForCluster1 ) ; poolList . add ( poolForCluster2 ) ; // poolList . add ( poolForServer ) ;
// todo : insert checking that each cluster contains region and one ' s type is equal ( Partitioned , Replicated )
boolean partitioned = true ; // todo : insert CLI usage + throw exception if real region has another type
List < ServerLocation > serverFromPool = new ArrayList < ServerLocation > ( ) ; List < Pool > emptyPools = new ArrayList < Pool > ( ) ; // contains pool with no available servers
for ( Pool pool : poolList ) { List < ServerLocation > allServers = null ; if ( ! pool . getLocators ( ) . isEmpty ( ) ) allServers = ( ( AutoConnectionSourceImpl ) ( ( PoolImpl ) pool ) . getConnectionSource ( ) ) . findAllServers ( ) ; else if ( ! pool . getServers ( ) . isEmpty ( ) ) allServers = Arrays . asList ( ( ( ( PoolImpl ) pool ) . getConnectionSource ( ) ) . findServer ( Collections . emptySet ( ) ) ) ; if ( allServers != null ) serverFromPool . addAll ( allServers ) ; else { logger . info ( "not found servers on locator {}" , pool ) ; emptyPools . add ( pool ) ; } } poolList . removeAll ( emptyPools ) ; if ( serverFromPool . size ( ) == 0 ) { logger . info ( "no servers available" ) ; return ; } for ( ServerLocation server : serverFromPool ) { System . out . println ( "host: " + server . getHostName ( ) ) ; System . out . println ( "port: " + server . getPort ( ) ) ; System . out . println ( "----------------------" ) ; } // source for comparison / / todo : if this node doesn ' t contain region ! it ' s problem
Pool sourcePool ; if ( ! partitioned ) { int randomServerLocation = new Random ( ) . nextInt ( serverFromPool . size ( ) ) ; sourcePool = PoolManager . createFactory ( ) . addServer ( serverFromPool . get ( randomServerLocation ) . getHostName ( ) , serverFromPool . get ( randomServerLocation ) . getPort ( ) ) . create ( "target" ) ; } else { sourcePool = poolList . get ( 0 ) ; poolList . remove ( 0 ) ; } FunctionService . registerFunction ( new RegionInfoFunction ( ) ) ; ResultCollector regionInfoResult = FunctionService . onServers ( sourcePool ) . withArgs ( REGION_NAME ) . execute ( new RegionInfoFunction ( ) ) ; Map regionInfo = ( HashMap ) ( ( ArrayList ) regionInfoResult . getResult ( ) ) . get ( 0 ) ; System . out . println ( "region info: " + regionInfo ) ; int totalNumBuckets = ( Integer ) regionInfo . get ( "totalNumBuckets" ) ; // logger . debug ( " total keys ' batch counts is " , totalNumBuckets ) ;
System . out . println ( "total keys' batch counts is " + totalNumBuckets ) ; KeyExtractor keyExtractor = new KeyExtractor ( REGION_NAME , sourcePool , partitioned , totalNumBuckets ) ; Map < String , Map < String , Set > > clusterDifference = new HashMap < String , Map < String , Set > > ( ) ; // key : memeberId list : absent keys , diff values
// List < ResultCollector > taskResults = new ArrayList < ResultCollector > ( ) ;
List < PoolResult > taskResults = new ArrayList < PoolResult > ( ) ; // List < Future < ResultCollector > > collectTasks = new ArrayList < Future < ResultCollector > > ( poolList . size ( ) ) ;
List < Future < PoolResult > > collectTasks = new ArrayList < Future < PoolResult > > ( poolList . size ( ) ) ; ExecutorService executorService = Executors . newFixedThreadPool ( poolList . size ( ) ) ; while ( keyExtractor . hasKeys ( ) ) { Set keys = keyExtractor . getNextKeysBatch ( ) ; System . out . println ( "keys to check: " + keys ) ; for ( Pool nextPool : poolList ) collectTasks . add ( executorService . submit ( new CollectorTask ( keys , nextPool , REGION_NAME ) ) ) ; System . out . println ( "active tasks: " + collectTasks . size ( ) ) ; try { // for ( Future < ResultCollector > futureTask : collectTasks ) {
for ( Future < PoolResult > futureTask : collectTasks ) { taskResults . add ( futureTask . get ( ) ) ; } } catch ( InterruptedException ie ) { ie . printStackTrace ( ) ; } catch ( ExecutionException ee ) { ee . printStackTrace ( ) ; } collectTasks . clear ( ) ; System . out . println ( "compare contents.." ) ; // getting original contents
Map originalData = new HashMap ( ) ; /* for ( ResultCollector taskResultFromPool : taskResults ) {
 List memberResult = ( ArrayList ) taskResultFromPool . getResult ( ) ;
 if ( ! partitioned )
 for ( Object result : memberResult ) { / / if cluster has several nodes with replicated region . . . todo : adopt for partitioned
 if ( regionInfo . get ( " id " ) . equals ( ( ( HashMap ) result ) . get ( " memberId " ) ) ) {
 originalData = ( HashMap ) ( ( HashMap ) result ) . get ( " map " ) ;
 break ;
 else {
 FutureTask < ResultCollector > ft = new FutureTask < ResultCollector > ( new CollectorTask ( keys , sourcePool , REGION _ NAME ) ) ;
 try {
 ResultCollector rc = ft . get ( ) ;
 } catch ( Exception e ) {
 throw new RuntimeException ( " error getting key - hashcode from pool : " + sourcePool , e ) ; */
// FutureTask < ResultCollector > ft = new FutureTask < ResultCollector > ( new CollectorTask ( keys , sourcePool , REGION _ NAME ) ) ;
FutureTask < PoolResult > ft = new FutureTask < PoolResult > ( new CollectorTask ( keys , sourcePool , REGION_NAME ) ) ; ft . run ( ) ; try { // ResultCollector rc = ft . get ( ) ;
PoolResult rc = ft . get ( ) ; List poolResult = ( List ) rc . getResultCollector ( ) . getResult ( ) ; for ( Object singleResult : poolResult ) { originalData . putAll ( ( Map ) ( ( HashMap ) singleResult ) . get ( "map" ) ) ; } } catch ( Exception e ) { throw new RuntimeException ( "error getting key-hash from pool: " + sourcePool , e ) ; } /* if ( true )
 return ;
 / / todo : aggregate members ' data from one cluster
 if ( partitioned )
 aggregateSingleClusterMemberData ( taskResults ) ; */
System . out . println ( "original data is: " + originalData ) ; // for ( ResultCollector taskResultFromPool : taskResults ) {
for ( PoolResult taskResultFromPool : taskResults ) { List poolResult = ( ArrayList ) taskResultFromPool . getResultCollector ( ) . getResult ( ) ; if ( ! partitioned ) { for ( Object resultFromMember : poolResult ) { Map result = ( HashMap ) resultFromMember ; if ( regionInfo . get ( "id" ) . equals ( result . get ( "memberId" ) ) ) // for replicated region
continue ; /* System . out . println ( " member id : " + result . get ( " memberId " ) ) ;
 System . out . println ( " absent keys is " + result . get ( " absentKeys " ) ) ;
 System . out . println ( " it ' s data is : " + result . get ( " map " ) ) ; */
String memberId = ( String ) result . get ( "memberId" ) ; Map memberData = ( HashMap ) result . get ( "map" ) ; Map memberDataCopy = new HashMap ( ) ; memberDataCopy . putAll ( memberData ) ; memberDataCopy . keySet ( ) . retainAll ( originalData . keySet ( ) ) ; Map < String , Set > aggregationInfo = new HashMap < String , Set > ( ) ; // contains aggregation info for a member
// keys witch values are different
Set keysForDiffValues = new HashSet ( ) ; Set absentKeys = new HashSet ( ) ; for ( Object regionKey : memberDataCopy . keySet ( ) ) if ( ! memberDataCopy . get ( regionKey ) . equals ( originalData . get ( regionKey ) ) ) // we compare not original values , but it ' s hash code
keysForDiffValues . add ( regionKey ) ; aggregationInfo . put ( "diffValues" , keysForDiffValues ) ; // absent keys
memberData . keySet ( ) . removeAll ( memberDataCopy . keySet ( ) ) ; absentKeys . addAll ( memberData . keySet ( ) ) ; absentKeys . addAll ( ( HashSet ) result . get ( "absentKeys" ) ) ; aggregationInfo . put ( "absentKeys" , absentKeys ) ; /* if ( ! clusterDifference . containsKey ( memberId ) ) {
 clusterDifference . put ( memberId , aggregationInfo ) ;
 } else {
 Map < String , Set > difference = clusterDifference . get ( memberId ) ;
 difference . get ( " absentKeys " ) . addAll ( aggregationInfo . get ( " absentKeys " ) ) ;
 difference . get ( " diffValues " ) . addAll ( aggregationInfo . get ( " diffValues " ) ) ;
 clusterDifference . put ( memberId , difference ) ; */
if ( ! clusterDifference . containsKey ( memberId ) ) { clusterDifference . put ( memberId , aggregationInfo ) ; } else { Map < String , Set > difference = clusterDifference . get ( memberId ) ; difference . get ( "absentKeys" ) . addAll ( aggregationInfo . get ( "absentKeys" ) ) ; difference . get ( "diffValues" ) . addAll ( aggregationInfo . get ( "diffValues" ) ) ; clusterDifference . put ( memberId , difference ) ; } } } else { Map targetMap = new HashMap ( ) ; Set absentPoolKeys = new HashSet ( ) ; // aggregate absent keys from pool members
for ( Object memberResult : poolResult ) { targetMap . putAll ( ( Map ) ( ( HashMap ) memberResult ) . get ( "map" ) ) ; absentPoolKeys . addAll ( ( Set ) ( ( ( HashMap ) memberResult ) . get ( "absentKeys" ) ) ) ; } Map memberDataCopy = new HashMap ( ) ; memberDataCopy . putAll ( targetMap ) ; memberDataCopy . keySet ( ) . retainAll ( originalData . keySet ( ) ) ; Map < String , Set > aggregationInfo = new HashMap < String , Set > ( ) ; // contains aggregation info for a member
// keys witch values are different
Set keysForDiffValues = new HashSet ( ) ; Set absentKeys = new HashSet ( ) ; for ( Object regionKey : memberDataCopy . keySet ( ) ) if ( ! memberDataCopy . get ( regionKey ) . equals ( originalData . get ( regionKey ) ) ) // we compare not original values , but it ' s hash code
keysForDiffValues . add ( regionKey ) ; aggregationInfo . put ( "diffValues" , keysForDiffValues ) ; // absent keys
targetMap . keySet ( ) . removeAll ( memberDataCopy . keySet ( ) ) ; absentKeys . addAll ( targetMap . keySet ( ) ) ; absentKeys . addAll ( absentPoolKeys ) ; // aggregationInfo . put ( " absentKeys " , absentKeys ) ;
if ( ! clusterDifference . containsKey ( taskResultFromPool . getPool ( ) . toString ( ) ) ) { clusterDifference . put ( taskResultFromPool . getPool ( ) . toString ( ) , aggregationInfo ) ; } else { Map < String , Set > difference = clusterDifference . get ( taskResultFromPool . getPool ( ) . toString ( ) ) ; // difference . get ( " absentKeys " ) . addAll ( aggregationInfo . get ( " absentKeys " ) ) ;
difference . get ( "diffValues" ) . addAll ( aggregationInfo . get ( "diffValues" ) ) ; clusterDifference . put ( taskResultFromPool . getPool ( ) . toString ( ) , difference ) ; } } } taskResults . clear ( ) ; } System . out . println ( "____________________________" ) ; System . out . println ( "difference: " ) ; System . out . println ( clusterDifference ) ; executorService . shutdown ( ) ; adminDs . disconnect ( ) ;


signature:
public class HashCodeCollector { /** * only for partitioned region ! */
private static void aggregateSingleClusterMemberData ( List < ResultCollector > taskResults ) { } }

implementation: for ( ResultCollector singleCluster : taskResults ) { List membersResult = ( List ) singleCluster . getResult ( ) ; for ( Object resultFromNode : membersResult ) { System . out . print ( ( ( HashMap ) resultFromNode ) . get ( "ds" ) + ":" ) ; } System . out . println ( ) ; }


signature:
public class ImageFile { /** * An image file can be represented by multiple translated images . These images can all be from originally differently names
 * files , and can have different dimensions . However , all translated images need to be of the same file file . The
 * getDocbookFileName ( ) method needs to be able to append a fixed extension to the file name when the image is included in a
 * Docbook XML file .
 * This method will throw an exception if there are inconsistent file extensions on any of the original file names assigned
 * to the translated images .
 * @ throws CustomConstraintViolationException */
public void validate ( ) throws CustomConstraintViolationException { } }

implementation: final String extension = getExtension ( ) ; if ( extension != null ) { for ( final LanguageImage langImg : languageImages ) { if ( langImg . getOriginalFileName ( ) != null && ! langImg . getOriginalFileName ( ) . isEmpty ( ) ) { final String thisExtension = FileUtilities . getFileExtension ( langImg . getOriginalFileName ( ) ) ; if ( ! thisExtension . toLowerCase ( ) . equals ( extension . toLowerCase ( ) ) ) throw new CustomConstraintViolationException ( "All LanguageImages contained by an ImageFile need to have the same file extension" ) ; } } }


signature:
public class ExpressionBuilder { /** * Adds a description for a null property .
 * @ param property The property to check .
 * @ param name The property name .
 * @ return This object . */
public ExpressionBuilder notNull ( final Object property , final String name ) { } }

implementation: if ( property == null ) { messageContainer . addErrorMessage ( "Property '" + name + "' cannot be null" ) ; } return this ;


signature:
public class ExpressionBuilder { /** * Adds a description for a null or empty property ( Strings , Collections and Maps are
 * checked for emptyness as well as null - ness ) .
 * @ param property The property to check .
 * @ param name The property name .
 * @ return This object . */
public ExpressionBuilder notNullOrEmpty ( final Object property , final String name ) { } }

implementation: notNull ( property , name ) ; if ( property instanceof String && ( ( String ) property ) . isEmpty ( ) ) { messageContainer . addErrorMessage ( "Property '" + name + "' cannot be empty." ) ; } if ( property instanceof Collection && ( ( Collection < ? > ) property ) . isEmpty ( ) ) { messageContainer . addErrorMessage ( "Collection '" + name + "' must contain elements." ) ; } if ( property instanceof Map && ( ( Map < ? , ? > ) property ) . isEmpty ( ) ) { messageContainer . addErrorMessage ( "Map '" + name + "' must contain elements." ) ; } return this ;


signature:
public class Launcher { /** * Parses command line arguments .
 * @ param commandLineArguments
 * - The arguments . */
private static void parseCommandLineArguments ( String [ ] commandLineArguments ) { } }

implementation: Options options = constructGnuOptions ( ) ; CommandLineParser parser = new GnuParser ( ) ; try { CommandLine line = parser . parse ( options , commandLineArguments ) ; if ( line . hasOption ( HELP_OPTION ) ) { printHelp ( options ) ; } if ( line . hasOption ( DEBUG_OPTION ) ) { debugEnabled = true ; } if ( ! debugEnabled && line . hasOption ( QUIET_OPTION ) ) { quiet = true ; } } catch ( Throwable t ) { printHelp ( options ) ; }


signature:
public class Launcher { /** * Prints help if requested .
 * @ param options
 * - The GNU options . */
private static void printHelp ( final Options options ) { } }

implementation: StringBuilder sb = new StringBuilder ( ) ; sb . append ( "java -jar icegem-cache-utils-<version>.jar [options] <" ) ; Command [ ] commands = Command . values ( ) ; for ( int i = 0 ; i < commands . length ; i ++ ) { sb . append ( commands [ i ] . getName ( ) ) ; if ( i < ( commands . length - 1 ) ) { sb . append ( " | " ) ; } } sb . append ( "> [command_specific_options]" ) ; HelpFormatter formatter = new HelpFormatter ( ) ; formatter . printHelp ( sb . toString ( ) , options ) ; Utils . exitWithFailure ( ) ;


signature:
public class Launcher { /** * Constructs the set of GNU options .
 * @ return - The constructed options . */
private static Options constructGnuOptions ( ) { } }

implementation: final Options gnuOptions = new Options ( ) ; gnuOptions . addOption ( "d" , DEBUG_OPTION , false , "Print debug information" ) . addOption ( "q" , QUIET_OPTION , false , "Quiet output. Doesn't work if --" + DEBUG_OPTION + " specified." ) . addOption ( "h" , HELP_OPTION , false , "Print usage information" ) ; return gnuOptions ;


signature:
public class Launcher { /** * Looks for the index of command in the specified array .
 * @ param args
 * - Arguments .
 * @ return - Index of command , or - 1 if command is not found in the array . */
private static int findCommandIndex ( String [ ] args ) { } }

implementation: int commandIndex = - 1 ; for ( int i = 0 ; i < args . length ; i ++ ) { for ( Command command : Command . values ( ) ) { if ( command . getName ( ) . equals ( args [ i ] . trim ( ) ) ) { commandIndex = i ; break ; } } } return commandIndex ;


signature:
public class Launcher { /** * Extracts the launcher arguments from the all arguments array .
 * @ param args
 * - All arguments .
 * @ param commandIndex
 * - Index of the command .
 * @ return - Launcher arguments . */
private static String [ ] extractLauncherArgs ( String [ ] args , int commandIndex ) { } }

implementation: String [ ] launcherArgs = new String [ commandIndex ] ; System . arraycopy ( args , 0 , launcherArgs , 0 , commandIndex ) ; return launcherArgs ;


signature:
public class Launcher { /** * Extracts the command - specific arguments from the all arguments array .
 * @ param args
 * - All arguments .
 * @ param commandIndex
 * - Index of the command .
 * @ return - Command - specific arguments . */
private static String [ ] extractCommandArgs ( String [ ] args , int commandIndex ) { } }

implementation: String [ ] commandArgs = new String [ args . length - commandIndex - 1 ] ; System . arraycopy ( args , commandIndex + 1 , commandArgs , 0 , args . length - commandIndex - 1 ) ; return commandArgs ;


signature:
public class Launcher { /** * The entry point of the application .
 * @ param args
 * - All arguments .
 * @ throws Exception */
public static void main ( String [ ] args ) { } }

implementation: try { int commandIndex = findCommandIndex ( args ) ; if ( commandIndex < 0 ) { printHelp ( ) ; } String [ ] launcherArgs = extractLauncherArgs ( args , commandIndex ) ; String [ ] commandArgs = extractCommandArgs ( args , commandIndex ) ; parseCommandLineArguments ( launcherArgs ) ; debug ( "Launcher#main(): args = " + Arrays . asList ( args ) ) ; debug ( "Launcher#main(): launcherArgs = " + Arrays . asList ( launcherArgs ) ) ; debug ( "Launcher#main(): commandArgs = " + Arrays . asList ( commandArgs ) ) ; String commandName = args [ commandIndex ] ; Executable tool = Command . getUtil ( commandName ) ; if ( tool != null ) { tool . execute ( commandArgs , debugEnabled , quiet ) ; } else { debug ( "Launcher#main(): Command \"" + commandName + "\" not found" ) ; printHelp ( ) ; } } catch ( Throwable t ) { debug ( "Launcher#main(): Throwable caught with message = " + t . getMessage ( ) , t ) ; Utils . exitWithFailure ( "Unexpected throwable" , t ) ; }


signature:
public class Launcher { /** * Prints debug information if debug is enabled .
 * @ param message
 * - Debug message .
 * @ param t
 * - Instance of Throwable . */
private static void debug ( String message , Throwable t ) { } }

implementation: if ( debugEnabled ) { System . err . println ( "0 [Launcher] " + message ) ; if ( t != null ) { t . printStackTrace ( System . err ) ; } }


signature:
public class EdgeRenderer { /** * < p > Renders the supplied Edge according to the following structure : < / p >
 * < pre > ( node _ id | subgraph ) edgeRHS [ attr _ list ] < / pre >
 * < p > . . . where . . . < / p >
 * < pre > edgeRHS : edgeop ( node _ id | subgraph ) [ edgeRHS ] < / pre >
 * @ param config The non - null RenderConfiguration .
 * @ param edge The non - null Edge to be rendered . */
@ Override protected String doRender ( final RenderConfiguration config , final Edge edge ) { } }

implementation:
// Edges can be from / to Nodes and Subgraphs . Pick the correct ID source .
final String edgeID = edge . getNodeID ( ) != null ? nodeIdRenderer . doRender ( config , edge . getNodeID ( ) ) : quote ( edge . getSubgraph ( ) . getId ( ) ) ; // Render the attributes after the RightSideEdge .
final RightSideEdge rightSideEdge = edge . getRightSideEdge ( ) ; return config . getIndent ( ) + edgeID + " " + rightSideEdgeRenderer . doRender ( config , rightSideEdge ) + " " + attributeRenderer . doRender ( config , edge . getAttributes ( ) ) ;


signature:
public class MonitorTool { /** * configuration */
private void init ( ) { } }

implementation: try { log . info ( Utils . currentDate ( ) + "" ) ; log . info ( Utils . currentDate ( ) + "  --------------------------------------------------" ) ; log . info ( Utils . currentDate ( ) + "  Monitoring tool started" ) ; log . info ( Utils . currentDate ( ) + "  --------------------------------------------------" ) ; propertiesHelper = new PropertiesHelper ( "/monitoring.properties" ) ; nodesController = new NodesController ( propertiesHelper , locators , timeout ) ; nodesController . addNodeEventHandler ( new LoggerNodeEventHandler ( ) ) ; for ( NodeEventHandler handler : customEventHandlersList ) { nodesController . addNodeEventHandler ( handler ) ; } timer = new Timer ( ) ; } catch ( Throwable t ) { Utils . exitWithFailure ( "Throwable caught during the initialization" , t ) ; }


signature:
public class MonitorTool { /** * Starts the checking task */
private void start ( ) { } }

implementation: try { timer . schedule ( new IsAliveTimerTask ( ) , 0 , period ) ; } catch ( Throwable t ) { Utils . exitWithFailure ( "Throwable caught during the startup" , t ) ; }


signature:
public class PeerCacheService { /** * Creates regions structure similar to server region structure .
 * @ param regionNames names of the regions to reconstruct .
 * @ return set of created regions . */
public Set < Region < ? , ? > > createRegions ( Map < String , String > regionNames ) { } }

implementation: Set < Region < ? , ? > > regions = new HashSet < Region < ? , ? > > ( ) ; proxyRegionFactory = cache . createClientRegionFactory ( ClientRegionShortcut . PROXY ) ; for ( String regionPath : regionNames . keySet ( ) ) { Region region = createRegion ( regionPath , regionNames . get ( regionPath ) ) ; regions . add ( region ) ; } return regions ;


signature:
public class CommentRenderer { /** * { @ inheritDoc } */
@ Override protected String doRender ( final RenderConfiguration config , final Comment comment ) { } }

implementation:
// Check sanity
final StringBuilder builder = new StringBuilder ( config . getNewline ( ) + config . getIndent ( ) ) ; final List < String > commentLines = comment . getCommentLines ( ) ; if ( commentLines . size ( ) == 1 ) { // Use a ' / / ' single - line comment
builder . append ( "// " ) . append ( commentLines . get ( 0 ) ) ; } else if ( commentLines . size ( ) > 1 ) { // Use a ' / * ' . . . ' * / ' multi - line comment
builder . append ( "/* " ) . append ( config . getNewline ( ) ) ; for ( String current : commentLines ) { builder . append ( config . getIndent ( ) ) . append ( " * " ) . append ( current ) . append ( config . getNewline ( ) ) ; } builder . append ( config . getIndent ( ) ) . append ( " */" ) ; } // All Done .
return builder . toString ( ) + config . getNewline ( ) ;


signature:
public class ExpirationController { /** * Applies the specified policy on the specified region and returns number
 * of destroyed entries .
 * @ param region
 * - the region
 * @ param policy
 * - the expiration policy
 * @ return - the number of destroyed region entries */
public long process ( Region < ? , ? > region , ExpirationPolicy policy ) { } }

implementation: long destroyedEntriesNumber = 0 ; try { if ( region == null ) { throw new IllegalStateException ( "The Region cannot be null" ) ; } if ( policy == null ) { throw new IllegalArgumentException ( "The ExpirationPolicy cannot be null" ) ; } logger . info ( "Running ExpirationController process with parameters region = " + region + ", policy = " + policy + ", packetSize = " + packetSize + ", packetDelay = " + packetDelay ) ; DestroyedEntriesCountCollector collector = ( DestroyedEntriesCountCollector ) FunctionService . onRegion ( region ) . withArgs ( new ExpirationFunctionArguments ( packetSize , packetDelay ) ) . withCollector ( new DestroyedEntriesCountCollector ( ) ) . execute ( new ExpirationFunction ( policy ) ) ; Object result = collector . getResult ( ) ; if ( result instanceof Long ) { destroyedEntriesNumber = ( Long ) result ; } logger . info ( "ExpirationController process with parameters region = " + region + ", policy = " + policy + ", packetSize = " + packetSize + ", packetDelay = " + packetDelay + " has destroyed " + destroyedEntriesNumber + " entries" ) ; } catch ( RuntimeException re ) { logger . error ( "RuntimeException during processing" , re ) ; throw re ; } return destroyedEntriesNumber ;


signature:
public class RenderConfiguration { /** * Assigns the indentationToken of this RenderConfiguration .
 * @ param indentationToken the indentationToken of this RenderConfiguration . Cannot be null or empty . */
public final void setIndentationToken ( final String indentationToken ) { } }

implementation:
// Check sanity
if ( indentationToken == null || indentationToken . isEmpty ( ) ) { throw new IllegalArgumentException ( "Cannot handle null or empty 'indentationToken' argument." ) ; } // Assign internal state
this . indentationToken = indentationToken ;


signature:
public class RenderConfiguration { /** * Clones this RenderConfiguration , and changes the indentation level ( of the returned
 * RenderConfiguration ) as indicated .
 * @ param indentationChange The change of the indentation level in the returned RenderConfiguration .
 * @ return A { @ link RenderConfiguration } clone of this one - except that the indentationLevel is changed with the
 * supplied amount .
 * @ throws IllegalArgumentException if the indentationLevel after the change is negative .
 * @ see # setIndentationLevel ( int ) */
public final RenderConfiguration cloneAndChangeIndentation ( final int indentationChange ) throws IllegalArgumentException { } }

implementation:
// Check sanity
final int newIndentationLevel = getIndentationLevel ( ) + indentationChange ; final RenderConfiguration toReturn = new RenderConfiguration ( newIndentationLevel , indentationToken , isDirectedGraph ) ; toReturn . getExtraConfiguration ( ) . putAll ( getExtraConfiguration ( ) ) ; // All Done .
return toReturn ;


signature:
public class RenderConfiguration { /** * Retrieves a full indent , given the { @ link # indentationToken } and { @ link # indentationLevel } .
 * @ return The full string to be emitted before a properly indented token is rendered . */
public String getIndent ( ) { } }

implementation:
StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < getIndentationLevel ( ) ; i ++ ) { builder . append ( indentationToken ) ; } // All Done .
return builder . toString ( ) ;


signature:
public class JavaPackageExtractor { /** * Retrieves the package definition from the supplied sourceFile .
 * @ param sourceFile The sourceFile from which the package definition should be extracted .
 * @ return The package of the sourceFile . */
@ Override public String getPackage ( final File sourceFile ) { } }

implementation:
String aLine = getPackage ( sourceFile , PACKAGE_STATEMENT ) ; if ( aLine != null ) return aLine ; // No package statement found .
// Return default package .
return "" ;


signature:
public class LifecycleInvestigationDoclet { /** * Generate documentation here .
 * This method is required for all doclets .
 * @ return true on success . */
public static boolean start ( final RootDoc root ) { } }

implementation:
// Perform some reflective investigation of the RootDoc
final boolean toReturn = Standard . start ( root ) ; eventSequence . add ( "start (root): " + toReturn ) ; // We should emit the eventSequence here .
for ( int i = 0 ; i < eventSequence . size ( ) ; i ++ ) { System . out . println ( " event [" + i + " / " + eventSequence . size ( ) + "]: " + eventSequence . get ( i ) ) ; } // All Done .
return toReturn ;


signature:
public class LifecycleInvestigationDoclet { /** * < p > Check for doclet - added options . Returns the number of
 * arguments you must specify on the command line for the
 * given option . For example , " - d docs " would return 2 . < / p >
 * < p > This method is required if the doclet contains any options .
 * If this method is missing , Javadoc will print an invalid flag
 * error for every option . < / p >
 * @ return number of arguments on the command line for an option
 * including the option name itself . Zero return means
 * option not known . Negative value means error occurred . */
public static int optionLength ( final String option ) { } }

implementation: final int standardOptionLength = Standard . optionLength ( option ) ; eventSequence . add ( "optionLength (" + option + "): " + standardOptionLength ) ; return standardOptionLength ;


signature:
public class LifecycleInvestigationDoclet { /** * Check that options have the correct arguments .
 * This method is not required , but is recommended ,
 * as every option will be considered valid if this method
 * is not present . It will default gracefully ( to true )
 * if absent .
 * Printing option related error messages ( using the provided
 * DocErrorReporter ) is the responsibility of this method .
 * @ return true if the options are valid . */
public static boolean validOptions ( final String options [ ] [ ] , DocErrorReporter reporter ) { } }

implementation:
final boolean toReturn = Standard . validOptions ( options , reporter ) ; if ( options == null || options . length == 0 ) { eventSequence . add ( "validOptions (none supplied): " + toReturn ) ; } else { for ( int i = 0 ; i < options . length ; i ++ ) { final String thisOption = Arrays . stream ( options [ i ] ) . reduce ( ( l , r ) -> l + " " + r ) . orElse ( "<none>" ) ; eventSequence . add ( "validOptions [" + i + " / " + options . length + "] (" + thisOption + "): " + toReturn ) ; } } // All Done .
return toReturn ;


signature:
public class NodesController { /** * Extracts port from the SystemMember object .
 * @ param member
 * - the specified SystemMember
 * @ return - port if its found , - 1 otherwise
 * @ throws AdminException */
private Set < Integer > extractPortsSet ( SystemMember member ) throws AdminException { } }

implementation: Set < Integer > portsSet = new HashSet < Integer > ( ) ; SystemMemberCache cache = member . getCache ( ) ; if ( cache != null ) { SystemMemberCacheServer [ ] cacheServers = cache . getCacheServers ( ) ; if ( cacheServers != null ) { for ( SystemMemberCacheServer cacheServer : cacheServers ) { portsSet . add ( cacheServer . getPort ( ) ) ; } } } return portsSet ;


signature:
public class NodesController { /** * Looks for the existing pool with name poolFactory . If there is no such
 * pool , creates new one .
 * @ param host
 * - the concrete server ' s host
 * @ param port
 * - the concrete server ' s port
 * @ return found or new pool for the specified parameters */
private Pool findOrCreatePool ( String host , int port ) { } }

implementation: String poolName = Utils . toKey ( host , port ) ; Pool pool = PoolManager . find ( poolName ) ; if ( pool == null ) { poolFactory . reset ( ) ; poolFactory . addServer ( host , port ) ; pool = poolFactory . create ( poolName ) ; } return pool ;


signature:
public class RuleUtil { /** * Get the rule name from an audit event source name .
 * @ param eventSrcName the audit event source name
 * @ return the rule name , which is the class name without package and removed eventual " Check " suffix */
public static String getName ( String eventSrcName ) { } }

implementation: if ( eventSrcName == null ) { return null ; } if ( eventSrcName . endsWith ( "Check" ) ) { eventSrcName = eventSrcName . substring ( 0 , eventSrcName . length ( ) - 5 ) ; } return eventSrcName . substring ( eventSrcName . lastIndexOf ( '.' ) + 1 ) ;


signature:
public class RuleUtil { /** * Get the rule category from an audit event source name .
 * @ param eventSrcName the audit event source name
 * @ return the rule category , which is the last package name or " misc " or " extension " */
public static String getCategory ( String eventSrcName ) { } }

implementation: if ( eventSrcName == null ) { return null ; } int end = eventSrcName . lastIndexOf ( '.' ) ; eventSrcName = eventSrcName . substring ( 0 , end ) ; if ( CHECKSTYLE_PACKAGE . equals ( eventSrcName ) ) { return "misc" ; } else if ( ! eventSrcName . startsWith ( CHECKSTYLE_PACKAGE ) ) { return "extension" ; } return eventSrcName . substring ( eventSrcName . lastIndexOf ( '.' ) + 1 ) ;


signature:
public class AbstractRootDocWrapper { /** * { @ inheritDoc } */
@ Override public void printError ( final SourcePosition pos , final String msg ) { } }

implementation: wrappedRootDoc . printError ( pos , msg ) ;


signature:
public class AbstractRootDocWrapper { /** * { @ inheritDoc } */
@ Override public void printWarning ( final SourcePosition pos , final String msg ) { } }

implementation: wrappedRootDoc . printWarning ( pos , msg ) ;


signature:
public class AbstractRootDocWrapper { /** * { @ inheritDoc } */
@ Override public void printNotice ( final SourcePosition pos , final String msg ) { } }

implementation: wrappedRootDoc . printNotice ( pos , msg ) ;


signature:
public class MethodFrameCounter { /** * Increment the counter .
 * @ param className name of class to enter . */
public static void enterFrame ( String className ) { } }

implementation: int counter = local . get ( ) . incrementAndGet ( ) ; classNames . get ( ) . add ( className ) ; if ( counter == MAX_STACK_DEPTH ) { throw new RuntimeException ( STACK_OVERFLOW_MSG + getClassNames ( ) ) ; }


signature:
public class MethodFrameCounter { /** * Decrement the counter and remove class name from the list .
 * @ param className name of class to exit from . */
public static void exitFrame ( String className ) { } }

implementation: int counter = local . get ( ) . decrementAndGet ( ) ; if ( counter < 0 ) { String errorMessage = "Method frame counter is less then 0. Some programming error: count(exitFrame) > count(enterFrame)." + getClassNames ( ) ; clearCounter ( ) ; throw new RuntimeException ( errorMessage ) ; } String frameToExit = classNames . get ( ) . remove ( classNames . get ( ) . size ( ) - 1 ) ; if ( ! className . equals ( frameToExit ) ) { throw new RuntimeException ( "Method frame counter try to exit from the class '" + className + "' but must exit from the class '" + frameToExit + "' first." + getClassNames ( ) ) ; }


signature:
public class MethodFrameCounter { /** * Creates string with all classes that have been entered by method frame counter .
 * @ return String */
private static String getClassNames ( ) { } }

implementation: StringBuilder result = new StringBuilder ( "\nMethod frame counter enter to the following classes:\n" ) ; for ( String className : classNames . get ( ) ) { result . append ( className ) . append ( "\n" ) ; } return result . toString ( ) ;


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

implementation: String fieldName = field . getName ( ) ; String fullClassName = CodeGenUtils . className ( field . getType ( ) ) ; return "if (in.readByte() != 0) {\n" + CodeGenUtils . tab ( "result.set" + CodeGenUtils . firstLetterToUpperCase ( fieldName ) + "(" + "(" + fullClassName + ") " + "com.gemstone.gemfire.DataSerializer.readObject(in)" + ");\n" ) + "}\n" ;


signature:
public class CorrectPackagingRule { /** * Delegate method , implemented by concrete subclasses .
 * @ param project The active MavenProject .
 * @ param helper The EnforcerRuleHelper instance , from which the MavenProject has been retrieved .
 * @ throws RuleFailureException If the enforcer rule was not satisfied . */
@ Override @ SuppressWarnings ( "unchecked" ) protected void performValidation ( final MavenProject project , final EnforcerRuleHelper helper ) throws RuleFailureException { } }

implementation:
// Find all java source files , and map their packages to their names .
final List < String > compileSourceRoots = ( List < String > ) project . getCompileSourceRoots ( ) ; if ( compileSourceRoots . size ( ) == 0 ) { return ; } final SortedMap < String , SortedSet < String > > packageName2SourceFileNameMap = new TreeMap < String , SortedSet < String > > ( ) ; for ( String current : compileSourceRoots ) { addPackages ( new File ( current ) , packageName2SourceFileNameMap ) ; } // Retrieve the groupId of this project
final String groupId = project . getGroupId ( ) ; if ( groupId == null || groupId . equals ( "" ) ) { // Don ' t accept empty groupIds
throw new RuleFailureException ( "Maven groupId cannot be null or empty." , project . getArtifact ( ) ) ; } else { // Correct packaging everywhere ?
final SortedSet < String > incorrectPackages = new TreeSet < String > ( ) ; for ( Map . Entry < String , SortedSet < String > > currentPackage : packageName2SourceFileNameMap . entrySet ( ) ) { final String candidate = currentPackage . getKey ( ) ; if ( ! candidate . startsWith ( groupId ) ) { incorrectPackages . add ( candidate ) ; } } if ( incorrectPackages . size ( ) > 0 ) { final SortedMap < String , SortedSet < String > > result = new TreeMap < String , SortedSet < String > > ( ) ; for ( String current : incorrectPackages ) { result . put ( current , packageName2SourceFileNameMap . get ( current ) ) ; } throw new RuleFailureException ( "Incorrect packaging detected; required [" + groupId + "] but found package to file names: " + result , project . getArtifact ( ) ) ; } }


signature:
public class CorrectPackagingRule { /** * Splices the supplied packageExtractorImplementations argument , which is assumed to be a comma - separated
 * string holding fully qualified class names of the PackageExtractor implementations which should be used
 * by this CorrectPackagingRule .
 * @ param packageExtractorImplementations a comma - separated string holding fully qualified class names of the
 * PackageExtractor implementations . Each such class must have a default
 * ( i . e . no - argument ) constructor .
 * @ throws IllegalArgumentException if the supplied packageExtractorImplementations argument could not yield an
 * instantiated PackageExtractor instance . */
public final void setPackageExtractors ( final String packageExtractorImplementations ) throws IllegalArgumentException { } }

implementation:
// Check sanity
if ( packageExtractorImplementations == null ) { throw new NullPointerException ( "Cannot handle empty packageExtractorImplementations argument." ) ; } // Instantiate the PackageExtractor instances .
List < PackageExtractor > extractors = new ArrayList < PackageExtractor > ( ) ; for ( String current : splice ( packageExtractorImplementations ) ) { try { // Load the current PackageExtractor implementation class
final Class < ? > aClass = getClass ( ) . getClassLoader ( ) . loadClass ( current ) ; // The PackageExtractor implementation must have a default constructor .
// Fire , and handle any exceptions .
extractors . add ( ( PackageExtractor ) aClass . newInstance ( ) ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Could not instantiate PackageExtractor from class [" + current + "]. Validate that implementation has a default constructor, and implements the" + PackageExtractor . class . getSimpleName ( ) + " interface." ) ; } } // Assign if non - null .
if ( extractors . size ( ) > 0 ) { this . packageExtractors = extractors ; }


signature:
public class CorrectPackagingRule { /** * Adds all source file found by recursive search under sourceRoot to the
 * toPopulate List , using a width - first approach .
 * @ param fileOrDirectory The file or directory to search for packages and [ if a directory ] recursively
 * search for further source files .
 * @ param package2FileNamesMap A Map relating package names extracted by the PackageExtractors . */
private void addPackages ( final File fileOrDirectory , final SortedMap < String , SortedSet < String > > package2FileNamesMap ) { } }

implementation:
for ( PackageExtractor current : packageExtractors ) { final FileFilter sourceFileDefinitionFilter = current . getSourceFileFilter ( ) ; if ( fileOrDirectory . isFile ( ) && sourceFileDefinitionFilter . accept ( fileOrDirectory ) ) { // Single source file to add .
final String thePackage = current . getPackage ( fileOrDirectory ) ; SortedSet < String > sourceFileNames = package2FileNamesMap . get ( thePackage ) ; if ( sourceFileNames == null ) { sourceFileNames = new TreeSet < String > ( ) ; package2FileNamesMap . put ( thePackage , sourceFileNames ) ; } // Done .
sourceFileNames . add ( fileOrDirectory . getName ( ) ) ; } else if ( fileOrDirectory . isDirectory ( ) ) { // Add the immediate source files
for ( File currentChild : fileOrDirectory . listFiles ( sourceFileDefinitionFilter ) ) { addPackages ( currentChild , package2FileNamesMap ) ; } // Recurse into subdirectories
for ( File currentSubdirectory : fileOrDirectory . listFiles ( DIRECTORY_FILTER ) ) { addPackages ( currentSubdirectory , package2FileNamesMap ) ; } } }


signature:
public class LanguageImage { /** * Create the thumbnails , and make sure the parent imagefile is valid .
 * @ throws CustomConstraintViolationException */
@ PrePersist @ PreUpdate private void updateImageData ( ) throws CustomConstraintViolationException { } }

implementation: thumbnail = createImage ( true ) ; imageFile . validate ( ) ; if ( imageData != null ) { imageContentHash = HashUtilities . generateSHA256 ( imageData ) . toCharArray ( ) ; }


signature:
public class LanguageImage { /** * The UI will attempt to assign an empty value if the file upload box does not have a file selected . This method is used to
 * ignore any empty values , while passing through any legitimate file uploads . This means that the absence of a file in the
 * upload box does not indicate that no file should be assigned to the entity .
 * @ param uiOriginalFileName The image file name uploaded through the UI */
public void setUiOriginalFileName ( final String uiOriginalFileName ) { } }

implementation: this . uiOriginalFileName = uiOriginalFileName ; if ( this . uiOriginalFileName != null && ! this . uiOriginalFileName . isEmpty ( ) ) originalFileName = this . uiOriginalFileName ;


signature:
public class BucketOrientedQueryService { /** * Executes a particular query on specified region using a set of keys that represents buckets . The set of buckets is
 * determined by keys of entries that are stored in such buckets : - real and fake keys can be used ( such key should
 * have the same routing object as bucket ' s keys have ) ; - it will be enough to specify one key for each bucket . Work
 * of this method is based on execution of function .
 * @ see BucketOrientedQueryFunction
 * @ param queryString OQL query string .
 * @ param region Partitioned region on which query will be executed .
 * @ param keys Set of keys that specify buckets .
 * @ return Query results as instance of { @ link SelectResults } .
 * @ throws QueryException When in case of query execution failure . */
@ SuppressWarnings ( { } }

implementation: "unchecked" } ) public static SelectResults < Object > executeOnBuckets ( String queryString , Region region , Set < Object > keys ) throws QueryException { return executeOnBuckets ( queryString , null , region , keys ) ;


signature:
public class BucketOrientedQueryService { /** * Executes a particular query with parameters on specified region using a set of keys that represents buckets . The
 * set of buckets is determined by keys of entries that are stored in such buckets : - real and fake keys can be used
 * ( such key should have the same routing object as bucket ' s keys have ) ; - it will be enough to specify one key for
 * each bucket . Work of this method is based on execution of function .
 * @ see BucketOrientedQueryFunction
 * @ param queryString OQL query string .
 * @ param queryParameters Query parameters .
 * @ param region Partitioned region on which query will be executed .
 * @ param keys Set of keys that specify buckets .
 * @ return Query results as instance of { @ link SelectResults } .
 * @ throws QueryException When in case of query execution failure . */
@ SuppressWarnings ( { } }

implementation: "unchecked" } ) public static SelectResults < Object > executeOnBuckets ( String queryString , Object [ ] queryParameters , Region region , Set < Object > keys ) throws QueryException { if ( ( queryString == null ) || ( queryString . length ( ) == 0 ) ) { throw new QueryException ( "You must specify query string for execution." ) ; } int limit = extractLimit ( queryString ) ; BucketOrientedQueryFunctionArgument functionArgument = new BucketOrientedQueryFunctionArgument ( queryString , queryParameters ) ; BucketOrientedQueryFunction function = new BucketOrientedQueryFunction ( ) ; FunctionService . registerFunction ( function ) ; List < List < Object > > queryResults ; try { queryResults = ( List < List < Object > > ) FunctionService . onRegion ( region ) . withFilter ( keys ) . withArgs ( functionArgument ) . execute ( function ) . getResult ( ) ; } catch ( FunctionException e ) { logger . error ( "Failed to execute bucket oriented query function: " + function , e ) ; throw new QueryException ( e . getMessage ( ) ) ; } return formatSelectResults ( queryResults , limit ) ;


signature:
public class BucketOrientedQueryService { /** * Extracts limit value from query string .
 * @ param queryString OQL query string .
 * @ return Value of ' limit ' clause . */
private static int extractLimit ( String queryString ) { } }

implementation: int limitIndex = queryString . lastIndexOf ( "limit" ) ; if ( limitIndex == - 1 ) { limitIndex = queryString . lastIndexOf ( "LIMIT" ) ; } if ( limitIndex == - 1 ) { return limitIndex ; } String limitValue = queryString . substring ( limitIndex + 5 ) ; return Integer . parseInt ( limitValue . trim ( ) ) ;


signature:
public class BucketOrientedQueryService { /** * Collects and formats query results into SelectResults . Limits query results based on limit value .
 * @ param queryResults Query results from several nodes .
 * @ param limit Query results limit .
 * @ return Aggregated query results represented by instance of { @ link SelectResults } . */
@ SuppressWarnings ( { } }

implementation: "unchecked" } ) private static SelectResults < Object > formatSelectResults ( List < List < Object > > queryResults , int limit ) { List < Object > list = new ArrayList < Object > ( ) ; ObjectType baseElementType = null ; for ( List < Object > queryResult : queryResults ) { ObjectType elementType = ( ObjectType ) queryResult . remove ( queryResult . size ( ) - 1 ) ; if ( baseElementType == null ) { baseElementType = elementType ; } else if ( ! baseElementType . equals ( elementType ) ) { throw new IllegalStateException ( "Collection types for query result are different." ) ; } list . addAll ( queryResult ) ; if ( limit != - 1 && list . size ( ) >= limit ) { break ; } } return limit == - 1 ? new ResultsCollectionWrapper ( baseElementType , list ) : new ResultsCollectionWrapper ( baseElementType , list , limit ) ;


signature:
public class RTSupport { /** * With stack counter
 * @ param obj
 * @ param depth of
 * @ throws InvalidClassException */
private static void checkAllowedInRealTime0 ( Object obj , int depth ) throws InvalidClassException { } }

implementation:
if ( depth >= MethodFrameCounter . MAX_STACK_DEPTH ) { // todo : correct > ? or > = ?
throw new RuntimeException ( ) ; } Class < ? > clazz = obj . getClass ( ) ; if ( clazz . getName ( ) . startsWith ( "java." ) || clazz . getName ( ) . startsWith ( "javax." ) ) { checkAllowedInCompileTimeJdkType ( clazz ) ; } else { checkAllowedInCompileTimeCustomType ( clazz ) ; } // array
if ( clazz . isArray ( ) ) { final int length = Array . getLength ( obj ) ; for ( int k = 0 ; k < length ; k ++ ) { Object elem = Array . get ( obj , k ) ; checkAllowedInRealTime0 ( elem , depth + 1 ) ; } } // Collection
if ( Collection . class . isAssignableFrom ( clazz ) ) { for ( Object elem : ( ( Collection ) obj ) ) { checkAllowedInRealTime0 ( elem , depth + 1 ) ; } } // Map
if ( Map . class . isAssignableFrom ( clazz ) ) { for ( Map . Entry < Object , Object > elem : ( ( Map < Object , Object > ) obj ) . entrySet ( ) ) { checkAllowedInRealTime0 ( elem . getKey ( ) , depth + 1 ) ; checkAllowedInRealTime0 ( elem . getValue ( ) , depth + 1 ) ; } }


signature:
public class JavaProcessLauncher { /** * Runs process with arguments based on a specified class in a separate VM .
 * Waits while process is working and returns exit code after process
 * finished .
 * @ param id TODO
 * @ param klass
 * of type Class
 * @ param javaArguments
 * arguments for java
 * @ param processArguments
 * arguments for process
 * @ return int
 * @ throws IOException
 * when
 * @ throws InterruptedException
 * when */
public int runAndWaitProcessExitCode ( String id , Class < ? > klass , String [ ] javaArguments , String [ ] processArguments ) throws IOException , InterruptedException { } }

implementation: Process process = startProcess ( id , klass , javaArguments , processArguments , false ) ; process . waitFor ( ) ; return process . exitValue ( ) ;


signature:
public class JavaProcessLauncher { /** * Runs a process and returns the Process object .
 * @ param id TODO
 * @ param clazz
 * - the class to run
 * @ param javaArguments
 * arguments for java
 * @ param processArguments
 * arguments for process
 * @ return - the Process object representing running process
 * @ throws IOException
 * @ throws InterruptedException */
public Process runWithoutConfirmation ( String id , Class < ? > clazz , String [ ] javaArguments , String [ ] processArguments ) throws IOException , InterruptedException { } }

implementation: return startProcess ( id , clazz , javaArguments , processArguments , false ) ;


signature:
public class JavaProcessLauncher { /** * Runs process based on a specified class in a separate VM using array of
 * arguments . To confirm that process completes startup it should write a
 * startup completed string into it ' s standard output .
 * @ param id
 * the process identifier .
 * @ param klass
 * of type Class .
 * @ param javaArguments
 * arguments for java .
 * @ param processArguments
 * arguments for process .
 * @ return Process the started process .
 * @ throws IOException
 * when
 * @ throws InterruptedException
 * when */
public Process runWithConfirmation ( String id , Class < ? > klass , String [ ] javaArguments , String [ ] processArguments ) throws IOException , InterruptedException { } }

implementation: Process process = startProcess ( id , klass , javaArguments , processArguments , true ) ; waitConfirmation ( klass . getSimpleName ( ) , process ) ; new StreamRedirector ( process . getInputStream ( ) , klass . getSimpleName ( ) + PROCESS_STDOUT_STREAM_PREFIX , redirectProcessInputStreamToParentProcessStdOut ) . start ( ) ; return process ;


signature:
public class JavaProcessLauncher { /** * Runs process with arguments based on a specified class in a separate VM .
 * Waits DEFAULT _ PROCESS _ STARTUP _ TIME before returns the created process to
 * a caller .
 * @ param klass
 * of type Class
 * @ param javaArguments
 * arguments for java
 * @ param processArguments
 * arguments for process
 * @ return Process
 * @ throws IOException
 * when
 * @ throws InterruptedException
 * when
 * @ throws TimeoutException
 * when */
public Process runWithStartupDelay ( Class < ? > klass , String [ ] javaArguments , String [ ] processArguments ) throws IOException , InterruptedException , TimeoutException { } }

implementation: return runWithStartupDelay ( klass , javaArguments , processArguments , DEFAULT_PROCESS_STARTUP_SHUTDOWN_TIME ) ;


signature:
public class JavaProcessLauncher { /** * Runs process with arguments based on a specified class in a separate VM .
 * Waits processStartupTime before returns the created process to a caller .
 * @ param klass
 * of type Class
 * @ param processStartupTime
 * time in milliseconds that launcher spend on waiting process
 * after it ' s start .
 * @ param javaArguments
 * arguments for java
 * @ param processArguments
 * arguments for process
 * @ return Process
 * @ throws IOException
 * when
 * @ throws InterruptedException
 * when
 * @ throws TimeoutException
 * if process startup is not completed in time . */
public Process runWithStartupDelay ( Class < ? > klass , String [ ] javaArguments , String [ ] processArguments , long processStartupTime ) throws IOException , InterruptedException , TimeoutException { } }

implementation: Process process = runWithConfirmation ( "" , klass , javaArguments , processArguments ) ; if ( processStartupTime > 0 ) { Thread . sleep ( processStartupTime ) ; } return process ;


signature:
public class JavaProcessLauncher { /** * Stops process by sending new line to it ' s output stream .
 * The process can be stopped by calling destroy ( ) method .
 * @ param process
 * of type Process
 * @ throws IOException
 * when
 * @ throws InterruptedException */
public void stopBySendingNewLineIntoProcess ( Process process ) throws IOException , InterruptedException { } }

implementation: if ( process != null ) { BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( process . getOutputStream ( ) ) ) ; writer . newLine ( ) ; writer . flush ( ) ; process . waitFor ( ) ; }


signature:
public class JavaProcessLauncher { /** * Starts process based on specified class using command line arguments .
 * This process inherits a classpath from parent VM that starts it .
 * @ param klass
 * of type Class
 * @ param javaArguments
 * of type String [ ]
 * @ param processArguments
 * of type String [ ]
 * @ param withConfirmation
 * of type boolean
 * @ return Process
 * @ throws IOException
 * when
 * @ throws InterruptedException
 * when */
private Process startProcess ( String id , Class < ? > klass , String [ ] javaArguments , String [ ] processArguments , boolean withConfirmation ) throws IOException , InterruptedException { } }

implementation: List < String > arguments = createCommandLineForProcess ( klass , javaArguments , processArguments ) ; Process process = new ProcessBuilder ( arguments ) . start ( ) ; redirectProcessStreams ( id , klass , process , ! withConfirmation ) ; return process ;


signature:
public class JavaProcessLauncher { /** * Redirects process standard output and error streams into parent process
 * standard output .
 * @ param klass
 * of type Class
 * @ param process
 * of type Process
 * @ param redirectProcessStdOut
 * of type boolean */
private void redirectProcessStreams ( String id , Class < ? > klass , Process process , boolean redirectProcessStdOut ) { } }

implementation: String errorStreamType = ( printType ? klass . getSimpleName ( ) + id + PROCESS_ERROR_STREAM_PREFIX : "" ) ; new StreamRedirector ( process . getErrorStream ( ) , errorStreamType , redirectProcessErrorStreamToParentProcessStdOut , System . err ) . start ( ) ; if ( redirectProcessStdOut ) { String outputStreamType = ( printType ? klass . getSimpleName ( ) + id + PROCESS_STDOUT_STREAM_PREFIX : "" ) ; new StreamRedirector ( process . getInputStream ( ) , outputStreamType , redirectProcessInputStreamToParentProcessStdOut , System . out ) . start ( ) ; }


signature:
public class JavaProcessLauncher { /** * Builds command line for starting java process based on specified
 * arguments .
 * @ param klazz
 * @ param processArguments
 * of type String [ ]
 * @ return List < String > */
private List < String > createCommandLineForProcess ( Class < ? > klazz , String [ ] processArguments ) { } }

implementation: return createCommandLineForProcess ( klazz , null , processArguments ) ;


signature:
public class JavaProcessLauncher { /** * Builds command line for starting java process based on specified
 * arguments .
 * @ param klazz
 * @ param javaArguments
 * of type String [ ]
 * @ param processArguments
 * of type String [ ]
 * @ return List < String > */
private List < String > createCommandLineForProcess ( Class < ? > klazz , String [ ] javaArguments , String [ ] processArguments ) { } }

implementation: String javaHome = System . getProperty ( "java.home" ) ; String javaBin = javaHome + File . separator + "bin" + File . separator + "java" ; String classpath = System . getProperty ( "java.class.path" ) ; List < String > argumentsList = new ArrayList < String > ( ) ; argumentsList . add ( javaBin ) ; argumentsList . add ( "-cp" ) ; argumentsList . add ( classpath ) ; if ( javaArguments != null && javaArguments . length > 0 ) { argumentsList . addAll ( Arrays . asList ( javaArguments ) ) ; } argumentsList . add ( klazz . getCanonicalName ( ) ) ; if ( processArguments != null && processArguments . length > 0 ) { argumentsList . addAll ( Arrays . asList ( processArguments ) ) ; } return argumentsList ;


signature:
public class JavaProcessLauncher { /** * Waits startup complete confirmation from process .
 * @ param className
 * of type String
 * @ param process
 * of type Process
 * @ throws IOException
 * when
 * @ throws InterruptedException
 * when */
private void waitConfirmation ( String className , Process process ) throws IOException , InterruptedException { } }

implementation: System . out . println ( "Waiting startup complete confirmation for a process (" + className + ")..." ) ; BufferedReader bufferedReader = new BufferedReader ( new InputStreamReader ( process . getInputStream ( ) ) ) ; String line ; while ( ( line = bufferedReader . readLine ( ) ) != null ) { if ( line . equals ( PROCESS_STARTUP_COMPLETED ) ) { System . out . println ( "The process (" + className + ") has been started successfully" ) ; return ; } else if ( redirectProcessInputStreamToParentProcessStdOut ) { System . out . println ( className + PROCESS_STDOUT_STREAM_PREFIX + line ) ; } } throw new InterruptedException ( "Process (" + className + ") " + "has been already finished without startup complete confirmation" ) ;


signature:
public class VisualizationWrappedRootDocConverter { /** * { @ inheritDoc } */
@ Override protected Graph doConvert ( final VisualizationWrappedRootDoc toConvert ) { } }

implementation:
final Graph toReturn = new Graph ( ) ; // Create subgraphs for each package and add them to the returned Graph .
toConvert . sortClassesPerPackage ( ) . forEach ( ( packageDoc , classDocs ) -> toReturn . add ( convertPackage ( packageDoc , classDocs ) ) ) ; // All Done .
return toReturn ;


signature:
public class VelocityTemplate { /** * Using a specified Velocity Template and provided context , create the outputFilename .
 * @ param outputFilename the file to be generated .
 * @ param template the velocity template to use .
 * @ param context the velocity context map .
 * @ throws VelocityException if the template was not found or any other Velocity exception .
 * @ throws MojoExecutionException
 * @ throws IOException */
public void generate ( String outputFilename , String template , Context context ) throws VelocityException , MojoExecutionException , IOException { } }

implementation:
Writer writer = null ; try { File f = new File ( outputFilename ) ; if ( ! f . getParentFile ( ) . exists ( ) ) { f . getParentFile ( ) . mkdirs ( ) ; } writer = new FileWriter ( f ) ; getVelocity ( ) . getEngine ( ) . mergeTemplate ( templateDirectory + "/" + template , context , writer ) ; } catch ( ResourceNotFoundException e ) { throw new ResourceNotFoundException ( "Template not found: " + templateDirectory + "/" + template , e ) ; } catch ( VelocityException | IOException e ) { throw e ; // to get past generic catch for Exception .
} catch ( Exception e ) { throw new MojoExecutionException ( e . getMessage ( ) , e ) ; } finally { if ( writer != null ) { writer . flush ( ) ; writer . close ( ) ; getLog ( ) . debug ( "File " + outputFilename + " created..." ) ; } }


signature:
public class CheckstyleCheckerListener { /** * { @ inheritDoc } */
public void fileStarted ( AuditEvent event ) { } }

implementation: final String fileName = StringUtils . replace ( event . getFileName ( ) , "\\" , "/" ) ; for ( File sourceDirectory : sourceDirectories ) { String sourceDirectoryPath = StringUtils . replace ( sourceDirectory . getPath ( ) , "\\" , "/" ) ; if ( fileName . startsWith ( sourceDirectoryPath + "/" ) ) { currentFile = StringUtils . substring ( fileName , sourceDirectoryPath . length ( ) + 1 ) ; events = getResults ( ) . getFileViolations ( currentFile ) ; break ; } } if ( events == null ) { events = new ArrayList < > ( ) ; }


signature:
public class CheckstyleCheckerListener { /** * { @ inheritDoc } */
public void addError ( AuditEvent event ) { } }

implementation: if ( SeverityLevel . IGNORE . equals ( event . getSeverityLevel ( ) ) ) { return ; } if ( severityLevel == null || severityLevel . equals ( event . getSeverityLevel ( ) ) ) { events . add ( event ) ; }


signature:
public class ReplicationProcessor { /** * Creates , configures and runs the guest nodes and collects information
 * form them
 * @ return - 0 in case of success , 1 otherwise
 * @ throws IOException
 * @ throws InterruptedException */
public int process ( ) throws IOException , InterruptedException { } }

implementation: debug ( "ReplicationProcessor#process(): Processing start" ) ; Properties gemfireProperties = PropertiesHelper . filterProperties ( System . getProperties ( ) , "gemfire." ) ; String [ ] vmOptions = PropertiesHelper . propertiesToVMOptions ( gemfireProperties ) ; debug ( "ReplicationProcessor#process(): vmOptions = " + Arrays . asList ( vmOptions ) ) ; List < Process > processesList = new ArrayList < Process > ( ) ; for ( Object keyObject : clustersProperties . keySet ( ) ) { String cluster = ( String ) keyObject ; String clustersPropertiesString = PropertiesHelper . propertiesToString ( clustersProperties ) ; debug ( "ReplicationProcessor#process(): Starting GuestNode with parameters: cluster = " + cluster + ", clustersPropertiesString = " + clustersPropertiesString + ", timeout = " + timeout + ", regionName = " + regionName ) ; Process process = javaProcessLauncher . runWithoutConfirmation ( "" , GuestNode . class , vmOptions , new String [ ] { cluster , clustersPropertiesString , String . valueOf ( timeout ) , regionName , String . valueOf ( debugEnabled ) , String . valueOf ( quiet ) , String . valueOf ( processingStartedAt ) } ) ; debug ( "ReplicationProcessor#process(): Adding GuestNode to processList" ) ; processesList . add ( process ) ; } debug ( "ReplicationProcessor#process(): Waiting for processes finish" ) ; int mainExitCode = 0 ; int processNumber = 0 ; for ( Process process : processesList ) { debug ( "ReplicationProcessor#process(): Waiting for process #" + processNumber ) ; int exitCode = process . waitFor ( ) ; if ( exitCode != 0 ) { mainExitCode = 1 ; } debug ( "ReplicationProcessor#process(): Process #" + processNumber + " finished with exitCode = " + exitCode ) ; processNumber ++ ; } debug ( "ReplicationProcessor#process(): Processing finished with mainExitCode = " + mainExitCode ) ; return mainExitCode ;


signature:
public class ReplicationProcessor { /** * Prints debug information if the debug is enabled
 * @ param message
 * - the debug message */
private void debug ( String message ) { } }

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


signature:
public class ValidationAspect { /** * Defines a Pointcut for any constructor to a class implementing Validatable .
 * The Pointcut will return { @ code true } for all non - default Constructors , i . e . when the signature
 * of the JoinPoint has more than 0 arguments .
 * @ param joinPoint The currently executing joinPoint . */
@ Pointcut ( value = "initialization(se.jguru.nazgul.tools.validation.api.Validatable+.new(..)) && if()" , argNames = "joinPoint" ) public static boolean anyNonDefaultConstructor ( final JoinPoint joinPoint ) { } }

implementation:
// Extract the JoinPoint signature .
final Signature signature = joinPoint . getSignature ( ) ; final boolean isConstructorSignature = signature instanceof ConstructorSignature ; if ( isConstructorSignature ) { final Constructor constructor = ( ( ConstructorSignature ) signature ) . getConstructor ( ) ; final boolean isNonDefaultConstructor = constructor != null && constructor . getParameters ( ) . length > 0 ; log . trace ( "Non-Default Constructor signature [" + signature . toString ( ) + "] for [" + ( constructor == null ? "<null>" : constructor . toString ( ) ) + "]: " + isNonDefaultConstructor ) ; // All Done .
return isNonDefaultConstructor ; } else { log . debug ( "Found non-constructor signature: " + signature ) ; } // Nopes .
return false ;


signature:
public class ValidationAspect { /** * Aspect invoking the { @ link Validatable # validateInternalState ( ) } method before returning from any non - default
 * constructor within a class implementing { @ link Validatable } .
 * @ param joinPoint The currently executing joinPoint .
 * @ throws InternalStateValidationException if the validation of the { @ link Validatable } failed . */
@ AfterReturning ( value = "anyNonDefaultConstructor(joinPoint) && target(aValidatable)" , argNames = "joinPoint, aValidatable" ) public void performValidationAfterCompoundConstructor ( final JoinPoint joinPoint , final Validatable aValidatable ) throws InternalStateValidationException { } }

implementation:
if ( log . isDebugEnabled ( ) ) { log . debug ( "Validating instance of type [" + aValidatable . getClass ( ) . getName ( ) + "]" ) ; } if ( joinPoint . getStaticPart ( ) == null ) { log . warn ( "Static part of join point was null for validatable of type: " + aValidatable . getClass ( ) . getName ( ) , new IllegalStateException ( ) ) ; return ; } // Ignore calling validateInternalState when we execute constructors in
// any class but the concrete Validatable class .
final ConstructorSignature sig = ( ConstructorSignature ) joinPoint . getSignature ( ) ; final Class < ? > constructorDefinitionClass = sig . getConstructor ( ) . getDeclaringClass ( ) ; if ( aValidatable . getClass ( ) == constructorDefinitionClass ) { // Now fire the validateInternalState method .
aValidatable . validateInternalState ( ) ; } else { log . debug ( "Ignored firing validatable for constructor defined in [" + constructorDefinitionClass . getName ( ) + "] and Validatable of type [" + aValidatable . getClass ( ) . getName ( ) + "]" ) ; }


signature:
public class InProcExample { /** * You can use services in process */
public static void example1 ( String ... args ) { } }

implementation:
/* Synchronous service . */
final TodoManager todoManagerImpl = new TodoManager ( ) ; /* Create the service which manages async calls to todoManagerImpl . */
final ServiceQueue serviceQueue = serviceBuilder ( ) . setServiceObject ( todoManagerImpl ) . build ( ) . startServiceQueue ( ) ; /* Create Asynchronous proxy over Synchronous service . */
final TodoManagerClientInterface todoManager = serviceQueue . createProxy ( TodoManagerClientInterface . class ) ; serviceQueue . startCallBackHandler ( ) ; System . out . println ( "This is an async call" ) ; /* Asynchronous method call . */
todoManager . add ( new Todo ( "Call Mom" , "Give Mom a call" ) ) ; AtomicInteger countTracker = new AtomicInteger ( ) ; // Hold count from async call to service
System . out . println ( "This is an async call to count" ) ; todoManager . count ( count -> { System . out . println ( "This lambda expression is the callbackWithTimeout " + count ) ; countTracker . set ( count ) ; } ) ; todoManager . clientProxyFlush ( ) ; // Flush all methods . It batches calls .
Sys . sleep ( 100 ) ; System . out . printf ( "This is the count back from the server %d\n" , countTracker . get ( ) ) ; System . out . printf ( "END EXAMPLE 1 %s \n" , countTracker . get ( ) ) ; System . out . printf ( "END EXAMPLE 1 %s \n" , countTracker . get ( ) ) ; System . out . printf ( "END EXAMPLE 1 %s \n" , countTracker . get ( ) ) ; System . out . printf ( "END EXAMPLE 1 %s \n" , countTracker . get ( ) ) ;


signature:
public class InProcExample { /** * You can use services in process */
public static void example2 ( String ... args ) { } }

implementation:
/* Synchronous service . */
final TodoManager todoManagerImpl = new TodoManager ( ) ; /* Create the service which manages async calls to todoManagerImpl .
 You can control the batch size of methods .
 After it hits so many , it sends those methods to the service .
 This allows threads to handle many method calls with on access of the queue .
 Here we set it to 1 so it will flush with every call .
 Setting invoke dynamic false turns off auto type conversion which is mainly for JSON REST calls
 and WebSocket calls .
 This means that you can execute the service more efficiently when it is in proc . */
final ServiceQueue serviceQueue = serviceBuilder ( ) . setRequestQueueBuilder ( queueBuilder ( ) . setBatchSize ( 1 ) ) . setServiceObject ( todoManagerImpl ) . setInvokeDynamic ( false ) . build ( ) . startServiceQueue ( ) ; /* Create Asynchronous proxy over Synchronous service . */
final TodoManagerClientInterface todoManager = serviceQueue . createProxy ( TodoManagerClientInterface . class ) ; serviceQueue . startCallBackHandler ( ) ; System . out . println ( "This is an async call" ) ; /* Asynchronous method call . */
todoManager . add ( new Todo ( "Call Mom" , "Give Mom a call" ) ) ; AtomicInteger countTracker = new AtomicInteger ( ) ; // Hold count from async call to service
System . out . println ( "This is an async call to count" ) ; todoManager . count ( count -> { System . out . println ( "This lambda expression is the callbackWithTimeout " + count ) ; countTracker . set ( count ) ; } ) ; /* We don ' t need this now . */
// todoManager . clientProxyFlush ( ) ; / / Flush all methods . It batches calls .
Sys . sleep ( 100 ) ; System . out . printf ( "This is the count back from the service %d\n" , countTracker . get ( ) ) ; todoManager . list ( todos -> todos . forEach ( System . out :: println ) ) ;


signature:
public class Types { /** * Is the genericType of a certain class ? */
public static boolean isA ( Class clazz , ParameterizedType pType ) { } }

implementation: return clazz . isAssignableFrom ( ( Class ) pType . getRawType ( ) ) ;


signature:
public class Types { /** * See if the two methods are compatible , that is they have the same
 * relative signature
 * @ param method
 * @ param intfMethod
 * @ return */
public static boolean isCompatible ( Method method , Method intfMethod ) { } }

implementation: if ( method == intfMethod ) return true ; if ( ! method . getName ( ) . equals ( intfMethod . getName ( ) ) ) return false ; if ( method . getParameterTypes ( ) . length != intfMethod . getParameterTypes ( ) . length ) return false ; for ( int i = 0 ; i < method . getParameterTypes ( ) . length ; i ++ ) { Class rootParam = method . getParameterTypes ( ) [ i ] ; Class intfParam = intfMethod . getParameterTypes ( ) [ i ] ; if ( ! intfParam . isAssignableFrom ( rootParam ) ) return false ; } return true ;


signature:
public class Types { /** * Given a method and a root class , find the actual method declared in the
 * root that implements the method .
 * @ param clazz
 * @ param intfMethod
 * @ return */
public static Method getImplementingMethod ( Class clazz , Method intfMethod ) { } }

implementation:
Class < ? > declaringClass = intfMethod . getDeclaringClass ( ) ; if ( declaringClass . equals ( clazz ) ) return intfMethod ; Class [ ] paramTypes = intfMethod . getParameterTypes ( ) ; if ( declaringClass . getTypeParameters ( ) . length > 0 && paramTypes . length > 0 ) { Type [ ] intfTypes = findParameterizedTypes ( clazz , declaringClass ) ; Map < String , Type > typeVarMap = new HashMap < String , Type > ( ) ; TypeVariable < ? extends Class < ? > > [ ] vars = declaringClass . getTypeParameters ( ) ; for ( int i = 0 ; i < vars . length ; i ++ ) { if ( intfTypes != null && i < intfTypes . length ) { typeVarMap . put ( vars [ i ] . getName ( ) , intfTypes [ i ] ) ; } else { // Interface type parameters may not have been filled out
typeVarMap . put ( vars [ i ] . getName ( ) , vars [ i ] . getGenericDeclaration ( ) ) ; } } Type [ ] paramGenericTypes = intfMethod . getGenericParameterTypes ( ) ; paramTypes = new Class [ paramTypes . length ] ; for ( int i = 0 ; i < paramTypes . length ; i ++ ) { if ( paramGenericTypes [ i ] instanceof TypeVariable ) { TypeVariable tv = ( TypeVariable ) paramGenericTypes [ i ] ; Type t = typeVarMap . get ( tv . getName ( ) ) ; if ( t == null ) { throw new RuntimeException ( "Unable to resolve type variable" ) ; } paramTypes [ i ] = getRawType ( t ) ; } else { paramTypes [ i ] = getRawType ( paramGenericTypes [ i ] ) ; } } } try { return clazz . getMethod ( intfMethod . getName ( ) , paramTypes ) ; } catch ( NoSuchMethodException e ) { } try { Method tmp = clazz . getMethod ( intfMethod . getName ( ) , intfMethod . getParameterTypes ( ) ) ; return tmp ; } catch ( NoSuchMethodException e ) { } return intfMethod ;


signature:
public class Types { /** * Returns the type argument from a parameterized type
 * @ param genericType
 * @ return null if there is no type parameter */
public static Class < ? > getTypeArgument ( Type genericType ) { } }

implementation: if ( ! ( genericType instanceof ParameterizedType ) ) return null ; ParameterizedType parameterizedType = ( ParameterizedType ) genericType ; Class < ? > typeArg = ( Class < ? > ) parameterizedType . getActualTypeArguments ( ) [ 0 ] ; return typeArg ;


signature:
public class Types { /** * Finds an actual value of a type variable . The method looks in a class
 * hierarchy for a class defining the variable and returns the value if
 * present .
 * @ param root
 * @ param typeVariable
 * @ return actual type of the type variable */
public static Type resolveTypeVariable ( Class < ? > root , TypeVariable < ? > typeVariable ) { } }

implementation: if ( typeVariable . getGenericDeclaration ( ) instanceof Class < ? > ) { Class < ? > classDeclaringTypeVariable = ( Class < ? > ) typeVariable . getGenericDeclaration ( ) ; Type [ ] types = findParameterizedTypes ( root , classDeclaringTypeVariable ) ; if ( types == null ) return null ; for ( int i = 0 ; i < types . length ; i ++ ) { TypeVariable < ? > tv = classDeclaringTypeVariable . getTypeParameters ( ) [ i ] ; if ( tv . equals ( typeVariable ) ) { return types [ i ] ; } } } return null ;


signature:
public class Types { /** * Given a class and an interfaces , go through the class hierarchy to find
 * the interface and return its type arguments .
 * @ param classToSearch
 * @ param interfaceToFind
 * @ return type arguments of the interface */
public static Type [ ] getActualTypeArgumentsOfAnInterface ( Class < ? > classToSearch , Class < ? > interfaceToFind ) { } }

implementation: Type [ ] types = findParameterizedTypes ( classToSearch , interfaceToFind ) ; if ( types == null ) throw new RuntimeException ( "Unable to find type arguments of " + interfaceToFind ) ; return types ;


signature:
public class Types { /** * Search for the given interface or class within the root ' s class / interface
 * hierarchy . If the searched for class / interface is a generic return an
 * array of real types that fill it out .
 * @ param root
 * @ param searchedFor
 * @ return */
public static Type [ ] findParameterizedTypes ( Class < ? > root , Class < ? > searchedFor ) { } }

implementation: if ( searchedFor . isInterface ( ) ) { return findInterfaceParameterizedTypes ( root , null , searchedFor ) ; } return findClassParameterizedTypes ( root , null , searchedFor ) ;


signature:
public class RedisKeyValueStoreBuilder { /** * RedisKeyValueStoreBuilder redis : / / redisdb : < password > @ < host > : < port > / 0
 * @ return this */
public RedisKeyValueStoreBuilder setRedisUri ( final URI uri ) { } }

implementation: getRedisOptions ( ) . setPort ( uri . getPort ( ) ) ; getRedisOptions ( ) . setHost ( uri . getHost ( ) ) ; final String userInfo = uri . getUserInfo ( ) ; final String [ ] split = Str . split ( userInfo ) ; if ( split . length == 2 ) { getRedisOptions ( ) . setAuth ( split [ 1 ] ) ; } else if ( split . length == 1 ) { getRedisOptions ( ) . setAuth ( split [ 0 ] ) ; } return this ;


signature:
public class AutoPopulateGenericObjectPool { /** * Populate the pool up to minIdle instances . Is limited to maxIdle and maxActive .
 * @ throws Exception when could not borrow or return objects to the pool */
private void populate ( ) throws Exception { } }

implementation: List < T > initializer = new ArrayList < T > ( this . getMinIdle ( ) ) ; for ( int idx = 0 ; idx < this . getMinIdle ( ) && ( this . getMaxIdle ( ) == DISABLED || idx < this . getMaxIdle ( ) ) && ( this . getMaxActive ( ) == DISABLED || idx < this . getMaxActive ( ) ) ; idx ++ ) { initializer . add ( this . borrowObject ( ) ) ; } for ( int idx = 0 ; idx < this . getMinIdle ( ) && ( this . getMaxIdle ( ) == DISABLED || idx < this . getMaxIdle ( ) ) && ( this . getMaxActive ( ) == DISABLED || idx < this . getMaxActive ( ) ) ; idx ++ ) { this . returnObject ( initializer . get ( idx ) ) ; }


signature:
public class WekaThreadSafeScorerPassthrough { /** * The the given < code > Object [ ] < / code > with this scorer ( thread safe ! ) .
 * The score in bound by the configuration < code > minScore < / code > and < code > maxScore < / code > .
 * @ param scorable the scorable data to score
 * @ return the score value already bound the configuration range
 * @ throws FOSException when classification was not possible */
@ Override public double [ ] score ( Object [ ] scorable ) throws FOSException { } }

implementation: return WekaUtils . score ( classifier , scorable , instanceSetters , instances , attributes ) ;


signature:
public class SEIProcessor { /** * Used for non exception return option
 * @ param method
 * @ param returnBuilder */
private void addReturnOptionDescription ( Method method , Return . ReturnBuilder returnBuilder ) { } }

implementation: DocReturn returnAnno = getNonExceptionDocReturn ( method ) ; String returnOptionDesc = ( returnAnno == null ) ? null : returnAnno . description ( ) ; returnBuilder . description ( StringUtils . isEmpty ( returnOptionDesc ) ? null : returnAnno . description ( ) ) ;


signature:
public class WekaThreadSafeScorerPool { /** * The the given < code > Object [ ] < / code > with this scorer ( thread safe ! ) .
 * The score in bound by the configuration < code > minScore < / code > and < code > maxScore < / code > .
 * @ param scorable the scorable data to score
 * @ return the score value already bound the configuration range
 * @ throws FOSException when classification was not possible */
@ Override public double [ ] score ( Object [ ] scorable ) throws FOSException { } }

implementation:
/* the pool can change while this is processing ( reload ) so assign a local variable */
final ObjectPool < Classifier > localPool = pool ; Classifier classifier = null ; try { classifier = localPool . borrowObject ( ) ; return WekaUtils . score ( classifier , scorable , instanceSetters , instances , attributes ) ; } catch ( Exception e ) { throw new FOSException ( e ) ; } finally { returnObject ( localPool , classifier ) ; }


signature:
public class WekaThreadSafeScorerPool { /** * Returns the given object to the pool .
 * @ param pool The pool to where return the object to .
 * @ param object The object to be returned to the pool . */
private void returnObject ( ObjectPool < Classifier > pool , Classifier object ) { } }

implementation: try { pool . returnObject ( object ) ; } catch ( Exception e ) { logger . error ( "Could not return object to pool" , e ) ; }


signature:
public class JmsService { /** * Get the destination .
 * @ param destinationName destinationName
 * @ return JMS destination which is a queue or topic . */
private Destination getDestination ( final String destinationName ) { } }

implementation: if ( ! destinations . containsKey ( destinationName ) ) { Destination destination = destinationSupplier . apply ( destinationName ) ; destinations . put ( destinationName , destination ) ; } return destinations . get ( destinationName ) ;


signature:
public class JmsService { /** * Get the ` MessageConsumer ` .
 * @ param destinationName destinationName
 * @ return JMS ` MessageConsumer ` . */
private MessageConsumer getConsumer ( final String destinationName ) { } }

implementation: if ( ! consumers . containsKey ( destinationName ) ) { Session session = getSession ( ) ; Destination destination = getDestination ( destinationName ) ; try { MessageConsumer consumer = session . createConsumer ( destination ) ; consumers . put ( destinationName , consumer ) ; } catch ( JMSException e ) { throw new JmsException ( "Unable to create consumer for destination " + destinationName , e ) ; } } return consumers . get ( destinationName ) ;


signature:
public class JmsService { /** * Get the ` MessageProducer ` or create one from the JMS session .
 * @ param destinationName destinationName
 * @ return JMS ` MessageProducer ` . */
private MessageProducer getProducer ( final String destinationName ) { } }

implementation: if ( ! producers . containsKey ( destinationName ) ) { Session session = getSession ( ) ; Destination destination = getDestination ( destinationName ) ; MessageProducer producer ; try { producer = session . createProducer ( destination ) ; } catch ( JMSException e ) { throw new JmsException ( "Unable to create producer for destination " + destinationName , e ) ; } producers . put ( destinationName , producer ) ; } return producers . get ( destinationName ) ;


signature:
public class JmsService { /** * Get the current session or create one from the JMS connection .
 * @ return JMS Session */
private Session getSession ( ) { } }

implementation: if ( ! sessionOption . isPresent ( ) ) { try { sessionOption = Optional . of ( getConnection ( ) . createSession ( transacted , acknowledgeMode ) ) ; } catch ( JMSException e ) { throw new JmsException ( "Unable to get JMS session" , e ) ; } } return sessionOption . get ( ) ;


signature:
public class JmsService { /** * Get the current connection or create one using the connectionSupplier .
 * @ return JMS Connection */
private Connection getConnection ( ) { } }

implementation: if ( ! connectionOption . isPresent ( ) ) { final Connection connection = connectionSupplier . get ( ) ; if ( connection instanceof ActiveMQConnection ) { ( ( ActiveMQConnection ) connection ) . addTransportListener ( new TransportListener ( ) { @ Override public void onCommand ( Object command ) { } @ Override public void onException ( IOException error ) { } @ Override public void transportInterupted ( ) { connected . set ( false ) ; } @ Override public void transportResumed ( ) { connected . set ( true ) ; } } ) ; } connected . set ( true ) ; if ( startConnection ) { try { connection . start ( ) ; } catch ( JMSException e ) { throw new JmsException ( "Unable to start JMS connection" , e ) ; } } connectionOption = Optional . of ( connection ) ; } return connectionOption . get ( ) ;


signature:
public class JmsService { /** * Send a text message given a queue or topic name and a text message .
 * @ param destinationName destinationName
 * @ param messageContent messageContent */
public void sendTextMessageWithDestination ( final String destinationName , final String messageContent ) { } }

implementation: if ( ! this . isConnected ( ) ) { throw new JmsNotConnectedException ( "JMS connection is down " + destinationName ) ; } final Session session = getSession ( ) ; final MessageProducer producer = getProducer ( destinationName ) ; try { TextMessage message = session . createTextMessage ( messageContent ) ; producer . send ( message ) ; } catch ( JMSException e ) { throw new JmsException ( "Unable to send message to " + destinationName , e ) ; }


signature:
public class JmsService { /** * Listen to a message from JMS from a given destination by name .
 * @ param destinationName destinationName
 * @ param messageListener messageListener */
public void listenTextMessagesWithDestination ( final String destinationName , final Consumer < String > messageListener ) { } }

implementation: final MessageConsumer consumer = getConsumer ( destinationName ) ; try { consumer . setMessageListener ( message -> { try { messageListener . accept ( ( ( TextMessage ) message ) . getText ( ) ) ; if ( acknowledgeMode == Session . CLIENT_ACKNOWLEDGE ) { message . acknowledge ( ) ; } } catch ( JMSException e ) { throw new JmsException ( "Unable to register get text from message in listener " + destinationName , e ) ; } catch ( Exception ex ) { throw new IllegalStateException ( "Unable handle JMS Consumer  " + destinationName , ex ) ; } } ) ; } catch ( JMSException e ) { throw new JmsException ( "Unable to register message listener " + destinationName , e ) ; }


signature:
public class JmsService { /** * Receive a message from destination with timeout .
 * @ param destinationName destinationName
 * @ param timeout timeout
 * @ return message */
public String receiveTextMessageFromDestinationWithTimeout ( final String destinationName , final int timeout ) { } }

implementation: if ( ! this . isConnected ( ) ) { throw new JmsNotConnectedException ( "Not connected" ) ; } MessageConsumer consumer = getConsumer ( destinationName ) ; TextMessage message ; try { if ( timeout == 0 ) { message = ( TextMessage ) consumer . receiveNoWait ( ) ; } else { message = ( TextMessage ) consumer . receive ( timeout ) ; } if ( message != null ) { if ( acknowledgeMode == Session . CLIENT_ACKNOWLEDGE ) { message . acknowledge ( ) ; } return message . getText ( ) ; } else { return null ; } } catch ( JMSException e ) { throw new JmsException ( "Unable to receive message from " + destinationName , e ) ; }


signature:
public class JmsService { /** * Stop the service */
@ Override public void stop ( ) { } }

implementation: if ( connectionOption . isPresent ( ) ) { try { if ( startConnection ) connectionOption . get ( ) . close ( ) ; } catch ( JMSException e ) { throw new JmsException ( "Unable to stop " , e ) ; } connectionOption = Optional . empty ( ) ; sessionOption = Optional . empty ( ) ; producers . clear ( ) ; consumers . clear ( ) ; destinations . clear ( ) ; }


signature:
public class PMMLProducers { /** * Converts the given { @ link weka . classifiers . Classifier } to PMML and saves it to the given file .
 * @ param classifier The { @ link weka . classifiers . Classifier } to convert to PMML .
 * @ param file The file to save the PMML .
 * @ param compress { @ code true } to save the classifier GZipped , or { @ code false } otherwise .
 * @ throws com . feedzai . fos . impl . weka . exception . PMMLConversionException If if fails to convert to PMML . */
public static void produce ( Classifier classifier , File file , boolean compress ) throws PMMLConversionException { } }

implementation: Algorithm algorithm = Algorithm . fromClassifier ( classifier ) ; PMML pmml = algorithm . getPMMLProducer ( ) . produce ( classifier ) ; addAlgorithm ( pmml , algorithm ) ; try { if ( compress ) { String finalPath = file . getAbsolutePath ( ) ; logger . debug ( "Saving compressed file to '{}'." , finalPath ) ; try ( FileOutputStream fileOutputStream = new FileOutputStream ( finalPath ) ; GZIPOutputStream gzipOutputStream = new GZIPOutputStream ( fileOutputStream ) ; ) { JAXBUtil . marshalPMML ( pmml , new StreamResult ( gzipOutputStream ) ) ; } } else { logger . debug ( "Saving file to '{}'." , file . getAbsolutePath ( ) ) ; try ( FileOutputStream fos = new FileOutputStream ( file ) ) { JAXBUtil . marshalPMML ( pmml , new StreamResult ( file ) ) ; } } logger . debug ( "File successfully saved." ) ; } catch ( Exception e ) { logger . error ( "Failed to marshal the PMML to file." , e ) ; throw new PMMLConversionException ( "Failed to marshal the PMML to file." , e ) ; }


signature:
public class PMMLProducers { /** * Adds a { @ link org . dmg . pmml . Extension } element to the { @ link org . dmg . pmml . PMML } with the
 * algorithm used to build the classifier .
 * The name of the extension is { @ link com . feedzai . fos . impl . weka . utils . pmml . PMMLConversionCommons # ALGORITHM _ EXTENSION _ ELEMENT } .
 * @ param pmml The { @ link PMML } to which add the algorithm .
 * @ param algorithm The algorithm used to build the classifier . */
private static void addAlgorithm ( PMML pmml , Algorithm algorithm ) { } }

implementation: Extension extension = new Extension ( ) ; extension . withName ( ALGORITHM_EXTENSION_ELEMENT ) ; extension . withValue ( algorithm . name ( ) ) ; pmml . withExtensions ( extension ) ;


signature: public class NoCacheService { public static void main ( final String ... args ) { } }

implementation: final ManagedServiceBuilder managedServiceBuilder = managedServiceBuilder ( ) ; managedServiceBuilder . getHttpServerBuilder ( ) . addResponseDecorator ( new HttpResponseDecorator ( ) { @ Override public boolean decorateTextResponse ( HttpTextResponseHolder responseHolder , String requestPath , String method , int code , String contentType , String payload , MultiMap < String , String > responseHeaders , MultiMap < String , String > requestHeaders , MultiMap < String , String > requestParams ) { final HttpResponseBuilder responseBuilder = HttpResponseBuilder . httpResponseBuilder ( ) . setCode ( code ) . setContentType ( contentType ) . setBody ( payload ) ; if ( responseHeaders != null && ! responseHeaders . isEmpty ( ) ) { responseBuilder . setHeaders ( responseHeaders ) ; } responseBuilder . addHeader ( "Cache-Control" , "no-cache, no-store, must-revalidate" ) . addHeader ( "Pragma" , "no-cache" ) . addHeader ( "Expires" , "0" ) . addHeader ( "X-MyHeader-Hostname" , "foo" ) ; responseHolder . setHttpTextResponse ( ( HttpTextResponse ) responseBuilder . build ( ) ) ; return true ; } @ Override public boolean decorateBinaryResponse ( HttpBinaryResponseHolder responseHolder , String requestPath , String method , int code , String contentType , byte [ ] payload , MultiMap < String , String > responseHeaders , MultiMap < String , String > requestHeaders , MultiMap < String , String > requestParams ) { final HttpResponseBuilder responseBuilder = HttpResponseBuilder . httpResponseBuilder ( ) . setCode ( code ) . setContentType ( contentType ) . setBody ( payload ) ; if ( responseHeaders != null && ! responseHeaders . isEmpty ( ) ) { responseBuilder . setHeaders ( responseHeaders ) ; } responseBuilder . addHeader ( "Cache-Control" , "no-cache, no-store, must-revalidate" ) . addHeader ( "Pragma" , "no-cache" ) . addHeader ( "Expires" , "0" ) . addHeader ( "X-Calypso-Hostname" , "foo" ) ; responseHolder . setHttpBinaryResponse ( ( HttpBinaryResponse ) responseBuilder . build ( ) ) ; return true ; } } ) ; managedServiceBuilder . setRootURI ( "/" ) . addEndpointService ( new NoCacheService ( ) ) . startApplication ( ) ;