signature:
public class DatastoreAdapter { /** * Store build result along with error information appended to the build log
 * @ param buildTask task
 * @ param buildResult result of running the task
 * @ param e The error that occurred during the build process
 * @ throws DatastoreException on failure to store data */
public BuildRecord storeResult ( BuildTask buildTask , Optional < BuildResult > buildResult , Throwable e ) throws DatastoreException { } }

implementation: BuildRecord . Builder buildRecordBuilder = initBuildRecordBuilder ( buildTask ) ; buildRecordBuilder . status ( SYSTEM_ERROR ) ; StringBuilder errorLog = new StringBuilder ( ) ; buildResult . ifPresent ( result -> { result . getRepourResult ( ) . ifPresent ( repourResult -> { buildRecordBuilder . executionRootName ( repourResult . getExecutionRootName ( ) ) ; buildRecordBuilder . executionRootVersion ( repourResult . getExecutionRootVersion ( ) ) ; buildRecordBuilder . repourLog ( repourResult . getLog ( ) ) ; } ) ; result . getBuildDriverResult ( ) . ifPresent ( buildDriverResult -> { errorLog . append ( buildDriverResult . getBuildLog ( ) ) ; errorLog . append ( "\n---- End Build Log ----\n" ) ; } ) ; result . getRepositoryManagerResult ( ) . ifPresent ( rmr -> { errorLog . append ( rmr . getLog ( ) ) ; errorLog . append ( "\n---- End Repository Manager Log ----\n" ) ; } ) ; result . getEnvironmentDriverResult ( ) . ifPresent ( r -> { if ( r . getLog ( ) != null && ! r . getLog ( ) . equals ( "" ) ) errorLog . append ( r . getLog ( ) ) ; errorLog . append ( "\n---- End Environment Driver Log ----\n" ) ; } ) ; } ) ; errorLog . append ( "Build status: " ) . append ( getBuildStatus ( buildResult ) ) . append ( "\n" ) ; errorLog . append ( "Caught exception: " ) . append ( e . toString ( ) ) . append ( "\n" ) ; StringWriter stackTraceWriter = new StringWriter ( ) ; e . printStackTrace ( new PrintWriter ( stackTraceWriter ) ) ; errorLog . append ( stackTraceWriter . getBuffer ( ) ) ; buildRecordBuilder . buildLog ( errorLog . toString ( ) ) ; userLog . error ( "Build status: {}." , getBuildStatus ( buildResult ) ) ; log . debug ( "Storing ERROR result of buildTask.getBuildConfigurationAudited().getName() to datastore." , e ) ; return datastore . storeCompletedBuild ( buildRecordBuilder ) ;


signature:
public class DatastoreAdapter { /** * Initialize a new BuildRecord . Builder based on the data contained in the BuildTask .
 * Note , this must be done inside a transaction because it fetches the BuildRecordSet entities from
 * the database .
 * @ return The initialized build record builder */
private BuildRecord . Builder initBuildRecordBuilder ( BuildTask buildTask ) { } }

implementation: BuildOptions buildOptions = buildTask . getBuildOptions ( ) ; BuildRecord . Builder builder = BuildRecord . Builder . newBuilder ( ) . id ( buildTask . getId ( ) ) . buildConfigurationAudited ( buildTask . getBuildConfigurationAudited ( ) ) . user ( buildTask . getUser ( ) ) . submitTime ( buildTask . getSubmitTime ( ) ) . startTime ( buildTask . getStartTime ( ) ) . productMilestone ( buildTask . getProductMilestone ( ) ) . temporaryBuild ( buildOptions . isTemporaryBuild ( ) ) ; if ( buildTask . getEndTime ( ) == null ) { buildTask . setEndTime ( Date . from ( Instant . now ( ) ) ) ; } builder . endTime ( buildTask . getEndTime ( ) ) ; if ( buildTask . getBuildConfigSetRecordId ( ) != null ) { BuildConfigSetRecord buildConfigSetRecord = datastore . getBuildConfigSetRecordById ( buildTask . getBuildConfigSetRecordId ( ) ) ; builder . buildConfigSetRecord ( buildConfigSetRecord ) ; } List < Integer > dependencies = buildTask . getDependencies ( ) . stream ( ) . map ( t -> t . getId ( ) ) . collect ( Collectors . toList ( ) ) ; builder . dependencyBuildRecordIds ( dependencies . toArray ( new Integer [ dependencies . size ( ) ] ) ) ; List < Integer > dependants = buildTask . getDependants ( ) . stream ( ) . map ( t -> t . getId ( ) ) . collect ( Collectors . toList ( ) ) ; builder . dependentBuildRecordIds ( dependants . toArray ( new Integer [ dependants . size ( ) ] ) ) ; return builder ;


signature:
public class RandomUtils { /** * Returns a pseudo - random number between min and max , inclusive .
 * The difference between min and max can be at most
 * < code > Integer . MAX _ VALUE - 1 < / code > .
 * @ param min Minimum value
 * @ param max Maximum value . Must be greater than min .
 * @ return Integer between min and max , inclusive .
 * @ see java . util . Random # nextInt ( int )
 * @ author http : / / stackoverflow . com / questions / 363681 / generating - random - integers - in - a - range - with - java */
public static int randInt ( int min , int max ) { } }

implementation:
// NOTE : Usually this should be a field rather than a method
// variable so that it is not re - seeded every call .
Random rand = new Random ( ) ; // nextInt is normally exclusive of the top value ,
// so add 1 to make it inclusive
int randomNum = rand . nextInt ( ( max - min ) + 1 ) + min ; return randomNum ;


signature:
public class ProductVersionPredicates { /** * This predicate returns all the ProductVersions linked to a specified BuildConfiguration */
public static Predicate < ProductVersion > withBuildConfigurationId ( Integer buildConfigurationId ) { } }

implementation: return ( root , query , cb ) -> { SetJoin < ProductVersion , BuildConfiguration > buildConfigurationJoin = root . join ( ProductVersion_ . buildConfigurations ) ; return cb . equal ( buildConfigurationJoin . get ( BuildConfiguration_ . id ) , buildConfigurationId ) ; } ;


signature:
public class JenkinsServerFactory { /** * This checks if jenkins does not use option Prevent Cross Site Request Forgery exploits
 * mnovotny : TODO : see NCL - 669 this method should be placed in producing JenkinsServer , but as CSRF is not propagated
 * out from JenkinsServer instance , we need to figure out the setting by special API call through JenkinsHttpClient
 * @ param url Jenkins instance URL with port
 * @ return
 * @ throws BuildDriverException */
boolean isJenkinsServerSecuredWithCSRF ( String url ) throws BuildDriverException { } }

implementation: try { JenkinsBuildDriverModuleConfig config = configuration . getModuleConfig ( new PncConfigProvider < JenkinsBuildDriverModuleConfig > ( JenkinsBuildDriverModuleConfig . class ) ) ; String username = config . getUsername ( ) ; String password = config . getPassword ( ) ; if ( url == null || username == null || password == null ) { throw new BuildDriverException ( "Missing config to instantiate " + JenkinsBuildDriver . DRIVER_ID + "." ) ; } try { JenkinsHttpClient jenkinsHttpClient = new JenkinsHttpClient ( new URI ( url ) , username , password ) ; try { jenkinsHttpClient . get ( "/crumbIssuer/api/xml" ) ; return true ; } catch ( IOException e ) { return false ; } } catch ( URISyntaxException e ) { throw new BuildDriverException ( "Cannot instantiate " + JenkinsBuildDriver . DRIVER_ID + ". Make sure you are using valid url: " + url , e ) ; } } catch ( ConfigurationParseException e ) { throw new BuildDriverException ( "Cannot read configuration for " + JenkinsBuildDriver . DRIVER_ID + "." , e ) ; }


signature:
public class DefaultDatastore { /** * Checks the given list against the existing database and creates a new list containing
 * artifacts which have been saved to or loaded from the database .
 * @ param artifacts of in - memory artifacts to either insert to the database or find the matching record in the db
 * @ param artifactCache
 * @ return Set of up to date JPA artifact entities */
private Set < Artifact > saveArtifacts ( Collection < Artifact > artifacts , Map < String , TargetRepository > repositoriesCache , Map < Artifact . IdentifierSha256 , Artifact > artifactCache ) { } }

implementation: logger . debug ( "Saving {} artifacts." , artifacts . size ( ) ) ; Set < Artifact > savedArtifacts = new HashSet < > ( ) ; Set < Artifact . IdentifierSha256 > artifactConstraints = new HashSet < > ( ) ; for ( Artifact artifact : artifacts ) { artifactConstraints . add ( new Artifact . IdentifierSha256 ( artifact . getIdentifier ( ) , artifact . getSha256 ( ) ) ) ; } Set < Artifact > artifactsInDb = null ; if ( artifactConstraints . size ( ) > 0 ) { artifactsInDb = artifactRepository . withIdentifierAndSha256s ( artifactConstraints ) ; } if ( artifactsInDb != null ) { for ( Artifact artifact : artifactsInDb ) { logger . trace ( "Found in DB, adding to cache. Artifact {}" , artifact ) ; artifactCache . put ( artifact . getIdentifierSha256 ( ) , artifact ) ; } } for ( Artifact artifact : artifacts ) { TargetRepository targetRepository = artifact . getTargetRepository ( ) ; linkTargetRepository ( repositoriesCache , artifact , targetRepository ) ; Artifact artifactFromDb ; if ( RepositoryType . GENERIC_PROXY . equals ( targetRepository . getRepositoryType ( ) ) ) { artifactFromDb = saveHttpArtifact ( artifact ) ; } else { artifactFromDb = getOrSaveRepositoryArtifact ( artifact , artifactCache ) ; } savedArtifacts . add ( artifactFromDb ) ; } logger . debug ( "Artifacts saved: {}." , artifacts ) ; return savedArtifacts ;


signature:
public class DefaultDatastore { /** * Save a build config set record to the db . This requires a new transaction to ensure that
 * the record is immediately committed to the database so that it ' s available to use by the
 * foreign keys set in the individual build records . */
@ Override @ TransactionAttribute ( TransactionAttributeType . REQUIRES_NEW ) public BuildConfigSetRecord saveBuildConfigSetRecord ( BuildConfigSetRecord buildConfigSetRecord ) { } }

implementation: return buildConfigSetRecordRepository . save ( buildConfigSetRecord ) ;


signature:
public class DefaultDatastore { /** * Rebuild is required if Build Configuration has been modified or a dependency has been rebuilt since last successful build . */
@ Override public Set < BuildConfiguration > getBuildConfigurations ( BuildConfigurationSet buildConfigurationSet ) { } }

implementation: return new HashSet < > ( buildConfigurationRepository . queryWithPredicates ( withBuildConfigurationSetId ( buildConfigurationSet . getId ( ) ) ) ) ;


signature:
public class DefaultDatastore { /** * Check is some of the dependencies from the previous build were rebuild .
 * Checking is done based on captured dependencies which are stored in the Build Record . */
private boolean hasARebuiltImplicitDependency ( BuildRecord latestSuccessfulBuildRecord , boolean temporaryBuild ) { } }

implementation: Collection < BuildRecord > lastBuiltFrom = getRecordsUsedFor ( latestSuccessfulBuildRecord ) ; return lastBuiltFrom . stream ( ) . anyMatch ( br -> hasNewerVersion ( br , temporaryBuild ) ) ;


signature:
public class DefaultDatastore { /** * Check is some of the dependencies defined on BuildConfiguration has newer version . */
private boolean hasARebuiltExplicitDependency ( BuildRecord latestSuccessfulBuildRecord , Set < BuildConfiguration > dependencies , boolean temporaryBuild ) { } }

implementation: for ( BuildConfiguration dependencyBuildConfiguration : dependencies ) { BuildRecord dependencyLatestSuccessfulBuildRecord = buildRecordRepository . getLatestSuccessfulBuildRecord ( dependencyBuildConfiguration . getId ( ) , temporaryBuild ) ; if ( dependencyLatestSuccessfulBuildRecord == null ) { return true ; } boolean newer = dependencyLatestSuccessfulBuildRecord . getEndTime ( ) . after ( latestSuccessfulBuildRecord . getEndTime ( ) ) ; if ( newer ) { return true ; } } return false ;


signature:
public class BpmTask { /** * Listen to notifications from BPM process for this task .
 * @ param eventType event to follow */
public < T extends BpmNotificationRest > void addListener ( BpmEventType eventType , Consumer < T > listener ) { } }

implementation: List < Consumer < ? > > consumers = listeners . computeIfAbsent ( eventType , ( k ) -> new ArrayList < > ( ) ) ; consumers . add ( listener ) ;


signature:
public class BpmTask { /** * Extend process parameters from the task with additional useful information ,
 * such as pncBaseUrl and taskId , needed for notifications .
 * Before use , taskId MUST be assigned .
 * @ throws CoreException */
Map < String , Object > getExtendedProcessParameters ( ) throws CoreException { } }

implementation:
Serializable processParameters = getProcessParameters ( ) ; requireNonNull ( processParameters ) ; Map < String , Object > actualParameters = new HashMap < > ( ) ; try { actualParameters . put ( "processParameters" , MAPPER . writeValueAsString ( processParameters ) ) ; } catch ( JsonProcessingException e ) { throw new CoreException ( "Could not serialize process processParameters '" + processParameters + "'." , e ) ; } // global not process related parameters
actualParameters . put ( "taskId" , taskId ) ; actualParameters . put ( "usersAuthToken" , accessToken ) ; return actualParameters ;


signature:
public class BuildTasksInitializer { /** * Collects all BuildConfigurationAudited entities , that needs to be built .
 * @ param buildConfiguration Current BuildConfiguration used to resolve dependencies .
 * @ param buildConfigurationAudited Specific revision of a BuildConfiguration ( passed as first parameter ) to be potentially built
 * @ param toBuild Set of BuildConfigurationAudited entities planned to be built
 * @ param visited Set of BuildConfigurations , which were already evaluated , if should be built
 * @ param checkImplicitDependencies
 * @ return Returns true , if the buildConfiguration should be rebuilt , otherwise returns false . */
private boolean collectDependentConfigurations ( BuildConfiguration buildConfiguration , BuildConfigurationAudited buildConfigurationAudited , Set < BuildConfigurationAudited > toBuild , Set < BuildConfiguration > visited , boolean checkImplicitDependencies , boolean forceRebuild , boolean temporaryBuild ) { } }

implementation: if ( visited . contains ( buildConfiguration ) ) { return toBuild . contains ( buildConfigurationAudited ) ; } visited . add ( buildConfiguration ) ; boolean requiresRebuild = forceRebuild || datastoreAdapter . requiresRebuild ( buildConfigurationAudited , checkImplicitDependencies , temporaryBuild ) ; for ( BuildConfiguration dependency : buildConfiguration . getDependencies ( ) ) { boolean dependencyRequiresRebuild = collectDependentConfigurations ( dependency , datastoreAdapter . getLatestBuildConfigurationAuditedInitializeBCDependencies ( dependency . getId ( ) ) , toBuild , visited , checkImplicitDependencies , forceRebuild , temporaryBuild ) ; requiresRebuild = requiresRebuild || dependencyRequiresRebuild ; } log . debug ( "Configuration {} requires rebuild: " , buildConfiguration . getId ( ) , requiresRebuild ) ; if ( requiresRebuild ) { toBuild . add ( buildConfigurationAudited ) ; } return requiresRebuild ;


signature:
public class BuildTasksInitializer { /** * Create a BuildSetTask of latest revisions of BuildConfigurations contained in the BuildConfigurationSet
 * @ param buildConfigurationSet BuildConfigurationSet to be built
 * @ param user A user , who triggered the build
 * @ param buildOptions Build options
 * @ param buildTaskIdProvider Provider to get build task ID
 * @ param submittedBuildTasks Already submitted build tasks
 * @ return Prepared BuildSetTask
 * @ throws CoreException Thrown if the BuildConfigSetRecord cannot be stored */
public BuildSetTask createBuildSetTask ( BuildConfigurationSet buildConfigurationSet , User user , BuildOptions buildOptions , Supplier < Integer > buildTaskIdProvider , Set < BuildTask > submittedBuildTasks ) throws CoreException { } }

implementation: return createBuildSetTask ( buildConfigurationSet , Collections . emptyMap ( ) , user , buildOptions , buildTaskIdProvider , submittedBuildTasks ) ;


signature:
public class BuildTasksInitializer { /** * Create a BuildSetTask of BuildConfigurations contained in the BuildConfigurationSet .
 * A specific revision of the BuildConfigurations contained in the set is used ,
 * if it ' s available in the buildConfigurationAuditedsMap parameter .
 * If it ' s not available , latest revision of the BuildConfiguration is used .
 * @ param buildConfigurationSet BuildConfigurationSet to be built
 * @ param buildConfigurationAuditedsMap A map BuildConfiguration : : id : BuildConfigurationAudited of specific revisions of BuildConfigurations contained in the buildConfigurationSet
 * @ param user A user , who triggered the build
 * @ param buildOptions Build options
 * @ param buildTaskIdProvider Provider to get build task ID
 * @ param submittedBuildTasks Already submitted build tasks
 * @ return Prepared BuildSetTask
 * @ throws CoreException Thrown if the BuildConfigSetRecord cannot be stored */
public BuildSetTask createBuildSetTask ( BuildConfigurationSet buildConfigurationSet , Map < Integer , BuildConfigurationAudited > buildConfigurationAuditedsMap , User user , BuildOptions buildOptions , Supplier < Integer > buildTaskIdProvider , Set < BuildTask > submittedBuildTasks ) throws CoreException { } }

implementation:
BuildSetTask buildSetTask = initBuildSetTask ( buildConfigurationSet , user , buildOptions ) ; Set < BuildConfigurationAudited > buildConfigurationAuditeds = new HashSet < > ( ) ; for ( BuildConfiguration buildConfiguration : datastoreAdapter . getBuildConfigurations ( buildConfigurationSet ) ) { BuildConfigurationAudited buildConfigurationAudited = buildConfigurationAuditedsMap . get ( buildConfiguration . getId ( ) ) ; if ( buildConfigurationAudited == null ) { buildConfigurationAudited = datastoreAdapter . getLatestBuildConfigurationAuditedInitializeBCDependencies ( buildConfiguration . getId ( ) ) ; } buildConfigurationAuditeds . add ( buildConfigurationAudited ) ; } // initializeBuildTasksInSet
log . debug ( "Initializing BuildTasks In Set for BuildConfigurationAuditeds: {}." , buildConfigurationAuditeds . stream ( ) . map ( bc -> bc . toString ( ) ) . collect ( Collectors . joining ( "; " ) ) ) ; fillBuildTaskSet ( buildSetTask , user , buildTaskIdProvider , buildConfigurationSet . getCurrentProductMilestone ( ) , buildConfigurationAuditeds , submittedBuildTasks , buildOptions ) ; return buildSetTask ;


signature:
public class BuildTasksInitializer { /** * Creates build tasks and sets up the appropriate dependency relations
 * @ param buildSetTask The build set task which will contain the build tasks . This must already have
 * initialized the BuildConfigSet , BuildConfigSetRecord , Milestone , etc . */
private void fillBuildTaskSet ( BuildSetTask buildSetTask , User user , Supplier < Integer > buildTaskIdProvider , ProductMilestone productMilestone , Set < BuildConfigurationAudited > toBuild , Set < BuildTask > alreadySubmittedBuildTasks , BuildOptions buildOptions ) { } }

implementation:
for ( BuildConfigurationAudited buildConfigAudited : toBuild ) { Optional < BuildTask > taskOptional = alreadySubmittedBuildTasks . stream ( ) . filter ( bt -> bt . getBuildConfigurationAudited ( ) . equals ( buildConfigAudited ) ) . findAny ( ) ; BuildTask buildTask ; if ( taskOptional . isPresent ( ) ) { buildTask = taskOptional . get ( ) ; log . debug ( "Linking BuildConfigurationAudited {} to existing task {}." , buildConfigAudited , buildTask ) ; } else { int buildId = buildTaskIdProvider . get ( ) ; String buildContentId = ContentIdentityManager . getBuildContentId ( buildId ) ; MDCUtils . addBuildContext ( buildContentId , buildOptions . isTemporaryBuild ( ) , temporaryBuildExpireDate ) ; buildTask = BuildTask . build ( buildConfigAudited , buildSetTask . getBuildOptions ( ) , user , buildId , buildSetTask , buildSetTask . getStartTime ( ) , productMilestone , buildContentId ) ; log . debug ( "Created new buildTask {} for BuildConfigurationAudited {}." , buildTask , buildConfigAudited ) ; } buildSetTask . addBuildTask ( buildTask ) ; } // Loop again to set dependencies
for ( BuildTask buildTask : buildSetTask . getBuildTasks ( ) ) { for ( BuildTask checkDepBuildTask : buildSetTask . getBuildTasks ( ) ) { if ( buildTask . hasDirectConfigDependencyOn ( checkDepBuildTask ) ) { buildTask . addDependency ( checkDepBuildTask ) ; } } }


signature:
public class ArtifactProvider { /** * Lookups built artifacts for the specified BuildRecord
 * @ return Returns requested artifacts or empty collection if BuildRecord with the specified ID doesn ' t exists */
public CollectionInfo < ArtifactRest > getBuiltArtifactsForBuildRecord ( int pageIndex , int pageSize , String sortingRsql , String query , int buildRecordId ) { } }

implementation: return queryForCollection ( pageIndex , pageSize , sortingRsql , query , withBuildRecordId ( buildRecordId ) ) ;


signature:
public class StringUtils { /** * Replace environment variables in string .
 * Environment variables are expected in format $ { env . ENV _ PROPERTY } ,
 * where " env " is static prefix and ENV _ PROPERTY is name of environment property .
 * @ param configString String with environment variables
 * @ return String with replaced environment variables */
public static String replaceEnv ( String configString ) { } }

implementation:
Properties properties = new Properties ( ) ; for ( Map . Entry < String , String > entry : System . getenv ( ) . entrySet ( ) ) { properties . put ( "env." + entry . getKey ( ) , entry . getValue ( ) ) ; } String replaced = StringPropertyReplacer . replaceProperties ( configString , properties ) ; // remove env placeholders that were not replaced with values
return replaced . replaceAll ( "\\$\\{env\\..+\\}" , "" ) ;


signature:
public class StringUtils { /** * Remove ending slash if present and return the string without ending slash
 * @ param string
 * @ return */
public static String stripEndingSlash ( String string ) { } }

implementation: if ( string == null ) { return null ; } if ( string . endsWith ( "/" ) ) { string = string . substring ( 0 , string . length ( ) - 1 ) ; } return string ;


signature:
public class StringUtils { /** * Remove ending slash if present and return the string without ending slash
 * @ param string
 * @ return */
public static String stripTrailingSlash ( String string ) { } }

implementation: if ( string == null ) { return null ; } if ( string . startsWith ( "/" ) ) { string = string . substring ( 1 , string . length ( ) ) ; } return string ;


signature:
public class StringUtils { /** * Adds ending slash if it is not present .
 * @ param string
 * @ return */
public static String addEndingSlash ( String string ) { } }

implementation: if ( string == null ) { return null ; } if ( ! string . endsWith ( "/" ) ) { string += "/" ; } return string ;


signature:
public class StringUtils { /** * Parse comma separated string to Integer array .
 * @ return An empty array when the string parameter is empty or null . */
public static Integer [ ] deserializeInt ( String string ) { } }

implementation: if ( string == null ) { return new Integer [ 0 ] ; } return Arrays . stream ( string . split ( "," ) ) . filter ( s -> ! s . equals ( "" ) ) . map ( Integer :: parseInt ) . toArray ( Integer [ ] :: new ) ;


signature:
public class StringUtils { /** * Serialize Integer array to comma separated string .
 * @ return An empty string when the Integer array parameter is empty or null . */
public static String serializeInt ( Integer [ ] integers ) { } }

implementation: if ( integers == null ) { return "" ; } return Arrays . stream ( integers ) . map ( i -> Integer . toString ( i ) ) . collect ( Collectors . joining ( "," ) ) ;


signature:
public class Gerrit { /** * Generate a download url for a Gerrit snapshot using the gerrit url of the project and the ref
 * @ param gerritUrl URL has to be the ' git clone ' link ( either http or git + ssh )
 * @ param ref The ref to generate a snapshot . It can be a sha , branch , tag . If left empty , master is used
 * @ return Download url
 * @ throws GerritException thrown if the Gerrit Url is not valid */
public String generateDownloadUrlWithGerritGitweb ( @ NotNull String gerritUrl , @ NotNull String ref ) throws GerritException { } }

implementation: return MessageFormat . format ( GERRIT_DOWNLOAD_URL_TEMPLATE , getHost ( gerritUrl ) , getProject ( gerritUrl ) , ref ) ;


signature:
public class Gerrit { /** * Generate an https URL generated from the ' git clone ' Gerrit url . If ref is specified , URL will point to it
 * The url generated points to the git log based on the ref
 * Useful to list the repository ' s Gerrit gitweb if we don ' t know the ref
 * @ param gerritUrl ' git clone ' gerrit url . Can be http or git + ssh
 * @ param ref if not null or empty , this is used to generate a Gerrit gitweb url to the ref
 * @ return Gerrit Gitweb URL */
public String generateGerritGitwebLogUrl ( @ NotNull String gerritUrl , String ref ) throws GerritException { } }

implementation: String host = getHost ( gerritUrl ) ; String project = getProject ( gerritUrl ) ; if ( ref == null || ref . isEmpty ( ) ) { return MessageFormat . format ( GERRIT_GITWEB_URL_TEMPLATE , host , project ) ; } else { return MessageFormat . format ( GERRIT_GITWEB_SHORTLOG_URL_TEMPLATE , host , project , ref ) ; }


signature:
public class Gerrit { /** * Generate an https URL generated from the ' git clone ' Gerrit url .
 * The url generated points to the specific commit based on the ref . If ref is a branch ,
 * it ' ll point to the latest commit
 * @ param gerritUrl ' git clone ' gerrit url . Can be http or git + ssh
 * @ param ref this is used to generate a Gerrit gitweb url to the ref
 * @ return Gerrit Gitweb URL */
public String generateGerritGitwebCommitUrl ( @ NotNull String gerritUrl , @ NotNull String ref ) throws GerritException { } }

implementation: return MessageFormat . format ( GERRIT_GITWEB_COMMIT_URL_TEMPLATE , getHost ( gerritUrl ) , getProject ( gerritUrl ) , ref ) ;


signature:
public class TimeUtils { /** * Generate timestamp in the format tYYYYMMDD - HHMMSS - XXX ( XXX = miliseconds )
 * @ param generationEnabled Flag indicating , if the generation of timestamp is enabled
 * @ param dateInstant Time instant for which the timestamp will be generated
 * @ return Timestamp string or null , if generation is disabled */
public static String generateTimestamp ( boolean generationEnabled , Date dateInstant ) { } }

implementation: if ( ! generationEnabled ) return null ; Calendar instant = new Calendar . Builder ( ) . setInstant ( dateInstant ) . setTimeZone ( TimeZone . getTimeZone ( "UTC" ) ) . build ( ) ; return String . format ( "t%d%02d%02d-%02d%02d%02d-%03d" , instant . get ( Calendar . YEAR ) , instant . get ( Calendar . MONTH ) + 1 , instant . get ( Calendar . DAY_OF_MONTH ) , instant . get ( Calendar . HOUR_OF_DAY ) , instant . get ( Calendar . MINUTE ) , instant . get ( Calendar . SECOND ) , instant . get ( Calendar . MILLISECOND ) ) ;


signature:
public class BuildQueue { /** * Add a new , ready to build task to queue
 * @ param task task to be enqueued */
public synchronized boolean addReadyTask ( BuildTask task ) { } }

implementation: if ( ! task . readyToBuild ( ) ) { throw new IllegalArgumentException ( "a not ready task added to the queue: " + task ) ; } unfinishedTasks . add ( task ) ; log . debug ( "adding task: {}" , task ) ; readyTasks . add ( task ) ; return true ;


signature:
public class BuildQueue { /** * Add a task that is waiting for dependencies
 * @ param task task that is not ready to build
 * @ param taskReadyCallback a callback to be invoked when the task becomes ready */
public synchronized void addWaitingTask ( BuildTask task , Runnable taskReadyCallback ) { } }

implementation: unfinishedTasks . add ( task ) ; log . debug ( "adding waiting task: {}" , task ) ; waitingTasksWithCallbacks . put ( task , taskReadyCallback ) ;


signature:
public class BuildQueue { /** * remove task from the queue .
 * This method should be invoked if the task is completed , either successfully , or with error ( including rejected build )
 * @ param task task to be removed */
public synchronized void removeTask ( BuildTask task ) { } }

implementation: log . debug ( "removing task: {}" , task ) ; if ( tasksInProgress . remove ( task ) ) { availableBuildSlots . release ( ) ; } if ( readyTasks . remove ( task ) ) { log . debug ( "The task {} has been removed from readyTasks." , task ) ; } if ( waitingTasksWithCallbacks . remove ( task ) != null ) { log . debug ( "The task {} has been removed from waitingTasks." , task ) ; } if ( unfinishedTasks . remove ( task ) ) { log . debug ( "The task {} has been removed from unfinishedTasks." , task ) ; }


signature:
public class BuildQueue { /** * Trigger searching for ready tasks in the waiting queue .
 * This method should be invoked if one task has finished and there ' s a possibility that other tasks became ready to be built . */
public synchronized void executeNewReadyTasks ( ) { } }

implementation: List < BuildTask > newReadyTasks = extractReadyTasks ( ) ; log . debug ( "starting new ready tasks. New ready tasks: {}" , newReadyTasks ) ; readyTasks . addAll ( newReadyTasks ) ;


signature:
public class BuildQueue { /** * Get build task for given build configuration from the queue .
 * @ param buildConfigAudited build configuration
 * @ return Optional . of ( build task for the configuration ) if build task is enqueued / in progress , Optional . empty ( ) otherwise */
public synchronized Optional < BuildTask > getTask ( BuildConfigurationAudited buildConfigAudited ) { } }

implementation: Optional < BuildTask > ready = readyTasks . stream ( ) . filter ( bt -> bt . getBuildConfigurationAudited ( ) . equals ( buildConfigAudited ) ) . findAny ( ) ; Optional < BuildTask > waiting = waitingTasksWithCallbacks . keySet ( ) . stream ( ) . filter ( bt -> bt . getBuildConfigurationAudited ( ) . equals ( buildConfigAudited ) ) . findAny ( ) ; Optional < BuildTask > inProgress = tasksInProgress . stream ( ) . filter ( bt -> bt . getBuildConfigurationAudited ( ) . equals ( buildConfigAudited ) ) . findAny ( ) ; return ready . isPresent ( ) ? ready : waiting . isPresent ( ) ? waiting : inProgress ;


signature:
public class TargetRepository { /** * Check if a given artifact originates from a trusted source . Compares the given artifactOriginUrl
 * to the list of trusted repositories .
 * @ param artifactOriginUrl The URL from which the artifact was downloaded
 * @ param targetRepository
 * @ return true if the artifact url came from a trusted repo , false otherwise */
static boolean isTrusted ( String artifactOriginUrl , TargetRepository targetRepository ) { } }

implementation: if ( targetRepository . temporaryRepo ) { return false ; } if ( artifactOriginUrl == null || artifactOriginUrl . isEmpty ( ) ) { return false ; } for ( String trustedRepoUrl : TRUSTED_REPOSITORY_URLS ) { if ( artifactOriginUrl . startsWith ( trustedRepoUrl ) ) { return true ; } } return false ;


signature:
public class PullingMonitor { /** * Periodically checks the condition and calls onMonitorComplete when it returns true .
 * If timeout is reached onMonitorError is called .
 * @ param onMonitorComplete
 * @ param onMonitorError
 * @ param condition
 * @ param checkInterval
 * @ param timeout
 * @ param timeUnit Unit used for checkInterval and timeout */
public RunningTask monitor ( Runnable onMonitorComplete , Consumer < Exception > onMonitorError , Supplier < Boolean > condition , int checkInterval , int timeout , TimeUnit timeUnit ) { } }

implementation:
ObjectWrapper < RunningTask > runningTaskReference = new ObjectWrapper < > ( ) ; Runnable monitor = ( ) -> { RunningTask runningTask = runningTaskReference . get ( ) ; if ( runningTask == null ) { /* There might be a situation where this runnable is called before runningTaskReference is set with the
 * running task since this runnable is scheduled to run before runningTaskReference is set . In that
 * case , we just skip this runnable and re - run on the next scheduled interval with the assumption that
 * runningTaskReference will be set before the next re - run */
log . debug ( "runningTask not set yet inside the 'monitor' runnable! Skipping!" ) ; return ; } try { // Check if given condition is satisfied
if ( condition . get ( ) ) { runningTasks . remove ( runningTask ) ; runningTask . cancel ( ) ; onMonitorComplete . run ( ) ; } } catch ( Exception e ) { log . error ( "Exception in monitor runnable" , e ) ; runningTasks . remove ( runningTask ) ; runningTask . cancel ( ) ; onMonitorError . accept ( e ) ; } } ; ScheduledFuture < ? > future = executorService . scheduleWithFixedDelay ( monitor , 0L , checkInterval , timeUnit ) ; Consumer < RunningTask > onTimeout = ( runningTask ) -> { runningTasks . remove ( runningTask ) ; onMonitorError . accept ( new MonitorException ( "Service was not ready in: " + timeout + " " + timeUnit . toString ( ) ) ) ;


signature:
public class User { /** * Adds the project build record .
 * @ param buildRecord the project build record
 * @ return the project build record */
public BuildRecord addBuildRecord ( BuildRecord buildRecord ) { } }

implementation: getBuildRecords ( ) . add ( buildRecord ) ; buildRecord . setUser ( this ) ; return buildRecord ;


signature:
public class User { /** * Removes the project build record .
 * @ param buildRecord the project build record
 * @ return the project build record */
public BuildRecord removeBuildRecord ( BuildRecord buildRecord ) { } }

implementation: getBuildRecords ( ) . remove ( buildRecord ) ; buildRecord . setUser ( null ) ; return buildRecord ;


signature:
public class TemporaryBuildsCleanerAsyncInvoker { /** * Deletes a single temporary build .
 * @ param buildRecordId ID of the build to be deleted
 * @ param authToken Bearer token
 * @ param onComplete Operation to be executed after deletion operation
 * @ return True if the build exists and deletion started otherwise , false is build doesn ' t exist
 * @ throws ValidationException Thrown when build cannot be deleted */
public boolean deleteTemporaryBuild ( Integer buildRecordId , String authToken , Consumer < Result > onComplete ) throws ValidationException { } }

implementation: BuildRecord buildRecord = buildRecordRepository . findByIdFetchAllProperties ( buildRecordId ) ; if ( buildRecord == null ) { return false ; } if ( ! buildRecord . isTemporaryBuild ( ) ) { throw new ValidationException ( "Only deletion of the temporary builds is allowed" ) ; } executorService . submit ( ( ) -> { try { Result result = temporaryBuildsCleaner . deleteTemporaryBuild ( buildRecordId , authToken ) ; onComplete . accept ( result ) ; } catch ( ValidationException e ) { logger . error ( "Failed to delete temporary buildRecord.id: " + buildRecordId + "." , e ) ; onComplete . accept ( new Result ( buildRecordId . toString ( ) , Result . Status . FAILED , "Failed to delete temporary buildRecord." ) ) ; } } ) ; return true ;


signature:
public class BuildConfiguration { /** * Gets the full set of indirect dependencies ( dependencies of dependencies ) . In cases where a particular dependency is both
 * a direct dependency and is an indirect dependency , it will be included in the set .
 * @ return The set of indirect dependencies */
public Set < BuildConfiguration > getIndirectDependencies ( ) { } }

implementation: Set < BuildConfiguration > indirectDependencies = new HashSet < BuildConfiguration > ( ) ; List < BuildConfiguration > configsToCheck = new ArrayList < BuildConfiguration > ( ) ; configsToCheck . addAll ( getDependencies ( ) ) ; while ( ! configsToCheck . isEmpty ( ) ) { BuildConfiguration nextConfig = configsToCheck . get ( 0 ) ; for ( BuildConfiguration nextDep : nextConfig . getDependencies ( ) ) { if ( ! indirectDependencies . contains ( nextDep ) ) { indirectDependencies . add ( nextDep ) ; configsToCheck . add ( nextDep ) ; } } configsToCheck . remove ( nextConfig ) ; } return indirectDependencies ;


signature:
public class BuildConfiguration { /** * Perform a depth first search of the dependencies to find a match of the given build config . Returns a list with a single
 * build config ( this ) , if no match is found .
 * @ param buildConfig The build config to search for
 * @ return A list of the build configurations in the path between this config and the given config . */
public List < BuildConfiguration > dependencyDepthFirstSearch ( BuildConfiguration buildConfig ) { } }

implementation: List < BuildConfiguration > path = new ArrayList < > ( ) ; path . add ( this ) ; return this . dependencyDepthFirstSearch ( buildConfig , path ) ;


signature:
public class BuildConfiguration { /** * Get the full set of both the direct and indirect dependencies .
 * @ return A set containing both direct and indirect dependencies */
public Set < BuildConfiguration > getAllDependencies ( ) { } }

implementation: Set < BuildConfiguration > allDependencies = new HashSet < BuildConfiguration > ( ) ; allDependencies . addAll ( getDependencies ( ) ) ; allDependencies . addAll ( getIndirectDependencies ( ) ) ; return allDependencies ;


signature:
public class BuildConfiguration { /** * This method is private because a dependant should never be added externally . Instead the dependency relation should be
 * set up using the addDependency method
 * @ param dependant
 * @ return */
private boolean addDependant ( BuildConfiguration dependant ) { } }

implementation: boolean result = dependants . add ( dependant ) ; if ( ! dependant . getDependencies ( ) . contains ( this ) ) { dependant . addDependency ( this ) ; } return result ;


signature:
public class BuildConfiguration { /** * This method is private because a dependant should never be removed externally . Instead the dependency relation should be
 * set up using the removeDependency method
 * @ param dependant
 * @ return */
private boolean removeDependant ( BuildConfiguration dependant ) { } }

implementation: boolean result = dependants . remove ( dependant ) ; if ( dependant . getDependencies ( ) . contains ( this ) ) { dependant . removeDependency ( this ) ; } return result ;


signature:
public class BuildConfiguration { /** * Change the BC clone name into date _ original - BC - name where date will be for every clone updated and for original BC names
 * will be added .
 * Example : clone1 of pslegr - BC on Wednesday October , 21st , 2015 : 20151021095415 _ pslegr - BC
 * clone2 of 20151021095415 _ pslegr - BC on Thursday October , 22nd , 2015 : 20151022nnnnn _ pslegr - BC
 * clone3 of pslegr - BC on Friday October , 23rd , 2015 : 20151023nnnnn _ pslegr - BC
 * @ param bcName
 * @ param now
 * @ return A correct name for the cloned BuildConfiguration */
public static String retrieveCloneName ( String bcName , Date now ) { } }

implementation:
String bcNameToAppend = "" ; int index = bcName . indexOf ( "_" ) ; if ( index == - 1 ) { // No ' _ ' was found , need to append date prefix to whole bcName
bcNameToAppend = bcName ; } else { // A ' _ ' char was found , need to analyze if the prefix is a date ( to
// be replaced with new one )
String prefix = bcName . substring ( 0 , index ) ; if ( prefix . length ( ) == CLONE_PREFIX_DATE_FORMAT . length ( ) ) { try { new SimpleDateFormat ( CLONE_PREFIX_DATE_FORMAT ) . parse ( prefix ) ; // The prefix was a date , need to append new date to a substring
// of original bcName
bcNameToAppend = bcName . substring ( index + 1 ) ; } catch ( ParseException ex ) { // The prefix was not a date , need to append date prefix to
// whole bcName
bcNameToAppend = bcName ; } } else { bcNameToAppend = bcName ; } } StringBuilder sb = new StringBuilder ( ) ; sb . append ( new SimpleDateFormat ( CLONE_PREFIX_DATE_FORMAT ) . format ( now ) ) . append ( "_" ) . append ( bcNameToAppend ) ; return sb . toString ( ) ;


signature: public class BuildExecutorMock { @ Override public BuildExecutionSession startBuilding ( BuildExecutionConfiguration buildExecutionConfiguration , Consumer < BuildExecutionStatusChangedEvent > onBuildExecutionStatusChangedEvent , String accessToken ) throws ExecutorException { } }

implementation: log . info ( "Starting mock build execution for buildExecutionConfiguration.id {}" , buildExecutionConfiguration . getId ( ) ) ; BuildExecutionSession buildExecutionSession = new BuildExecutionSessionMock ( buildExecutionConfiguration , onBuildExecutionStatusChangedEvent ) ; buildExecutionSession . setStatus ( BuildExecutionStatus . NEW ) ; runningExecutions . put ( buildExecutionConfiguration . getId ( ) , buildExecutionSession ) ; Consumer < BuildExecutionStatus > onCompleteInternal = ( buildStatus ) -> { log . debug ( "Removing buildExecutionConfiguration.id [" + buildExecutionConfiguration . getId ( ) + "] form list of running tasks." ) ; runningExecutions . remove ( buildExecutionConfiguration . getId ( ) ) ; buildExecutionSession . setStatus ( buildStatus ) ;


signature:
public class Configuration { /** * Reads configuration for module
 * @ param provider configuration provider of given module config type
 * @ param < T > module config
 * @ return Loaded configuration
 * @ throws ConfigurationParseException Thrown if configuration file couldn ' t be loaded or parsed */
@ SuppressWarnings ( "unchecked" ) public < T extends AbstractModuleConfig > T getModuleConfig ( ConfigProvider < T > provider ) throws ConfigurationParseException { } }

implementation: Class < T > moduleClass = provider . getType ( ) ; if ( configCache . containsKey ( moduleClass ) ) return ( T ) configCache . get ( moduleClass ) ; synchronized ( this ) { if ( configCache . containsKey ( moduleClass ) ) { return ( T ) configCache . get ( moduleClass ) ; } T config = configurationJsonParser . parseJSONPNCConfig ( CONFIG_STRING , provider ) ; configCache . put ( moduleClass , config ) ; return config ; }


signature:
public class TomcatServerJunit4Runner { /** * Instantiate embedded tomcat to be used in tests .
 * @ param klass The tested class .
 * @ return The embedded tomcat . */
private static EmbeddedTomcat instantiate ( Class < ? > klass ) { } }

implementation: EmbeddedTomcatConfiguration configuration = extractConfiguration ( klass ) ; return configuration == null ? new EmbeddedTomcat ( ) : new EmbeddedTomcat ( configuration ) ;


signature:
public class TomcatServerJunit4Runner { /** * Try to extract { @ link EmbeddedTomcat } configuration from the test class : search for a static
 * field / method annotated with { @ link com . github . mjeanroy . junit . servers . annotations . TestServerConfiguration } ) .
 * @ param klass The test class .
 * @ return The { @ link EmbeddedTomcat } configuration .
 * @ throws IllegalTomcatConfigurationException If extracted annotation is not an instance of { @ link EmbeddedTomcatConfiguration } . */
private static EmbeddedTomcatConfiguration extractConfiguration ( Class < ? > klass ) { } }

implementation: AbstractConfiguration configuration = findConfiguration ( klass ) ; if ( configuration == null ) { return null ; } if ( ! ( configuration instanceof EmbeddedTomcatConfiguration ) ) { throw new IllegalTomcatConfigurationException ( ) ; } return ( EmbeddedTomcatConfiguration ) configuration ;


signature:
public class JunitServerExtension { /** * Instantiate server ( implementation to use is automatically detected using the Service Provider
 * API ) .
 * @ param testClass The test class instance .
 * @ param configuration The embedded server configuration to use .
 * @ return The embedded server . */
protected EmbeddedServer < ? > instantiateServer ( Class < ? > testClass , AbstractConfiguration configuration ) { } }

implementation: return configuration == null ? Servers . instantiate ( testClass ) : Servers . instantiate ( configuration ) ;


signature:
public class JunitServerExtension { /** * Start and register the embedded server .
 * The embedded server may be used in two modes :
 * < ul >
 * < li > Started before all tests , and stopped after all tests , this is the static mode ( the extension has been used as a static extension ) . < / li >
 * < li > Started before each tests , and stopped after eacg tests , this is the non static mode ( the extension has not been used as a static extension ) . < / li >
 * < / ul >
 * @ param context The test context .
 * @ param staticMode { @ code true } if the extension has been registered as a static extension , { @ code false } otherwise .
 * @ return The registered adapter . */
private EmbeddedServerRunner registerEmbeddedServer ( ExtensionContext context , boolean staticMode ) { } }

implementation: Class < ? > testClass = context . getRequiredTestClass ( ) ; EmbeddedServer < ? > server = this . server == null ? instantiateServer ( testClass , configuration ) : this . server ; EmbeddedServerRunner serverAdapter = new EmbeddedServerRunner ( server ) ; serverAdapter . beforeAll ( ) ; putEmbeddedServerAdapterInStore ( context , serverAdapter , staticMode ) ; return serverAdapter ;


signature:
public class JunitServerExtension { /** * Stop and remove from the store the started embedded server .
 * @ param context The test context .
 * @ param staticMode { @ code true } if the extension has been registered as a static extension , { @ code false } otherwise .
 * @ see # registerEmbeddedServer ( ExtensionContext , boolean ) */
private void unregisterEmbeddedServer ( ExtensionContext context , boolean staticMode ) { } }

implementation: boolean registeredAsStatic = findInStore ( context , SERVER_RUNNER_STATIC_MODE ) ; if ( registeredAsStatic == staticMode ) { try { EmbeddedServerRunner serverAdapter = findEmbeddedServerAdapterInStore ( context ) ; serverAdapter . afterAll ( ) ; } finally { removeEmbeddedServerAdapterFromStore ( context ) ; } }


signature:
public class JunitServerExtension { /** * Put { @ link EmbeddedServerRunner } instance in the test context store .
 * @ param context The Junit - Jupiter test context .
 * @ param serverAdapter The instance to store . */
private static void putEmbeddedServerAdapterInStore ( ExtensionContext context , EmbeddedServerRunner serverAdapter , boolean staticMode ) { } }

implementation: putInStore ( context , SERVER_RUNNER_KEY , serverAdapter ) ; putInStore ( context , SERVER_RUNNER_STATIC_MODE , staticMode ) ;


signature:
public class JunitServerExtension { /** * Put value in the internal store .
 * @ param context The Junit - Jupiter test context .
 * @ param name The name of the value to look for .
 * @ param value The value to store .
 * @ param < T > The type of the value to look for . */
@ SuppressWarnings ( "unchecked" ) private static < T > void putInStore ( ExtensionContext context , String name , T value ) { } }

implementation: getStore ( context ) . put ( name , value ) ;


signature:
public class JunitServerExtension { /** * Find value in the internal store .
 * @ param context The Junit - Jupiter test context .
 * @ param name The name of the value to look for .
 * @ param < T > The type of the value to look for .
 * @ return The value currently stored . */
@ SuppressWarnings ( "unchecked" ) private static < T > T findInStore ( ExtensionContext context , String name ) { } }

implementation: return ( T ) getStore ( context ) . get ( name ) ;


signature:
public class UrlUtils { /** * Create URI object and wrap { @ link URISyntaxException } to { @ link UrlException } .
 * @ param scheme URL scheme .
 * @ param host URL host .
 * @ param port URL port .
 * @ param path URL path .
 * @ return The final URI .
 * @ throws UrlException If URI cannot be built because of an invalid parameter . */
public static URI createUri ( String scheme , String host , int port , String path ) { } }

implementation: try { return new URI ( scheme , null , host , port , path , null , null ) ; } catch ( URISyntaxException ex ) { throw new UrlException ( scheme , host , port , path , ex ) ; }


signature:
public class UrlUtils { /** * Ensure that given path is an absolute path ( i . e starts with { @ code ' / ' } .
 * @ param path The path .
 * @ return Absolute path . */
public static String ensureAbsolutePath ( String path ) { } }

implementation: if ( path == null || path . isEmpty ( ) ) { return String . valueOf ( PATH_SEPARATOR ) ; } return path . charAt ( 0 ) == PATH_SEPARATOR ? path : PATH_SEPARATOR + path ;


signature:
public class UrlUtils { /** * Concatenate two path value .
 * @ param path Path prefix .
 * @ param endpoint Path suffix .
 * @ return Final path . */
public static String concatenatePath ( String path , String endpoint ) { } }

implementation: String firstSegment = ensureAbsolutePath ( path ) ; if ( endpoint == null || endpoint . isEmpty ( ) ) { return firstSegment ; } StringBuilder sb = new StringBuilder ( firstSegment ) ; if ( path . charAt ( path . length ( ) - 1 ) != PATH_SEPARATOR ) { sb . append ( PATH_SEPARATOR ) ; } if ( endpoint . charAt ( 0 ) == PATH_SEPARATOR ) { sb . append ( endpoint . substring ( 1 ) ) ; } else { sb . append ( endpoint ) ; } return sb . toString ( ) ;


signature:
public class UrlUtils { /** * Check if given { @ code url } starts with HTTP scheme ( i . e { @ code " http " } or { @ code " https " } ) .
 * @ param url The URL to check .
 * @ return { @ code true } if { @ code url } starts with HTTP scheme , { @ code false } otherwise . */
public static boolean startsWithHttpScheme ( String url ) { } }

implementation: if ( url == null || url . isEmpty ( ) ) { return false ; } for ( String scheme : HTTP_SCHEMES ) { int prefixLength = scheme . length ( ) ; if ( url . length ( ) > prefixLength ) { String prefix = url . substring ( 0 , prefixLength ) ; if ( prefix . equalsIgnoreCase ( scheme ) ) { return true ; } } } return false ;


signature:
public class EmbeddedTomcat { /** * Create tomcat context .
 * May be override by subclasses .
 * @ return Tomcat context .
 * @ throws Exception Exception May be thrown by web app context initialization ( will be wrapped later ) .
 * @ deprecated Protected visibility may be removed in a next release , please submit an issue < a href = " https : / / github . com / mjeanroy / junit - servers / issues " > here < / a > to discuss it . */
@ Deprecated protected Context createContext ( ) throws Exception { } }

implementation:
Context context = null ; final String webapp = configuration . getWebapp ( ) ; final String path = configuration . getPath ( ) ; final String classpath = configuration . getClasspath ( ) ; final boolean forceMetaInf = configuration . isForceMetaInf ( ) ; final ClassLoader parentClassLoader = configuration . getParentClasspath ( ) ; final String descriptor = configuration . getOverrideDescriptor ( ) ; File webappDirectory = new File ( webapp ) ; if ( webappDirectory . exists ( ) ) { String webappAbsolutePath = webappDirectory . getAbsolutePath ( ) ; tomcat . getHost ( ) . setAppBase ( webappAbsolutePath ) ; context = tomcat . addWebapp ( path , webappAbsolutePath ) ; // Add additional classpath entry
if ( isNotBlank ( classpath ) ) { File file = new File ( classpath ) ; if ( file . exists ( ) ) { // Check that additional classpath entry contains META - INF directory
File metaInf = new File ( file , "META-INF" ) ; if ( ! metaInf . exists ( ) && forceMetaInf ) { metaInf . mkdir ( ) ; } // = = Tomcat 8
String absolutePath = file . getAbsolutePath ( ) ; StandardRoot root = new StandardRoot ( context ) ; root . createWebResourceSet ( WebResourceRoot . ResourceSetType . PRE , "/WEB-INF/classes" , absolutePath , null , path ) ; context . setResources ( root ) ; // = = Tomcat 8
// = = Tomcat 7
// String s = file . toURI ( ) . toString ( ) ;
// loader . addRepository ( s ) ;
// = = Tomcat 7
// Used to scan additional classpath directory
// https : / / issues . apache . org / bugzilla / show _ bug . cgi ? id = 52853
( ( StandardJarScanner ) context . getJarScanner ( ) ) . setScanAllDirectories ( true ) ; } } // Custom parent classloader .
final ClassLoader threadCl = Thread . currentThread ( ) . getContextClassLoader ( ) ; final ClassLoader tomcatParentClassLoader ; if ( parentClassLoader != null ) { tomcatParentClassLoader = new CompositeClassLoader ( parentClassLoader , threadCl ) ; } else { tomcatParentClassLoader = threadCl ; } // Set the parent class loader that will be given
// to the created loader .
// Setting the parent class loader here is a shortcut for ( code in previous versions ) :
// Loader loader = context . getLoader ( ) ;
// if ( loader = = null ) {
// loader = new WebappLoader ( parentClassLoader ) ;
context . setParentClassLoader ( tomcatParentClassLoader ) ; // Override web . xml path
if ( descriptor != null ) { context . setAltDDName ( descriptor ) ; } } return context ;


signature:
public class Cookies { /** * Create cookie with a name and a value , all other parameters will
 * use the default values :
 * < ul >
 * < li > The webapp path is initialized with { @ code " src / main / webapp " } < / li >
 * < li > The path is initialized with { @ code " / " } < / li >
 * < li > The port is initialized with zero . < / li >
 * < li > The cookie is not secured . < / li >
 * < li > The cookie is not http - only . < / li >
 * < li > The cookie max - age is { @ code null } . < / li >
 * < / ul > .
 * @ param name Cookie name .
 * @ param value Cookie value .
 * @ return Cookie .
 * @ throws NullPointerException if name or value is null .
 * @ throws IllegalArgumentException if name is empty or blank . */
public static Cookie cookie ( String name , String value ) { } }

implementation: return new Cookie . Builder ( name , value ) . build ( ) ;


signature:
public class Cookies { /** * Create cookie .
 * @ param name Cookie name .
 * @ param value Cookie value .
 * @ param domain Cookie domain .
 * @ param path Cookie path .
 * @ param expires Cookie expires value .
 * @ param maxAge Cookie max age value .
 * @ param secure Secure flag .
 * @ param httpOnly Http flag .
 * @ return Cookie .
 * @ throws NullPointerException if name or value is null .
 * @ throws IllegalArgumentException if name is empty or blank . */
public static Cookie cookie ( String name , String value , String domain , String path , Long expires , Long maxAge , boolean secure , boolean httpOnly ) { } }

implementation: Cookie . Builder builder = new Cookie . Builder ( name , value ) . domain ( domain ) . path ( path ) . secure ( secure ) . httpOnly ( httpOnly ) ; if ( expires != null ) { builder . expires ( expires ) ; } if ( maxAge != null ) { builder . maxAge ( maxAge ) ; } return builder . build ( ) ;


signature:
public class Cookies { /** * Create a secured cookie , it means that cookie will have
 * secure flag and http only flag set to true .
 * @ param name Cookie name .
 * @ param value Cookie value .
 * @ param domain Cookie domain .
 * @ param path Cookie path .
 * @ param expires Cookie expires value .
 * @ param maxAge Cookie max age .
 * @ return Cookie .
 * @ throws NullPointerException if name or value is null .
 * @ throws IllegalArgumentException if name is empty or blank . */
public static Cookie secureCookie ( String name , String value , String domain , String path , Long expires , Long maxAge ) { } }

implementation: return Cookies . cookie ( name , value , domain , path , expires , maxAge , true , true ) ;


signature:
public class Cookies { /** * Create a session cookie , it means that cookie will have
 * secure flag and http only flag set to true and expires / max age values
 * are set to zero .
 * @ param name Cookie name .
 * @ param value Cookie value .
 * @ param domain Cookie domain .
 * @ param path Cookie path .
 * @ return Cookie .
 * @ throws NullPointerException if name or value is null .
 * @ throws IllegalArgumentException if name is empty or blank . */
public static Cookie sessionCookie ( String name , String value , String domain , String path ) { } }

implementation: return Cookies . cookie ( name , value , domain , path , - 1L , 0L , true , true ) ;


signature:
public class Cookies { /** * Create a cookie from header value .
 * @ param rawValue Header value .
 * @ return Cookie . */
public static Cookie read ( String rawValue ) { } }

implementation:
notBlank ( rawValue , "Cookie value" ) ; final String [ ] parts = rawValue . split ( FIELD_SEPARATOR ) ; // Extract name and value
final String [ ] nameAndValue = parts [ 0 ] . split ( NAME_VALUE_SEPARATOR ) ; if ( nameAndValue . length != 2 ) { throw new IllegalArgumentException ( "Cookie must have a valid name and a valid value" ) ; } final String name = nameAndValue [ 0 ] . trim ( ) ; final String value = nameAndValue [ 1 ] . trim ( ) ; if ( name . isEmpty ( ) ) { throw new IllegalArgumentException ( "Cookie must have a valid name" ) ; } // Extract other parts
Map < String , String > params = new HashMap < > ( ) ; if ( parts . length > 1 ) { for ( String part : parts ) { String [ ] param = part . split ( NAME_VALUE_SEPARATOR ) ; String paramName = param [ 0 ] . toLowerCase ( ) . trim ( ) ; String paramValue = param . length == 2 ? param [ 1 ] . trim ( ) : "" ; params . put ( paramName , paramValue ) ; } } final String domain = params . get ( "domain" ) ; final String path = params . get ( "path" ) ; final boolean secure = params . containsKey ( "secure" ) ; final boolean httpOnly = params . containsKey ( "httponly" ) ; final String maxAgeTt = params . get ( "max-age" ) ; final String expiresDate = params . get ( "expires" ) ; Long expires ; Long maxAge = maxAgeTt == null ? null : Long . valueOf ( maxAgeTt ) ; if ( expiresDate != null ) { expires = getTime ( expiresDate , "EEE, d MMM yyyy HH:mm:ss Z" , "EEE, d-MMM-yyyy HH:mm:ss Z" , "EEE, d/MMM/yyyy HH:mm:ss Z" ) ; } else { expires = null ; } if ( maxAge == null && expires == null ) { maxAge = 0L ; } else if ( maxAge == null ) { maxAge = expires - System . currentTimeMillis ( ) ; } return Cookies . cookie ( name , value , domain , path , expires , maxAge , secure , httpOnly ) ;


signature:
public class Cookies { /** * Serialize cookies as a string that is ready to be sent to a server over an HTTP
 * request ( a . k . a value of { @ code Cookie } header ) .
 * @ param cookies Cookies to serialize .
 * @ return The final value . */
public static String serialize ( Iterable < Cookie > cookies ) { } }

implementation: StringBuilder result = new StringBuilder ( ) ; boolean first = true ; for ( Cookie cookie : cookies ) { if ( ! first ) { result . append ( SEPARATOR ) ; } String name = cookie . getName ( ) ; String value = cookie . getValue ( ) ; result . append ( name ) . append ( NAME_VALUE_SEPARATOR ) . append ( value ) ; first = false ; } return result . toString ( ) ;


signature:
public class HttpHeader { /** * Create a header with a single value .
 * @ param name Header name , must not be blank .
 * @ param value Header value .
 * @ return Header .
 * @ throws NullPointerException If { @ code name } or { @ code value } are { @ code null } .
 * @ throws IllegalArgumentException If { @ code name } is blank . */
public static HttpHeader header ( String name , String value ) { } }

implementation: return new HttpHeader ( name , singletonList ( value ) ) ;


signature:
public class HttpHeader { /** * Create a header with multiple values .
 * @ param name Header name .
 * @ param values Header values , must not be empty .
 * @ return Header .
 * @ throws NullPointerException If { @ code name } or one of { @ code values } are { @ code null } .
 * @ throws IllegalArgumentException If { @ code name } is blank . */
public static HttpHeader header ( String name , Collection < String > values ) { } }

implementation: return new HttpHeader ( name , values ) ;


signature:
public class EmbeddedJetty { /** * Build web app context used to launch server .
 * May be override by subclasses .
 * @ throws Exception May be thrown by web app context initialization ( will be wrapped later ) . */
private WebAppContext createdWebAppContext ( ) throws Exception { } }

implementation:
final String path = configuration . getPath ( ) ; final String webapp = configuration . getWebapp ( ) ; final String classpath = configuration . getClasspath ( ) ; final ClassLoader parentClassLoader = configuration . getParentClassLoader ( ) ; final String overrideDescriptor = configuration . getOverrideDescriptor ( ) ; final Resource baseResource = configuration . getBaseResource ( ) ; final String containerJarPattern = configuration . getContainerJarPattern ( ) ; final String webInfJarPattern = configuration . getWebInfJarPattern ( ) ; WebAppContext ctx = new WebAppContext ( ) ; if ( containerJarPattern != null ) { ctx . setAttribute ( WebInfConfiguration . CONTAINER_JAR_PATTERN , containerJarPattern ) ; } else if ( JavaUtils . isPostJdk9 ( ) ) { // Fix to make TLD scanning works with Java > = 9
ctx . setAttribute ( WebInfConfiguration . CONTAINER_JAR_PATTERN , ".*\\.jar" ) ; } if ( webInfJarPattern != null ) { ctx . setAttribute ( WebInfConfiguration . WEBINF_JAR_PATTERN , webInfJarPattern ) ; } final ClassLoader systemClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; final ClassLoader classLoader ; if ( parentClassLoader != null ) { classLoader = new CompositeClassLoader ( parentClassLoader , systemClassLoader ) ; } else { classLoader = systemClassLoader ; } ctx . setClassLoader ( classLoader ) ; ctx . setContextPath ( path ) ; if ( baseResource == null ) { // use default base resource
ctx . setBaseResource ( newResource ( webapp ) ) ; } else { ctx . setBaseResource ( baseResource ) ; } if ( overrideDescriptor != null ) { ctx . setOverrideDescriptor ( overrideDescriptor ) ; } ctx . setConfigurations ( new Configuration [ ] { new WebInfConfiguration ( ) , new WebXmlConfiguration ( ) , new AnnotationConfiguration ( ) , new JettyWebXmlConfiguration ( ) , new MetaInfConfiguration ( ) , new FragmentConfiguration ( ) } ) ; if ( isNotBlank ( classpath ) ) { // Fix to scan Spring WebApplicationInitializer
// This will add compiled classes to jetty classpath
// See : http : / / stackoverflow . com / questions / 13222071 / spring - 3-1 - webapplicationinitializer - embedded - jetty - 8 - annotationconfiguration
// And more precisely : http : / / stackoverflow . com / a / 18449506/1215828
File classes = new File ( classpath ) ; PathResource containerResources = new PathResource ( classes . toURI ( ) ) ; ctx . getMetaData ( ) . addContainerResource ( containerResources ) ; } ctx . setParentLoaderPriority ( true ) ; ctx . setWar ( webapp ) ; ctx . setServer ( server ) ; // Add server context
server . setHandler ( ctx ) ; return ctx ;


signature:
public class AbstractEmbeddedServer { /** * Add custom environment properties .
 * Initial property value will be store in { @ link # oldProperties } map
 * and will be restore later . */
private void initEnvironment ( ) { } }

implementation: for ( Map . Entry < String , String > property : configuration . getEnvProperties ( ) . entrySet ( ) ) { String name = property . getKey ( ) ; String newValue = property . getValue ( ) ; String oldValue = getProperty ( property . getKey ( ) ) ; oldProperties . put ( name , oldValue ) ; setProperty ( name , newValue ) ; }


signature:
public class AbstractEmbeddedServer { /** * Reset custom environment properties .
 * Initial values stored in { @ link # oldProperties } will be restored
 * or clear . */
private void destroyEnvironment ( ) { } }

implementation: for ( Map . Entry < String , String > property : configuration . getEnvProperties ( ) . entrySet ( ) ) { String name = property . getKey ( ) ; String oldValue = oldProperties . get ( name ) ; oldProperties . remove ( name ) ; if ( oldValue == null ) { clearProperty ( name ) ; } else { setProperty ( name , oldValue ) ; } }


signature:
public class AbstractEmbeddedServer { /** * Exec hooks phase .
 * @ param pre Phase to execute ( true = > pre ; false = > post ) . */
private void execHooks ( boolean pre ) { } }

implementation: for ( Hook hook : configuration . getHooks ( ) ) { if ( pre ) { hook . pre ( this ) ; } else { hook . post ( this ) ; } }


signature:
public class Servers { /** * Instantiate jetty or tomcat embedded server .
 * Server configuration is automatically read on static field / methods
 * available on given class ( i . e field or method annotated
 * with { @ link com . github . mjeanroy . junit . servers . annotations . TestServerConfiguration } annotation ) .
 * Server implementation is automatically detected ( jetty or
 * tomcat ) with classpath detection .
 * @ param klass Class to inspect .
 * @ return Embedded server . */
public static EmbeddedServer < ? > instantiate ( Class < ? > klass ) { } }

implementation: AbstractConfiguration configuration = findConfiguration ( klass ) ; return instantiate ( configuration ) ;


signature:
public class Servers { /** * Instantiate jetty or tomcat embedded server .
 * Configuration is an optional parameter and can be null .
 * If configuration is null , empty constructor will be used to instantiate
 * embedded server .
 * Otherwise , constructor with one parameter ( configuration ) will
 * be used .
 * Server implementation is automatically detected ( jetty or
 * tomcat ) with classpath detection .
 * @ param configuration Optional configuration .
 * @ return Embedded server . */
@ SuppressWarnings ( "unchecked" ) public static EmbeddedServer < ? > instantiate ( AbstractConfiguration configuration ) { } }

implementation:
ServiceLoader < EmbeddedServerProvider > serviceProviders = ServiceLoader . load ( EmbeddedServerProvider . class ) ; List < EmbeddedServerProvider > coreServerProviders = new ArrayList < > ( ) ; List < EmbeddedServerProvider > customServerProviders = new ArrayList < > ( ) ; for ( EmbeddedServerProvider provider : serviceProviders ) { if ( provider . getClass ( ) . getName ( ) . startsWith ( "com.github.mjeanroy.junit.servers" ) ) { coreServerProviders . add ( provider ) ; } else { customServerProviders . add ( provider ) ; } } // No match , fail fast .
if ( coreServerProviders . isEmpty ( ) && customServerProviders . isEmpty ( ) ) { throw new ServerImplMissingException ( ) ; } // Choose the first one available .
if ( customServerProviders . isEmpty ( ) ) { return instantiate ( coreServerProviders . get ( 0 ) , configuration ) ; } // Try to instantiate the custom available implementation .
if ( customServerProviders . size ( ) > 1 ) { throw new ServerImplMissingException ( ) ; } return instantiate ( coreServerProviders . get ( 0 ) , configuration ) ;


signature:
public class Servers { /** * Find configuration object on static field / method on
 * running class . Configuration is read from static method or static field
 * annotated with { @ link com . github . mjeanroy . junit . servers . annotations . TestServerConfiguration } annotation .
 * @ param klass Class to inspect .
 * @ param < T > Type of configuration .
 * @ return Configuration . */
public static < T extends AbstractConfiguration > T findConfiguration ( Class < ? > klass ) { } }

implementation:
// Look for static methods first
List < Method > methods = findStaticMethodsAnnotatedWith ( klass , TestServerConfiguration . class ) ; List < Field > fields = findStaticFieldsAnnotatedWith ( klass , TestServerConfiguration . class ) ; int nbOfConfigurations = methods . size ( ) + fields . size ( ) ; if ( nbOfConfigurations > 1 ) { failBecauseOfDuplicateConfiguration ( klass , methods , fields ) ; } if ( ! methods . isEmpty ( ) ) { return invoke ( methods . get ( 0 ) ) ; } // Then , look for static field
if ( ! fields . isEmpty ( ) ) { return getter ( fields . get ( 0 ) ) ; } return null ;


signature:
public class Cookie { /** * Create cookie .
 * @ param name Cookie name .
 * @ param value Cookie value .
 * @ return Cookie .
 * @ throws NullPointerException if name or value is null .
 * @ throws IllegalArgumentException if name is empty or blank .
 * @ deprecated Use { @ link Cookies # cookie ( String , String ) } instead . */
@ Deprecated public static Cookie cookie ( String name , String value ) { } }

implementation: return Cookies . cookie ( name , value ) ;


signature:
public class Cookie { /** * Create cookie .
 * @ param name Cookie name .
 * @ param value Cookie value .
 * @ param domain Cookie domain .
 * @ param path Cookie path .
 * @ param expires Cookie expires value .
 * @ param maxAge Cookie max age value .
 * @ param secure Secure flag .
 * @ param httpOnly Http flag .
 * @ return Cookie .
 * @ throws NullPointerException if name or value is null .
 * @ throws IllegalArgumentException if name is empty or blank .
 * @ deprecated Use { @ link Cookies # cookie ( String , String , String , String , Long , Long , boolean , boolean ) } instead . */
@ Deprecated public static Cookie cookie ( String name , String value , String domain , String path , Long expires , Long maxAge , boolean secure , boolean httpOnly ) { } }

implementation: return Cookies . cookie ( name , value , domain , path , expires , maxAge , secure , httpOnly ) ;


signature:
public class Cookie { /** * Create a secured cookie , it means that cookie will have
 * secure flag and http only flag set to true .
 * @ param name Cookie name .
 * @ param value Cookie value .
 * @ param domain Cookie domain .
 * @ param path Cookie path .
 * @ param expires Cookie expires value .
 * @ param maxAge Cookie max age .
 * @ return Cookie .
 * @ throws NullPointerException if name or value is null .
 * @ throws IllegalArgumentException if name is empty or blank .
 * @ deprecated Use { @ link Cookies # secureCookie ( String , String , String , String , Long , Long ) } instead . */
@ Deprecated public static Cookie secureCookie ( String name , String value , String domain , String path , Long expires , Long maxAge ) { } }

implementation: return Cookies . secureCookie ( name , value , domain , path , expires , maxAge ) ;


signature:
public class Cookie { /** * Create a session cookie , it means that cookie will have
 * secure flag and http only flag set to true and expires / max age values
 * are set to zero .
 * @ param name Cookie name .
 * @ param value Cookie value .
 * @ param domain Cookie domain .
 * @ param path Cookie path .
 * @ return Cookie .
 * @ throws NullPointerException if name or value is null .
 * @ throws IllegalArgumentException if name is empty or blank .
 * @ deprecated Use { @ link Cookies # sessionCookie ( String , String , String , String ) } instead . */
@ Deprecated public static Cookie sessionCookie ( String name , String value , String domain , String path ) { } }

implementation: return Cookies . sessionCookie ( name , value , domain , path ) ;


signature:
public class AnnotationsHandlerRunner { /** * Process handlers .
 * @ param target Target class ( i . e tested class ) .
 * @ param before Flag to know if handler has to run " before " phase or " after " phase . */
private void process ( Object target , boolean before ) { } }

implementation: List < Field > fields = findAllFields ( target . getClass ( ) ) ; for ( Field field : fields ) { for ( AnnotationHandler handler : handlers ) { processField ( target , handler , field , before ) ; } }


signature:
public class AnnotationsHandlerRunner { /** * Process field for given handler .
 * @ param target Target class ( i . e tested class ) .
 * @ param handler Handler .
 * @ param field Field .
 * @ param before Flag to know if handler has to run " before " phase or " after " phase . */
private void processField ( Object target , AnnotationHandler handler , Field field , boolean before ) { } }

implementation: for ( Annotation annotation : field . getAnnotations ( ) ) { if ( handler . support ( annotation ) ) { if ( before ) { handler . before ( target , field ) ; } else { handler . after ( target , field ) ; } } }


signature:
public class ApacheHttpClient { /** * Create new http client using internal with custom internal client .
 * @ param server Embedded server .
 * @ param client Internal http client
 * @ return Http client .
 * @ throws NullPointerException If { @ code server } of { @ code client } are { @ code null } .
 * @ deprecated Use { @ link ApacheHttpClient # newApacheHttpClient ( HttpClientConfiguration , EmbeddedServer ) } */
@ Deprecated public static ApacheHttpClient newApacheHttpClient ( EmbeddedServer < ? > server , CloseableHttpClient client ) { } }

implementation: return new ApacheHttpClient ( HttpClientConfiguration . defaultConfiguration ( ) , server , client ) ;


signature:
public class ApacheHttpClient { /** * Create new http client using default internal client .
 * @ param server Embedded server .
 * @ return Http client .
 * @ throws NullPointerException If { @ code server } is { @ code null } . */
public static ApacheHttpClient defaultApacheHttpClient ( EmbeddedServer < ? > server ) { } }

implementation: HttpClientConfiguration configuration = HttpClientConfiguration . defaultConfiguration ( ) ; return newApacheHttpClient ( configuration , server ) ;


signature:
public class ApacheHttpClient { /** * Create new http client using custom configuration .
 * @ param configuration Client configuration .
 * @ param server Embedded server .
 * @ return Http client .
 * @ throws NullPointerException If { @ code server } or { @ code configuration } are { @ code null } . */
public static ApacheHttpClient newApacheHttpClient ( HttpClientConfiguration configuration , EmbeddedServer < ? > server ) { } }

implementation: HttpClientBuilder httpClientBuilder = HttpClientBuilder . create ( ) ; if ( ! configuration . isFollowRedirect ( ) ) { httpClientBuilder . disableRedirectHandling ( ) ; } CloseableHttpClient client = httpClientBuilder . build ( ) ; return new ApacheHttpClient ( configuration , server , client ) ;


signature:
public class ApacheHttpResponseFactory { /** * Create the final { @ link DefaultHttpResponse } instance .
 * @ param response The Apache response .
 * @ param duration The request duration .
 * @ return The HTTP response . */
static com . github . mjeanroy . junit . servers . client . HttpResponse of ( HttpResponse response , long duration ) { } }

implementation: return new ApacheHttpResponse ( response , duration ) ;


signature:
public class ApacheHttpRequest { /** * Add request body .
 * @ param httpRequest The HTTP request . */
private void handleBody ( HttpRequestBase httpRequest ) { } }

implementation: if ( hasBody ( ) ) { HttpEntityEnclosingRequestBase rq = ( HttpEntityEnclosingRequestBase ) httpRequest ; if ( ! formParams . isEmpty ( ) ) { handleFormParameters ( rq ) ; } else if ( body != null ) { handleRequestBody ( rq ) ; } }


signature:
public class ApacheHttpRequest { /** * Create request URI .
 * Each additional query parameters will be appended to final URI .
 * @ return Created URI .
 * @ throws URISyntaxException If an error occurred while building URI .
 * @ see URIBuilder */
private URI createRequestURI ( ) throws URISyntaxException { } }

implementation: URI uri = getEndpoint ( ) . toURI ( ) ; URIBuilder builder = new URIBuilder ( uri ) . setCharset ( StandardCharsets . UTF_8 ) ; for ( HttpParameter parameter : queryParams . values ( ) ) { builder . addParameter ( parameter . getName ( ) , parameter . getValue ( ) ) ; } return builder . build ( ) ;


signature:
public class ApacheHttpRequest { /** * Add headers to http request .
 * @ param httpRequest Http request in creation .
 * @ see org . apache . http . HttpRequest # addHeader ( Header ) */
private void handleHeaders ( HttpRequestBase httpRequest ) { } }

implementation: for ( HttpHeader header : headers . values ( ) ) { httpRequest . addHeader ( header . getName ( ) , header . serializeValues ( ) ) ; }


signature:
public class ApacheHttpRequest { /** * Add parameters as form url encoded content .
 * Each parameter is set as a key value entry to request
 * body .
 * @ param httpRequest Http request in creation . */
private void handleFormParameters ( HttpEntityEnclosingRequestBase httpRequest ) { } }

implementation: List < NameValuePair > pairs = map ( formParams . values ( ) , PARAM_MAPPER ) ; HttpEntity entity = new UrlEncodedFormEntity ( pairs , Charset . defaultCharset ( ) ) ; httpRequest . setEntity ( entity ) ;


signature:
public class ApacheHttpRequest { /** * Set request body value to http request .
 * @ param httpRequest Http request in creation . */
private void handleRequestBody ( HttpEntityEnclosingRequestBase httpRequest ) { } }

implementation: HttpEntity entity = new StringEntity ( body , Charset . defaultCharset ( ) ) ; httpRequest . setEntity ( entity ) ;


signature:
public class ApacheHttpRequest { /** * Add cookies to http request .
 * @ param httpRequest Http request in creation . */
private void handleCookies ( HttpRequestBase httpRequest ) { } }

implementation: if ( ! cookies . isEmpty ( ) ) { httpRequest . addHeader ( COOKIE , Cookies . serialize ( cookies ) ) ; }


signature:
public class AsyncHttpClient { /** * Create new http client using custom internal http client .
 * @ param server Embedded server .
 * @ param client Internal http client
 * @ return Http client .
 * @ throws NullPointerException If { @ code server } or { @ code client } are { @ code null } .
 * @ deprecated Use { @ link AsyncHttpClient # newAsyncHttpClient ( HttpClientConfiguration , EmbeddedServer ) } */
@ Deprecated public static AsyncHttpClient newAsyncHttpClient ( EmbeddedServer < ? > server , org . asynchttpclient . AsyncHttpClient client ) { } }

implementation: return new AsyncHttpClient ( HttpClientConfiguration . defaultConfiguration ( ) , server , client ) ;


signature:
public class AsyncHttpClient { /** * Create new http client using default internal http client .
 * @ param server Embedded server .
 * @ return Http client .
 * @ throws NullPointerException If { @ code server } is { @ code null } . */
public static AsyncHttpClient defaultAsyncHttpClient ( EmbeddedServer < ? > server ) { } }

implementation: HttpClientConfiguration configuration = HttpClientConfiguration . defaultConfiguration ( ) ; return newAsyncHttpClient ( configuration , server ) ;


signature:
public class AsyncHttpClient { /** * Create new http client using custom configuration .
 * @ param configuration Client configuration .
 * @ param server Embedded server .
 * @ return Http client .
 * @ throws NullPointerException If { @ code server } or { @ code configuration } are { @ code null } . */
public static AsyncHttpClient newAsyncHttpClient ( HttpClientConfiguration configuration , EmbeddedServer < ? > server ) { } }

implementation: AsyncHttpClientConfig config = new DefaultAsyncHttpClientConfig . Builder ( ) . setFollowRedirect ( configuration . isFollowRedirect ( ) ) . build ( ) ; DefaultAsyncHttpClient client = new DefaultAsyncHttpClient ( config ) ; return new AsyncHttpClient ( configuration , server , client ) ;


signature:
public class JettyServerExtension { /** * Try to extract { @ link EmbeddedJetty } configuration from :
 * < ul >
 * < li > The given { @ code configuration } if it is not { @ code null } . < / li >
 * < li > A class field / method annotated with { @ link com . github . mjeanroy . junit . servers . annotations . TestServerConfiguration } on given { @ code testClass } otherwise . < / li >
 * < / ul >
 * @ param testClass The test class to analyze .
 * @ param configuration The configuration to use if not { @ code null } .
 * @ return The { @ link EmbeddedJetty } configuration .
 * @ throws IllegalJettyConfigurationException If extracted { @ code configuration } is not an instance of { @ link EmbeddedJettyConfiguration } . */
private static EmbeddedJettyConfiguration extractConfiguration ( Class < ? > testClass , AbstractConfiguration configuration ) { } }

implementation: final AbstractConfiguration configurationToUse = configuration == null ? findConfiguration ( testClass ) : configuration ; if ( configurationToUse == null ) { return null ; } if ( ! ( configurationToUse instanceof EmbeddedJettyConfiguration ) ) { throw new IllegalJettyConfigurationException ( ) ; } return ( EmbeddedJettyConfiguration ) configurationToUse ;


signature:
public class JavaUtils { /** * Parse java version .
 * @ return The JAVA Version . */
private static int parseJavaVersion ( ) { } }

implementation: String [ ] parts = JAVA_SPECIFICATION_VERSION . split ( "\\." ) ; int nbParts = parts . length ; int majorIndex = nbParts > 1 ? 1 : 0 ; return Integer . parseInt ( parts [ majorIndex ] ) ;


signature:
public class CollectionUtils { /** * Join elements of a collection to a final string using a given separator . Note that :
 * < ul >
 * < li > If { @ code values } is { @ code null } , { @ code null } will be returned . < / li >
 * < li > If { @ code separator } is { @ code null } , an empty string is used instead . < / li >
 * < / ul >
 * @ param values The values to join .
 * @ param separator Value separator .
 * @ param < T > Type of elements in the collection .
 * @ return The joined elements . */
public static < T > String join ( Iterable < T > values , String separator ) { } }

implementation: if ( values == null ) { return null ; } String sep = separator == null ? "" : separator ; StringBuilder sb = new StringBuilder ( ) ; boolean first = true ; for ( T value : values ) { if ( ! first ) { sb . append ( sep ) ; } sb . append ( value == null ? null : value . toString ( ) ) ; first = false ; } return sb . toString ( ) ;


signature:
public class CollectionUtils { /** * Map input values to output values .
 * @ param inputs Input values .
 * @ param mapper Mapper function .
 * @ param < T > Type of input values .
 * @ param < U > Type of output values .
 * @ return Output values . */
public static < T , U > List < U > map ( Collection < T > inputs , Mapper < T , U > mapper ) { } }

implementation: if ( inputs == null ) { return null ; } List < U > outputs = new ArrayList < > ( inputs . size ( ) ) ; for ( T input : inputs ) { outputs . add ( mapper . apply ( input ) ) ; } return outputs ;


signature:
public class CollectionUtils { /** * Concat new value to existing inputs and returns new outputs .
 * Note that input is not modified .
 * @ param inputs Input list .
 * @ param newValue The new value to add .
 * @ param < T > The type of object .
 * @ return The outputs . */
public static < T > List < T > concat ( List < T > inputs , T newValue ) { } }

implementation: List < T > outputs = new ArrayList < > ( inputs . size ( ) + 1 ) ; outputs . addAll ( inputs ) ; outputs . add ( newValue ) ; return outputs ;


signature:
public class CollectionUtils { /** * Filter input by using given predicate and return
 * filtered outputs .
 * @ param list List input .
 * @ param predicate Predicate .
 * @ param < T > Type of elements .
 * @ return Filtered outputs . */
static < T > List < T > filter ( List < T > list , Predicate < T > predicate ) { } }

implementation: List < T > results = new ArrayList < > ( ) ; for ( T current : list ) { if ( predicate . apply ( current ) ) { results . add ( current ) ; } } return results ;


signature:
public class TomcatServerExtension { /** * Try to extract { @ link EmbeddedTomcat } configuration from :
 * < ul >
 * < li > The given { @ code configuration } if it is not { @ code null } . < / li >
 * < li > A class field / method annotated with { @ link com . github . mjeanroy . junit . servers . annotations . TestServerConfiguration } on given { @ code testClass } otherwise . < / li >
 * < / ul >
 * @ param testClass The test class to analyze .
 * @ param configuration The configuration to use if not { @ code null } .
 * @ return The { @ link EmbeddedTomcat } configuration .
 * @ throws IllegalTomcatConfigurationException If extracted { @ code configuration } is not an instance of { @ link EmbeddedTomcatConfiguration } . */
private EmbeddedTomcatConfiguration extractConfiguration ( Class < ? > testClass , AbstractConfiguration configuration ) { } }

implementation: final AbstractConfiguration configurationToUse = configuration == null ? findConfiguration ( testClass ) : configuration ; if ( configurationToUse == null ) { return null ; } if ( ! ( configurationToUse instanceof EmbeddedTomcatConfiguration ) ) { throw new IllegalTomcatConfigurationException ( ) ; } return ( EmbeddedTomcatConfiguration ) configurationToUse ;


signature:
public class DefaultHttpResponse { /** * Create a default HTTP Response from given values .
 * @ param duration Request - Response duration .
 * @ param status The response status code .
 * @ param body The response body .
 * @ param headers The response headers .
 * @ return The HTTP response . */
public static DefaultHttpResponse of ( long duration , int status , String body , Collection < HttpHeader > headers ) { } }

implementation: return new DefaultHttpResponse ( duration , status , body , headers ) ;


signature:
public class JettyServerJunit4Runner { /** * Instantiate embedded jetty to be used in tests .
 * @ param klass The tested class .
 * @ return The embedded jetty . */
private static EmbeddedJetty instantiate ( Class < ? > klass ) { } }

implementation: final EmbeddedJettyConfiguration configuration = extractConfiguration ( klass ) ; return configuration == null ? new EmbeddedJetty ( ) : new EmbeddedJetty ( configuration ) ;


signature:
public class JettyServerJunit4Runner { /** * Try to extract { @ link EmbeddedJetty } configuration from the test class : search for a static
 * field / method annotated with { @ link com . github . mjeanroy . junit . servers . annotations . TestServerConfiguration } ) .
 * @ param klass The test class .
 * @ return The { @ link EmbeddedJetty } configuration .
 * @ throws IllegalJettyConfigurationException If extracted annotation is not an instance of { @ link EmbeddedJetty } . */
private static EmbeddedJettyConfiguration extractConfiguration ( Class < ? > klass ) { } }

implementation: final AbstractConfiguration configuration = findConfiguration ( klass ) ; if ( configuration == null ) { return null ; } if ( ! ( configuration instanceof EmbeddedJettyConfiguration ) ) { throw new IllegalJettyConfigurationException ( ) ; } return ( EmbeddedJettyConfiguration ) configuration ;


signature:
public class OkHttpClient { /** * Create new http client using internal
 * http client from ok - http library .
 * @ param server Embedded server .
 * @ return Http client .
 * @ throws NullPointerException If { @ code server } is { @ code null } . */
public static OkHttpClient defaultOkHttpClient ( EmbeddedServer < ? > server ) { } }

implementation: HttpClientConfiguration configuration = HttpClientConfiguration . defaultConfiguration ( ) ; return newOkHttpClient ( configuration , server ) ;


signature:
public class OkHttpClient { /** * Create new http client using custom configuration .
 * @ param configuration Client configuration .
 * @ param server Embedded server .
 * @ return Http client .
 * @ throws NullPointerException If { @ code server } or { @ code configuration } are { @ code null } . */
public static OkHttpClient newOkHttpClient ( HttpClientConfiguration configuration , EmbeddedServer < ? > server ) { } }

implementation: okhttp3 . OkHttpClient client = new okhttp3 . OkHttpClient . Builder ( ) . followRedirects ( configuration . isFollowRedirect ( ) ) . build ( ) ; return new OkHttpClient ( configuration , server , client ) ;


signature:
public class OkHttpClient { /** * Create new http client using custom internal
 * http client from ok - http library .
 * @ param server Embedded server .
 * @ param client The custom client .
 * @ return Http client .
 * @ throws NullPointerException If { @ code server } or { @ code client } are { @ code null } .
 * @ deprecated Use { @ link OkHttpClient # newOkHttpClient ( HttpClientConfiguration , EmbeddedServer ) } */
@ Deprecated public static OkHttpClient newOkHttpClient ( EmbeddedServer < ? > server , okhttp3 . OkHttpClient client ) { } }

implementation: return new OkHttpClient ( HttpClientConfiguration . defaultConfiguration ( ) , server , client ) ;


signature:
public class NingAsyncHttpClient { /** * Create new http client using custom internal http client .
 * @ param server Embedded server .
 * @ param client Internal http client
 * @ return Http client .
 * @ throws NullPointerException If { @ code server } or { @ code client } are { @ code null } .
 * @ deprecated Use { @ link NingAsyncHttpClient # newAsyncHttpClient ( HttpClientConfiguration , EmbeddedServer ) } */
@ Deprecated public static NingAsyncHttpClient newAsyncHttpClient ( EmbeddedServer < ? > server , com . ning . http . client . AsyncHttpClient client ) { } }

implementation: return new NingAsyncHttpClient ( HttpClientConfiguration . defaultConfiguration ( ) , server , client ) ;


signature:
public class NingAsyncHttpClient { /** * Create new http client using internal
 * http client from async - http - client library .
 * An instance of { com . ning . http . client . NingAsyncHttpClient } will be automatically
 * created .
 * @ param server Embedded server .
 * @ return Http client .
 * @ throws NullPointerException If { @ code server } is { @ code null } . */
public static NingAsyncHttpClient defaultAsyncHttpClient ( EmbeddedServer < ? > server ) { } }

implementation: HttpClientConfiguration configuration = HttpClientConfiguration . defaultConfiguration ( ) ; AsyncHttpClientConfig config = new AsyncHttpClientConfig . Builder ( ) . setFollowRedirect ( configuration . isFollowRedirect ( ) ) . build ( ) ; return new NingAsyncHttpClient ( configuration , server , new com . ning . http . client . AsyncHttpClient ( config ) ) ;


signature:
public class ReflectionUtils { /** * Get all fields on given object and look for fields of
 * super classes .
 * @ param type Class to inspect .
 * @ return Fields . */
public static List < Field > findAllFields ( Class < ? > type ) { } }

implementation: List < Field > fields = new LinkedList < > ( ) ; if ( type != null ) { addAll ( fields , type . getDeclaredFields ( ) ) ; if ( type . getSuperclass ( ) != null ) { fields . addAll ( findAllFields ( type . getSuperclass ( ) ) ) ; } } return fields ;


signature:
public class ReflectionUtils { /** * Get all static fields on given class object .
 * @ param type Class to inspect .
 * @ return Fields . */
private static List < Field > findStaticFields ( Class < ? > type ) { } }

implementation: return filter ( asList ( type . getDeclaredFields ( ) ) , STATIC_FIELD_PREDICATE ) ;


signature:
public class ReflectionUtils { /** * Get all static methods on given class object .
 * @ param type Class to inspect .
 * @ return Fields . */
private static List < Method > findStaticMethods ( Class < ? > type ) { } }

implementation: return filter ( asList ( type . getDeclaredMethods ( ) ) , STATIC_METHOD_PREDICATE ) ;


signature:
public class ReflectionUtils { /** * Get all static fields on given class object
 * annotated with given annotation .
 * @ param type Class to inspect .
 * @ param klass Annotation class .
 * @ return Fields . */
public static List < Field > findStaticFieldsAnnotatedWith ( Class < ? > type , Class < ? extends Annotation > klass ) { } }

implementation: List < Field > fields = findStaticFields ( type ) ; return filter ( fields , new FieldAnnotatedWithPredicate ( klass ) ) ;


signature:
public class ReflectionUtils { /** * Get all static methods on given class object
 * annotated with given annotation .
 * @ param type Class to inspect .
 * @ param klass Annotation class .
 * @ return Fields . */
public static List < Method > findStaticMethodsAnnotatedWith ( Class < ? > type , Class < ? extends Annotation > klass ) { } }

implementation: List < Method > methods = findStaticMethods ( type ) ; return filter ( methods , new MethodAnnotatedWithPredicate ( klass ) ) ;


signature:
public class ReflectionUtils { /** * Set value of given field on given instance .
 * @ param instance Instance .
 * @ param field Field .
 * @ param value Field value .
 * @ throws ReflectionException if set operation is not permitted . */
public static void setter ( Object instance , Field field , Object value ) { } }

implementation: boolean forceAccess = false ; try { if ( ! field . isAccessible ( ) ) { forceAccess = true ; field . setAccessible ( true ) ; } field . set ( instance , value ) ; } catch ( IllegalAccessException ex ) { throw new ReflectionException ( ex ) ; } finally { if ( forceAccess ) { field . setAccessible ( false ) ; } }


signature:
public class ReflectionUtils { /** * Get value of field on target object .
 * If target is null , it means that field is static and do not
 * need any target instance .
 * @ param target Target object .
 * @ param field Field .
 * @ param < T > Type of expected value .
 * @ return Field value . */
@ SuppressWarnings ( "unchecked" ) public static < T > T getter ( Object target , Field field ) { } }

implementation: boolean forceAccess = false ; try { if ( ! field . isAccessible ( ) ) { field . setAccessible ( true ) ; forceAccess = true ; } return ( T ) field . get ( target ) ; } catch ( IllegalAccessException ex ) { throw new ReflectionException ( ex ) ; } finally { if ( forceAccess ) { field . setAccessible ( false ) ; } }


signature:
public class ReflectionUtils { /** * Invoke the static method without any arguments .
 * @ param method The method to invoke .
 * @ param < T > Return type .
 * @ return The result of the method invocation . */
@ SuppressWarnings ( "unchecked" ) public static < T > T invoke ( Method method ) { } }

implementation: boolean forceAccess = false ; try { if ( ! method . isAccessible ( ) ) { method . setAccessible ( true ) ; forceAccess = true ; } return ( T ) method . invoke ( null ) ; } catch ( InvocationTargetException | IllegalAccessException ex ) { throw new ReflectionException ( ex ) ; } finally { if ( forceAccess ) { method . setAccessible ( false ) ; } }


signature:
public class AbstractConfigurationBuilder { /** * Change { @ link # webapp } value .
 * @ param webapp New { @ link # webapp } value ( the absolute path will be used ) .
 * @ return this
 * @ throws NullPointerException If { @ code webapp } is null . */
public T withWebapp ( File webapp ) { } }

implementation: notNull ( webapp , "webapp" ) ; this . webapp = webapp . getAbsolutePath ( ) ; return self ( ) ;


signature:
public class AbstractConfigurationBuilder { /** * Add new property entry to the { @ link # envProperties } map .
 * @ param name Property name .
 * @ param value Property value .
 * @ return this
 * @ throws NullPointerException If { @ code name } or { @ code value } are { @ code null } .
 * @ throws IllegalArgumentException if { @ code name } is empty or blank . */
public T withProperty ( String name , String value ) { } }

implementation: this . envProperties . put ( notBlank ( name , "name" ) , notNull ( value , "value" ) ) ; return self ( ) ;


signature:
public class AbstractConfigurationBuilder { /** * Change { @ link # parentClassLoader } value .
 * @ param cls The class that will be used to get classloader .
 * @ return this
 * @ deprecated Use { @ link # withParentClassLoader ( Class ) } instead . */
@ Deprecated public T withParentClasspath ( Class < ? > cls ) { } }

implementation: notNull ( cls , "Base class" ) ; return withParentClassLoader ( cls . getClassLoader ( ) ) ;


signature:
public class AbstractConfigurationBuilder { /** * Change { @ link # parentClassLoader } value .
 * @ param classpath New classpath entry .
 * @ param others Other ( optional ) classpath urls .
 * @ return this */
public T withParentClasspath ( URL classpath , URL ... others ) { } }

implementation: Set < URL > classpathUrls = new HashSet < > ( ) ; classpathUrls . add ( classpath ) ; Collections . addAll ( classpathUrls , others ) ; return withParentClasspath ( classpathUrls ) ;


signature:
public class AbstractConfigurationBuilder { /** * Change { @ link # parentClassLoader } value .
 * @ param classpath New { @ link # parentClassLoader } value .
 * @ return this */
public T withParentClasspath ( Collection < URL > classpath ) { } }

implementation: int nbUrls = classpath . size ( ) ; if ( nbUrls > 0 ) { URL [ ] urls = classpath . toArray ( new URL [ nbUrls ] ) ; URLClassLoader urlClassLoader = new URLClassLoader ( urls ) ; withParentClassLoader ( urlClassLoader ) ; } return self ( ) ;


signature:
public class Dates { /** * Parse date using given pattern .
 * Note that this method will return null if pattern is not
 * valid or throws a { @ link ParseException } .
 * @ param date Date .
 * @ param pattern Pattern .
 * @ param patterns Other pattern to test .
 * @ return Date , null if pattern is not valid . */
static Date parse ( String date , String pattern , String ... patterns ) { } }

implementation:
Set < String > set = new HashSet < > ( ) ; set . add ( pattern ) ; if ( patterns != null ) { addAll ( set , patterns ) ; } for ( String p : set ) { try { return df ( p ) . parse ( date ) ; } catch ( ParseException ex ) { // Skip pattern
} } return null ;


signature:
public class Dates { /** * Parse date using given pattern and return time value .
 * Note that this method will return null if pattern is not
 * valid or throws a { @ link ParseException } .
 * @ param date Date .
 * @ param pattern Pattern .
 * @ param patterns Other pattern to test .
 * @ return Time value , null if pattern is not valid . */
public static Long getTime ( String date , String pattern , String ... patterns ) { } }

implementation: Date d = parse ( date , pattern , patterns ) ; return d == null ? null : d . getTime ( ) ;


signature:
public class Dates { /** * Format date according to given pattern .
 * @ param date Date .
 * @ param pattern Pattern .
 * @ return Formatted date . */
public static String format ( Date date , String pattern ) { } }

implementation: return df ( pattern ) . format ( date ) ;


signature:
public class Dates { /** * Format timestamp according to given pattern .
 * @ param time Timestamp .
 * @ param pattern Pattern .
 * @ return Formatted date . */
static String formatTime ( long time , String pattern ) { } }

implementation: Date date = new Date ( ) ; date . setTime ( time ) ; return format ( date , pattern ) ;


signature:
public class Preconditions { /** * Check that a given value is not null .
 * It throws a { @ link NullPointerException } exception if value is { @ code null } or returned the
 * value .
 * @ param value Value to check .
 * @ param name Name of parameter , it will produce an error message such as " { name } must not be null "
 * @ param < T > Type of value .
 * @ return First parameter if it is not null .
 * @ throws NullPointerException If { @ code value } is { @ code null } . */
public static < T > T notNull ( T value , String name ) { } }

implementation: if ( value == null ) { throw new NullPointerException ( format ( "%s must not be null" , name ) ) ; } return value ;


signature:
public class Preconditions { /** * Check that given collection is not empty ( i . e null or with a size equal to zero ) .
 * It throws a { @ link IllegalArgumentException } exception if collection is empty or
 * returned original collection otherwise .
 * Generated message will be : { name } must not be empty
 * Where name is the value given in parameter .
 * @ param collection Collection .
 * @ param name Name of field to produce exception message .
 * @ param < T > Type of elements .
 * @ return Original collection .
 * @ throws NullPointerException If { @ code collection } is { @ code null } .
 * @ throws IllegalArgumentException If { @ code collection } is empty . */
public static < T > Collection < T > notEmpty ( Collection < T > collection , String name ) { } }

implementation: notNull ( collection , name ) ; if ( collection . isEmpty ( ) ) { throw new IllegalArgumentException ( format ( "%s must not be empty" , name ) ) ; } return collection ;