idx
int64 0
165k
| question
stringlengths 73
4.15k
| target
stringlengths 5
918
| len_question
int64 21
890
| len_target
int64 3
255
|
|---|---|---|---|---|
151,200
|
public void generateReport ( List < XmlSuite > xmlSuites , List < ISuite > suites , String outputDirectoryName ) { removeEmptyDirectories ( new File ( outputDirectoryName ) ) ; boolean useFrames = System . getProperty ( FRAMES_PROPERTY , "true" ) . equals ( "true" ) ; boolean onlyFailures = System . getProperty ( ONLY_FAILURES_PROPERTY , "false" ) . equals ( "true" ) ; File outputDirectory = new File ( outputDirectoryName , REPORT_DIRECTORY ) ; outputDirectory . mkdirs ( ) ; try { if ( useFrames ) { createFrameset ( outputDirectory ) ; } createOverview ( suites , outputDirectory , ! useFrames , onlyFailures ) ; createSuiteList ( suites , outputDirectory , onlyFailures ) ; createGroups ( suites , outputDirectory ) ; createResults ( suites , outputDirectory , onlyFailures ) ; createLog ( outputDirectory , onlyFailures ) ; copyResources ( outputDirectory ) ; } catch ( Exception ex ) { throw new ReportNGException ( "Failed generating HTML report." , ex ) ; } }
|
Generates a set of HTML files that contain data about the outcome of the specified test suites .
| 247
| 19
|
151,201
|
private void createFrameset ( File outputDirectory ) throws Exception { VelocityContext context = createContext ( ) ; generateFile ( new File ( outputDirectory , INDEX_FILE ) , INDEX_FILE + TEMPLATE_EXTENSION , context ) ; }
|
Create the index file that sets up the frameset .
| 55
| 11
|
151,202
|
private void createSuiteList ( List < ISuite > suites , File outputDirectory , boolean onlyFailures ) throws Exception { VelocityContext context = createContext ( ) ; context . put ( SUITES_KEY , suites ) ; context . put ( ONLY_FAILURES_KEY , onlyFailures ) ; generateFile ( new File ( outputDirectory , SUITES_FILE ) , SUITES_FILE + TEMPLATE_EXTENSION , context ) ; }
|
Create the navigation frame .
| 101
| 5
|
151,203
|
private void createResults ( List < ISuite > suites , File outputDirectory , boolean onlyShowFailures ) throws Exception { int index = 1 ; for ( ISuite suite : suites ) { int index2 = 1 ; for ( ISuiteResult result : suite . getResults ( ) . values ( ) ) { boolean failuresExist = result . getTestContext ( ) . getFailedTests ( ) . size ( ) > 0 || result . getTestContext ( ) . getFailedConfigurations ( ) . size ( ) > 0 ; if ( ! onlyShowFailures || failuresExist ) { VelocityContext context = createContext ( ) ; context . put ( RESULT_KEY , result ) ; context . put ( FAILED_CONFIG_KEY , sortByTestClass ( result . getTestContext ( ) . getFailedConfigurations ( ) ) ) ; context . put ( SKIPPED_CONFIG_KEY , sortByTestClass ( result . getTestContext ( ) . getSkippedConfigurations ( ) ) ) ; context . put ( FAILED_TESTS_KEY , sortByTestClass ( result . getTestContext ( ) . getFailedTests ( ) ) ) ; context . put ( SKIPPED_TESTS_KEY , sortByTestClass ( result . getTestContext ( ) . getSkippedTests ( ) ) ) ; context . put ( PASSED_TESTS_KEY , sortByTestClass ( result . getTestContext ( ) . getPassedTests ( ) ) ) ; String fileName = String . format ( "suite%d_test%d_%s" , index , index2 , RESULTS_FILE ) ; generateFile ( new File ( outputDirectory , fileName ) , RESULTS_FILE + TEMPLATE_EXTENSION , context ) ; } ++ index2 ; } ++ index ; } }
|
Generate a results file for each test in each suite .
| 406
| 12
|
151,204
|
private void copyResources ( File outputDirectory ) throws IOException { copyClasspathResource ( outputDirectory , "reportng.css" , "reportng.css" ) ; copyClasspathResource ( outputDirectory , "reportng.js" , "reportng.js" ) ; // If there is a custom stylesheet, copy that. File customStylesheet = META . getStylesheetPath ( ) ; if ( customStylesheet != null ) { if ( customStylesheet . exists ( ) ) { copyFile ( outputDirectory , customStylesheet , CUSTOM_STYLE_FILE ) ; } else { // If not found, try to read the file as a resource on the classpath // useful when reportng is called by a jarred up library InputStream stream = ClassLoader . getSystemClassLoader ( ) . getResourceAsStream ( customStylesheet . getPath ( ) ) ; if ( stream != null ) { copyStream ( outputDirectory , stream , CUSTOM_STYLE_FILE ) ; } } } }
|
Reads the CSS and JavaScript files from the JAR file and writes them to the output directory .
| 225
| 20
|
151,205
|
public List < Throwable > getCauses ( Throwable t ) { List < Throwable > causes = new LinkedList < Throwable > ( ) ; Throwable next = t ; while ( next . getCause ( ) != null ) { next = next . getCause ( ) ; causes . add ( next ) ; } return causes ; }
|
Convert a Throwable into a list containing all of its causes .
| 72
| 14
|
151,206
|
private String commaSeparate ( Collection < String > strings ) { StringBuilder buffer = new StringBuilder ( ) ; Iterator < String > iterator = strings . iterator ( ) ; while ( iterator . hasNext ( ) ) { String string = iterator . next ( ) ; buffer . append ( string ) ; if ( iterator . hasNext ( ) ) { buffer . append ( ", " ) ; } } return buffer . toString ( ) ; }
|
Takes a list of Strings and combines them into a single comma - separated String .
| 91
| 18
|
151,207
|
public String stripThreadName ( String threadId ) { if ( threadId == null ) { return null ; } else { int index = threadId . lastIndexOf ( ' ' ) ; return index >= 0 ? threadId . substring ( 0 , index ) : threadId ; } }
|
TestNG returns a compound thread ID that includes the thread name and its numeric ID separated by an at sign . We only want to use the thread name as the ID is mostly unimportant and it takes up too much space in the generated report .
| 60
| 49
|
151,208
|
public long getStartTime ( List < IInvokedMethod > methods ) { long startTime = System . currentTimeMillis ( ) ; for ( IInvokedMethod method : methods ) { startTime = Math . min ( startTime , method . getDate ( ) ) ; } return startTime ; }
|
Find the earliest start time of the specified methods .
| 64
| 10
|
151,209
|
private long getEndTime ( ISuite suite , IInvokedMethod method ) { // Find the latest end time for all tests in the suite. for ( Map . Entry < String , ISuiteResult > entry : suite . getResults ( ) . entrySet ( ) ) { ITestContext testContext = entry . getValue ( ) . getTestContext ( ) ; for ( ITestNGMethod m : testContext . getAllTestMethods ( ) ) { if ( method == m ) { return testContext . getEndDate ( ) . getTime ( ) ; } } // If we can't find a matching test method it must be a configuration method. for ( ITestNGMethod m : testContext . getPassedConfigurations ( ) . getAllMethods ( ) ) { if ( method == m ) { return testContext . getEndDate ( ) . getTime ( ) ; } } for ( ITestNGMethod m : testContext . getFailedConfigurations ( ) . getAllMethods ( ) ) { if ( method == m ) { return testContext . getEndDate ( ) . getTime ( ) ; } } } throw new IllegalStateException ( "Could not find matching end time." ) ; }
|
Returns the timestamp for the time at which the suite finished executing . This is determined by finding the latest end time for each of the individual tests in the suite .
| 256
| 32
|
151,210
|
public void waitForBuffer ( long timeoutMilli ) { //assert(callerProcessing.booleanValue() == false); synchronized ( buffer ) { if ( dirtyBuffer ) return ; if ( ! foundEOF ( ) ) { logger . trace ( "Waiting for things to come in, or until timeout" ) ; try { if ( timeoutMilli > 0 ) buffer . wait ( timeoutMilli ) ; else buffer . wait ( ) ; } catch ( InterruptedException ie ) { logger . trace ( "Woken up, while waiting for buffer" ) ; } // this might went early, but running the processing again isn't a big deal logger . trace ( "Waited" ) ; } } }
|
What is something came in between when we last checked and when this method is called
| 149
| 16
|
151,211
|
public static void main ( String args [ ] ) throws Exception { final StringBuffer buffer = new StringBuffer ( "The lazy fox" ) ; Thread t1 = new Thread ( ) { public void run ( ) { synchronized ( buffer ) { buffer . delete ( 0 , 4 ) ; buffer . append ( " in the middle" ) ; System . err . println ( "Middle" ) ; try { Thread . sleep ( 4000 ) ; } catch ( Exception e ) { } buffer . append ( " of fall" ) ; System . err . println ( "Fall" ) ; } } } ; Thread t2 = new Thread ( ) { public void run ( ) { try { Thread . sleep ( 1000 ) ; } catch ( Exception e ) { } buffer . append ( " jump over the fence" ) ; System . err . println ( "Fence" ) ; } } ; t1 . start ( ) ; t2 . start ( ) ; t1 . join ( ) ; t2 . join ( ) ; System . err . println ( buffer ) ; }
|
We have more input since wait started
| 219
| 7
|
151,212
|
protected void notifyBufferChange ( char [ ] newData , int numChars ) { synchronized ( bufferChangeLoggers ) { Iterator < BufferChangeLogger > iterator = bufferChangeLoggers . iterator ( ) ; while ( iterator . hasNext ( ) ) { iterator . next ( ) . bufferChanged ( newData , numChars ) ; } } }
|
Notifies all registered BufferChangeLogger instances of a change .
| 75
| 13
|
151,213
|
public int expect ( String pattern ) throws MalformedPatternException , Exception { logger . trace ( "Searching for '" + pattern + "' in the reader stream" ) ; return expect ( pattern , null ) ; }
|
Attempts to detect the provided pattern as an exact match .
| 45
| 11
|
151,214
|
protected ExpectState prepareClosure ( int pairIndex , MatchResult result ) { /* TODO: potentially remove this? { System.out.println( "Begin: " + result.beginOffset(0) ); System.out.println( "Length: " + result.length() ); System.out.println( "Current: " + input.getCurrentOffset() ); System.out.println( "Begin: " + input.getMatchBeginOffset() ); System.out.println( "End: " + input.getMatchEndOffset() ); //System.out.println( "Match: " + input.match() ); //System.out.println( "Pre: >" + input.preMatch() + "<"); //System.out.println( "Post: " + input.postMatch() ); } */ // Prepare Closure environment ExpectState state ; Map < String , Object > prevMap = null ; if ( g_state != null ) { prevMap = g_state . getVars ( ) ; } int matchedWhere = result . beginOffset ( 0 ) ; String matchedText = result . toString ( ) ; // expect_out(0,string) // Unmatched upto end of match // expect_out(buffer) char [ ] chBuffer = input . getBuffer ( ) ; String copyBuffer = new String ( chBuffer , 0 , result . endOffset ( 0 ) ) ; List < String > groups = new ArrayList <> ( ) ; for ( int j = 1 ; j <= result . groups ( ) ; j ++ ) { String group = result . group ( j ) ; groups . add ( group ) ; } state = new ExpectState ( copyBuffer . toString ( ) , matchedWhere , matchedText , pairIndex , groups , prevMap ) ; return state ; }
|
Don t use input it s match values might have been reset in the loop that looks for the first possible match .
| 381
| 23
|
151,215
|
public void cmdProc ( Interp interp , TclObject argv [ ] ) throws TclException { int currentObjIndex , len , i ; int objc = argv . length - 1 ; boolean doBackslashes = true ; boolean doCmds = true ; boolean doVars = true ; StringBuffer result = new StringBuffer ( ) ; String s ; char c ; for ( currentObjIndex = 1 ; currentObjIndex < objc ; currentObjIndex ++ ) { if ( ! argv [ currentObjIndex ] . toString ( ) . startsWith ( "-" ) ) { break ; } int opt = TclIndex . get ( interp , argv [ currentObjIndex ] , validCmds , "switch" , 0 ) ; switch ( opt ) { case OPT_NOBACKSLASHES : doBackslashes = false ; break ; case OPT_NOCOMMANDS : doCmds = false ; break ; case OPT_NOVARS : doVars = false ; break ; default : throw new TclException ( interp , "SubstCrCmd.cmdProc: bad option " + opt + " index to cmds" ) ; } } if ( currentObjIndex != objc ) { throw new TclNumArgsException ( interp , currentObjIndex , argv , "?-nobackslashes? ?-nocommands? ?-novariables? string" ) ; } /* * Scan through the string one character at a time, performing * command, variable, and backslash substitutions. */ s = argv [ currentObjIndex ] . toString ( ) ; len = s . length ( ) ; i = 0 ; while ( i < len ) { c = s . charAt ( i ) ; if ( ( c == ' ' ) && doCmds ) { ParseResult res ; try { interp . evalFlags = Parser . TCL_BRACKET_TERM ; interp . eval ( s . substring ( i + 1 , len ) ) ; TclObject interp_result = interp . getResult ( ) ; interp_result . preserve ( ) ; res = new ParseResult ( interp_result , i + interp . termOffset ) ; } catch ( TclException e ) { i = e . errIndex + 1 ; throw e ; } i = res . nextIndex + 2 ; result . append ( res . value . toString ( ) ) ; res . release ( ) ; /** * Removed (ToDo) may not be portable on Mac } else if (c == '\r') { i++; */ } else if ( ( c == ' ' ) && doVars ) { ParseResult vres = Parser . parseVar ( interp , s . substring ( i , len ) ) ; i += vres . nextIndex ; result . append ( vres . value . toString ( ) ) ; vres . release ( ) ; } else if ( ( c == ' ' ) && doBackslashes ) { BackSlashResult bs = Interp . backslash ( s , i , len ) ; i = bs . nextIndex ; if ( bs . isWordSep ) { break ; } else { result . append ( bs . c ) ; } } else { result . append ( c ) ; i ++ ; } } interp . setResult ( result . toString ( ) ) ; }
|
This procedure is invoked to process the subst Tcl command . See the user documentation for details on what it does .
| 737
| 23
|
151,216
|
public static void mergeReports ( File reportOverall , File ... reports ) { SessionInfoStore infoStore = new SessionInfoStore ( ) ; ExecutionDataStore dataStore = new ExecutionDataStore ( ) ; boolean isCurrentVersionFormat = loadSourceFiles ( infoStore , dataStore , reports ) ; try ( BufferedOutputStream outputStream = new BufferedOutputStream ( new FileOutputStream ( reportOverall ) ) ) { Object visitor ; if ( isCurrentVersionFormat ) { visitor = new ExecutionDataWriter ( outputStream ) ; } else { visitor = new org . jacoco . previous . core . data . ExecutionDataWriter ( outputStream ) ; } infoStore . accept ( ( ISessionInfoVisitor ) visitor ) ; dataStore . accept ( ( IExecutionDataVisitor ) visitor ) ; } catch ( IOException e ) { throw new IllegalStateException ( String . format ( "Unable to write overall coverage report %s" , reportOverall . getAbsolutePath ( ) ) , e ) ; } }
|
Merge all reports in reportOverall .
| 212
| 8
|
151,217
|
public JaCoCoReportReader readJacocoReport ( IExecutionDataVisitor executionDataVisitor , ISessionInfoVisitor sessionInfoStore ) { if ( jacocoExecutionData == null ) { return this ; } JaCoCoExtensions . logger ( ) . info ( "Analysing {}" , jacocoExecutionData ) ; try ( InputStream inputStream = new BufferedInputStream ( new FileInputStream ( jacocoExecutionData ) ) ) { if ( useCurrentBinaryFormat ) { ExecutionDataReader reader = new ExecutionDataReader ( inputStream ) ; reader . setSessionInfoVisitor ( sessionInfoStore ) ; reader . setExecutionDataVisitor ( executionDataVisitor ) ; reader . read ( ) ; } else { org . jacoco . previous . core . data . ExecutionDataReader reader = new org . jacoco . previous . core . data . ExecutionDataReader ( inputStream ) ; reader . setSessionInfoVisitor ( sessionInfoStore ) ; reader . setExecutionDataVisitor ( executionDataVisitor ) ; reader . read ( ) ; } } catch ( IOException e ) { throw new IllegalArgumentException ( String . format ( "Unable to read %s" , jacocoExecutionData . getAbsolutePath ( ) ) , e ) ; } return this ; }
|
Read JaCoCo report determining the format to be used .
| 287
| 12
|
151,218
|
public ArtifactName build ( ) { String groupId = this . groupId ; String artifactId = this . artifactId ; String classifier = this . classifier ; String packaging = this . packaging ; String version = this . version ; if ( artifact != null && ! artifact . isEmpty ( ) ) { final String [ ] artifactSegments = artifact . split ( ":" ) ; // groupId:artifactId:version[:packaging][:classifier]. String value ; switch ( artifactSegments . length ) { case 5 : value = artifactSegments [ 4 ] . trim ( ) ; if ( ! value . isEmpty ( ) ) { classifier = value ; } case 4 : value = artifactSegments [ 3 ] . trim ( ) ; if ( ! value . isEmpty ( ) ) { packaging = value ; } case 3 : value = artifactSegments [ 2 ] . trim ( ) ; if ( ! value . isEmpty ( ) ) { version = value ; } case 2 : value = artifactSegments [ 1 ] . trim ( ) ; if ( ! value . isEmpty ( ) ) { artifactId = value ; } case 1 : value = artifactSegments [ 0 ] . trim ( ) ; if ( ! value . isEmpty ( ) ) { groupId = value ; } } } return new ArtifactNameImpl ( groupId , artifactId , classifier , packaging , version ) ; }
|
Creates the final artifact name .
| 295
| 7
|
151,219
|
public static Deployment of ( final File content ) { final DeploymentContent deploymentContent = DeploymentContent . of ( Assert . checkNotNullParam ( "content" , content ) . toPath ( ) ) ; return new Deployment ( deploymentContent , null ) ; }
|
Creates a new deployment for the file . If the file is a directory the content will be deployed exploded using the file system location .
| 57
| 27
|
151,220
|
public static Deployment of ( final Path content ) { final DeploymentContent deploymentContent = DeploymentContent . of ( Assert . checkNotNullParam ( "content" , content ) ) ; return new Deployment ( deploymentContent , null ) ; }
|
Creates a new deployment for the path . If the path is a directory the content will be deployed exploded using the file system location .
| 52
| 27
|
151,221
|
public static Deployment of ( final URL url ) { final DeploymentContent deploymentContent = DeploymentContent . of ( Assert . checkNotNullParam ( "url" , url ) ) ; return new Deployment ( deploymentContent , null ) ; }
|
Creates a new deployment for the URL . The target server will require access to the URL .
| 52
| 19
|
151,222
|
public Deployment setServerGroups ( final Collection < String > serverGroups ) { this . serverGroups . clear ( ) ; this . serverGroups . addAll ( serverGroups ) ; return this ; }
|
Sets the server groups for the deployment .
| 46
| 9
|
151,223
|
protected void validate ( final boolean isDomain ) throws MojoDeploymentException { final boolean hasServerGroups = hasServerGroups ( ) ; if ( isDomain ) { if ( ! hasServerGroups ) { throw new MojoDeploymentException ( "Server is running in domain mode, but no server groups have been defined." ) ; } } else if ( hasServerGroups ) { throw new MojoDeploymentException ( "Server is running in standalone mode, but server groups have been defined." ) ; } }
|
Validates the deployment .
| 109
| 5
|
151,224
|
private ModelNode buildAddOperation ( final ModelNode address , final Map < String , String > properties ) { final ModelNode op = ServerOperations . createAddOperation ( address ) ; for ( Map . Entry < String , String > prop : properties . entrySet ( ) ) { final String [ ] props = prop . getKey ( ) . split ( "," ) ; if ( props . length == 0 ) { throw new RuntimeException ( "Invalid property " + prop ) ; } ModelNode node = op ; for ( int i = 0 ; i < props . length - 1 ; ++ i ) { node = node . get ( props [ i ] ) ; } final String value = prop . getValue ( ) == null ? "" : prop . getValue ( ) ; if ( value . startsWith ( "!!" ) ) { handleDmrString ( node , props [ props . length - 1 ] , value ) ; } else { node . get ( props [ props . length - 1 ] ) . set ( value ) ; } } return op ; }
|
Creates the operation to add a resource .
| 219
| 9
|
151,225
|
private void handleDmrString ( final ModelNode node , final String name , final String value ) { final String realValue = value . substring ( 2 ) ; node . get ( name ) . set ( ModelNode . fromString ( realValue ) ) ; }
|
Handles DMR strings in the configuration
| 55
| 8
|
151,226
|
private ModelNode parseAddress ( final String profileName , final String inputAddress ) { final ModelNode result = new ModelNode ( ) ; if ( profileName != null ) { result . add ( ServerOperations . PROFILE , profileName ) ; } String [ ] parts = inputAddress . split ( "," ) ; for ( String part : parts ) { String [ ] address = part . split ( "=" ) ; if ( address . length != 2 ) { throw new RuntimeException ( part + " is not a valid address segment" ) ; } result . add ( address [ 0 ] , address [ 1 ] ) ; } return result ; }
|
Parses the comma delimited address into model nodes .
| 134
| 12
|
151,227
|
public static ContainerDescription getContainerDescription ( final ModelControllerClient client ) throws IOException , OperationExecutionException { return DefaultContainerDescription . lookup ( Assert . checkNotNullParam ( "client" , client ) ) ; }
|
Returns the description of the running container .
| 47
| 8
|
151,228
|
public static void waitForDomain ( final ModelControllerClient client , final long startupTimeout ) throws InterruptedException , RuntimeException , TimeoutException { waitForDomain ( null , client , startupTimeout ) ; }
|
Waits the given amount of time in seconds for a managed domain to start . A domain is considered started when each of the servers in the domain are started unless the server is disabled .
| 43
| 37
|
151,229
|
public static void shutdownDomain ( final ModelControllerClient client , final int timeout ) throws IOException , OperationExecutionException { // Note the following two operations used to shutdown a domain don't seem to work well in a composite operation. // The operation occasionally sees a java.util.concurrent.CancellationException because the operation client // is likely closed before the AsyncFuture.get() is complete. Using a non-composite operation doesn't seem to // have this issue. // First shutdown the servers final ModelNode stopServersOp = Operations . createOperation ( "stop-servers" ) ; stopServersOp . get ( "blocking" ) . set ( true ) ; stopServersOp . get ( "timeout" ) . set ( timeout ) ; ModelNode response = client . execute ( stopServersOp ) ; if ( ! Operations . isSuccessfulOutcome ( response ) ) { throw new OperationExecutionException ( "Failed to stop servers." , stopServersOp , response ) ; } // Now shutdown the host final ModelNode address = determineHostAddress ( client ) ; final ModelNode shutdownOp = Operations . createOperation ( "shutdown" , address ) ; response = client . execute ( shutdownOp ) ; if ( Operations . isSuccessfulOutcome ( response ) ) { // Wait until the process has died while ( true ) { if ( isDomainRunning ( client , true ) ) { try { TimeUnit . MILLISECONDS . sleep ( 20L ) ; } catch ( InterruptedException e ) { LOGGER . trace ( "Interrupted during sleep" , e ) ; } } else { break ; } } } else { throw new OperationExecutionException ( "Failed to shutdown host." , shutdownOp , response ) ; } }
|
Shuts down a managed domain container . The servers are first stopped then the host controller is shutdown .
| 373
| 20
|
151,230
|
public static ModelNode determineHostAddress ( final ModelControllerClient client ) throws IOException , OperationExecutionException { final ModelNode op = Operations . createReadAttributeOperation ( EMPTY_ADDRESS , "local-host-name" ) ; ModelNode response = client . execute ( op ) ; if ( Operations . isSuccessfulOutcome ( response ) ) { return DeploymentOperations . createAddress ( "host" , Operations . readResult ( response ) . asString ( ) ) ; } throw new OperationExecutionException ( op , response ) ; }
|
Determines the address for the host being used .
| 117
| 11
|
151,231
|
public static void waitForStandalone ( final ModelControllerClient client , final long startupTimeout ) throws InterruptedException , RuntimeException , TimeoutException { waitForStandalone ( null , client , startupTimeout ) ; }
|
Waits the given amount of time in seconds for a standalone server to start .
| 47
| 16
|
151,232
|
public static boolean isStandaloneRunning ( final ModelControllerClient client ) { try { final ModelNode response = client . execute ( Operations . createReadAttributeOperation ( EMPTY_ADDRESS , "server-state" ) ) ; if ( Operations . isSuccessfulOutcome ( response ) ) { final String state = Operations . readResult ( response ) . asString ( ) ; return ! CONTROLLER_PROCESS_STATE_STARTING . equals ( state ) && ! CONTROLLER_PROCESS_STATE_STOPPING . equals ( state ) ; } } catch ( RuntimeException | IOException e ) { LOGGER . trace ( "Interrupted determining if standalone is running" , e ) ; } return false ; }
|
Checks to see if a standalone server is running .
| 159
| 11
|
151,233
|
public static void shutdownStandalone ( final ModelControllerClient client , final int timeout ) throws IOException { final ModelNode op = Operations . createOperation ( "shutdown" ) ; op . get ( "timeout" ) . set ( timeout ) ; final ModelNode response = client . execute ( op ) ; if ( Operations . isSuccessfulOutcome ( response ) ) { while ( true ) { if ( isStandaloneRunning ( client ) ) { try { TimeUnit . MILLISECONDS . sleep ( 20L ) ; } catch ( InterruptedException e ) { LOGGER . trace ( "Interrupted during sleep" , e ) ; } } else { break ; } } } else { throw new OperationExecutionException ( op , response ) ; } }
|
Shuts down a standalone server .
| 161
| 7
|
151,234
|
public static PackageType resolve ( final MavenProject project ) { final String packaging = project . getPackaging ( ) . toLowerCase ( Locale . ROOT ) ; if ( DEFAULT_TYPES . containsKey ( packaging ) ) { return DEFAULT_TYPES . get ( packaging ) ; } return new PackageType ( packaging ) ; }
|
Resolves the package type from the maven project .
| 75
| 11
|
151,235
|
public static String getJavaCommand ( final Path javaHome ) { final Path resolvedJavaHome = javaHome == null ? findJavaHome ( ) : javaHome ; final String exe ; if ( resolvedJavaHome == null ) { exe = "java" ; } else { exe = resolvedJavaHome . resolve ( "bin" ) . resolve ( "java" ) . toString ( ) ; } if ( exe . contains ( " " ) ) { return "\"" + exe + "\"" ; } if ( WINDOWS ) { return exe + ".exe" ; } return exe ; }
|
Returns the Java command to use .
| 130
| 7
|
151,236
|
public static UndeployDescription of ( final DeploymentDescription deploymentDescription ) { Assert . checkNotNullParam ( "deploymentDescription" , deploymentDescription ) ; return of ( deploymentDescription . getName ( ) ) . addServerGroups ( deploymentDescription . getServerGroups ( ) ) ; }
|
Creates a new undeploy description .
| 64
| 8
|
151,237
|
public static Operation createDeployOperation ( final DeploymentDescription deployment ) { Assert . checkNotNullParam ( "deployment" , deployment ) ; final CompositeOperationBuilder builder = CompositeOperationBuilder . create ( true ) ; addDeployOperationStep ( builder , deployment ) ; return builder . build ( ) ; }
|
Creates an operation to deploy existing deployment content to the runtime .
| 64
| 13
|
151,238
|
public static Operation createDeployOperation ( final Set < DeploymentDescription > deployments ) { Assertions . requiresNotNullOrNotEmptyParameter ( "deployments" , deployments ) ; final CompositeOperationBuilder builder = CompositeOperationBuilder . create ( true ) ; for ( DeploymentDescription deployment : deployments ) { addDeployOperationStep ( builder , deployment ) ; } return builder . build ( ) ; }
|
Creates an option to deploy existing content to the runtime for each deployment
| 82
| 14
|
151,239
|
static void addDeployOperationStep ( final CompositeOperationBuilder builder , final DeploymentDescription deployment ) { final String name = deployment . getName ( ) ; final Set < String > serverGroups = deployment . getServerGroups ( ) ; // If the server groups are empty this is a standalone deployment if ( serverGroups . isEmpty ( ) ) { final ModelNode address = createAddress ( DEPLOYMENT , name ) ; builder . addStep ( createOperation ( DEPLOYMENT_DEPLOY_OPERATION , address ) ) ; } else { for ( String serverGroup : serverGroups ) { final ModelNode address = createAddress ( SERVER_GROUP , serverGroup , DEPLOYMENT , name ) ; builder . addStep ( createOperation ( DEPLOYMENT_DEPLOY_OPERATION , address ) ) ; } } }
|
Adds the deploy operation as a step to the composite operation .
| 178
| 12
|
151,240
|
private static void addRedeployOperationStep ( final CompositeOperationBuilder builder , final DeploymentDescription deployment ) { final String deploymentName = deployment . getName ( ) ; final Set < String > serverGroups = deployment . getServerGroups ( ) ; if ( serverGroups . isEmpty ( ) ) { builder . addStep ( createOperation ( DEPLOYMENT_REDEPLOY_OPERATION , createAddress ( DEPLOYMENT , deploymentName ) ) ) ; } else { for ( String serverGroup : serverGroups ) { builder . addStep ( createOperation ( DEPLOYMENT_REDEPLOY_OPERATION , createAddress ( SERVER_GROUP , serverGroup , DEPLOYMENT , deploymentName ) ) ) ; } } }
|
Adds a redeploy step to the composite operation .
| 160
| 10
|
151,241
|
public static String getFailureDescriptionAsString ( final ModelNode result ) { if ( isSuccessfulOutcome ( result ) ) { return "" ; } final String msg ; if ( result . hasDefined ( ClientConstants . FAILURE_DESCRIPTION ) ) { if ( result . hasDefined ( ClientConstants . OP ) ) { msg = String . format ( "Operation '%s' at address '%s' failed: %s" , result . get ( ClientConstants . OP ) , result . get ( ClientConstants . OP_ADDR ) , result . get ( ClientConstants . FAILURE_DESCRIPTION ) ) ; } else { msg = String . format ( "Operation failed: %s" , result . get ( ClientConstants . FAILURE_DESCRIPTION ) ) ; } } else { msg = String . format ( "An unexpected response was found checking the deployment. Result: %s" , result ) ; } return msg ; }
|
Parses the result and returns the failure description . If the result was successful an empty string is returned .
| 206
| 22
|
151,242
|
public static ModelNode createListDeploymentsOperation ( ) { final ModelNode op = createOperation ( READ_CHILDREN_NAMES ) ; op . get ( CHILD_TYPE ) . set ( DEPLOYMENT ) ; return op ; }
|
Creates an operation to list the deployments .
| 53
| 9
|
151,243
|
public static ModelNode createRemoveOperation ( final ModelNode address , final boolean recursive ) { final ModelNode op = createRemoveOperation ( address ) ; op . get ( RECURSIVE ) . set ( recursive ) ; return op ; }
|
Creates a remove operation .
| 49
| 6
|
151,244
|
public static Property getChildAddress ( final ModelNode address ) { if ( address . getType ( ) != ModelType . LIST ) { throw new IllegalArgumentException ( "The address type must be a list." ) ; } final List < Property > addressParts = address . asPropertyList ( ) ; if ( addressParts . isEmpty ( ) ) { throw new IllegalArgumentException ( "The address is empty." ) ; } return addressParts . get ( addressParts . size ( ) - 1 ) ; }
|
Finds the last entry of the address list and returns it as a property .
| 107
| 16
|
151,245
|
public static ModelNode getParentAddress ( final ModelNode address ) { if ( address . getType ( ) != ModelType . LIST ) { throw new IllegalArgumentException ( "The address type must be a list." ) ; } final ModelNode result = new ModelNode ( ) ; final List < Property > addressParts = address . asPropertyList ( ) ; if ( addressParts . isEmpty ( ) ) { throw new IllegalArgumentException ( "The address is empty." ) ; } for ( int i = 0 ; i < addressParts . size ( ) - 1 ; ++ i ) { final Property property = addressParts . get ( i ) ; result . add ( property . getName ( ) , property . getValue ( ) ) ; } return result ; }
|
Finds the parent address everything before the last address part .
| 160
| 12
|
151,246
|
public String getController ( ) { final StringBuilder controller = new StringBuilder ( ) ; if ( getProtocol ( ) != null ) { controller . append ( getProtocol ( ) ) . append ( "://" ) ; } if ( getHost ( ) != null ) { controller . append ( getHost ( ) ) ; } else { controller . append ( "localhost" ) ; } if ( getPort ( ) > 0 ) { controller . append ( ' ' ) . append ( getPort ( ) ) ; } return controller . toString ( ) ; }
|
Formats a connection string for CLI to use as it s controller connection .
| 117
| 15
|
151,247
|
static DefaultContainerDescription lookup ( final ModelControllerClient client ) throws IOException , OperationExecutionException { final ModelNode op = Operations . createReadResourceOperation ( new ModelNode ( ) . setEmptyList ( ) ) ; op . get ( ClientConstants . INCLUDE_RUNTIME ) . set ( true ) ; final ModelNode result = client . execute ( op ) ; if ( Operations . isSuccessfulOutcome ( result ) ) { final ModelNode model = Operations . readResult ( result ) ; final String productName = getValue ( model , "product-name" , "WildFly" ) ; final String productVersion = getValue ( model , "product-version" ) ; final String releaseVersion = getValue ( model , "release-version" ) ; final String launchType = getValue ( model , "launch-type" ) ; return new DefaultContainerDescription ( productName , productVersion , releaseVersion , launchType , "DOMAIN" . equalsIgnoreCase ( launchType ) ) ; } throw new OperationExecutionException ( op , result ) ; }
|
Queries the running container and attempts to lookup the information from the running container .
| 228
| 16
|
151,248
|
public static SimpleDeploymentDescription of ( final String name , @ SuppressWarnings ( "TypeMayBeWeakened" ) final Set < String > serverGroups ) { final SimpleDeploymentDescription result = of ( name ) ; if ( serverGroups != null ) { result . addServerGroups ( serverGroups ) ; } return result ; }
|
Creates a simple deployment description .
| 76
| 7
|
151,249
|
@ Override protected void addBuildInfoProperties ( BuildInfoBuilder builder ) { if ( envVars != null ) { for ( Map . Entry < String , String > entry : envVars . entrySet ( ) ) { builder . addProperty ( BuildInfoProperties . BUILD_INFO_ENVIRONMENT_PREFIX + entry . getKey ( ) , entry . getValue ( ) ) ; } } if ( sysVars != null ) { for ( Map . Entry < String , String > entry : sysVars . entrySet ( ) ) { builder . addProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } } }
|
Adding environment and system variables to build info .
| 144
| 9
|
151,250
|
@ JavaScriptMethod @ SuppressWarnings ( { "UnusedDeclaration" } ) public LoadBuildsResponse loadBuild ( String buildId ) { LoadBuildsResponse response = new LoadBuildsResponse ( ) ; // When we load a new build we need also to reset the promotion plugin. // The null plugin is related to 'None' plugin. setPromotionPlugin ( null ) ; try { this . currentPromotionCandidate = promotionCandidates . get ( buildId ) ; if ( this . currentPromotionCandidate == null ) { throw new IllegalArgumentException ( "Can't find build by ID: " + buildId ) ; } List < String > repositoryKeys = getRepositoryKeys ( ) ; List < UserPluginInfo > plugins = getPromotionsUserPluginInfo ( ) ; PromotionConfig promotionConfig = getPromotionConfig ( ) ; String defaultTargetRepository = getDefaultPromotionTargetRepository ( ) ; if ( StringUtils . isNotBlank ( defaultTargetRepository ) && repositoryKeys . contains ( defaultTargetRepository ) ) { promotionConfig . setTargetRepo ( defaultTargetRepository ) ; } response . addRepositories ( repositoryKeys ) ; response . setPlugins ( plugins ) ; response . setPromotionConfig ( promotionConfig ) ; response . setSuccess ( true ) ; } catch ( Exception e ) { response . setResponseMessage ( e . getMessage ( ) ) ; } return response ; }
|
Load the related repositories plugins and a promotion config associated to the buildId . Called from the UI .
| 304
| 20
|
151,251
|
@ SuppressWarnings ( { "UnusedDeclaration" } ) public void doIndex ( StaplerRequest req , StaplerResponse resp ) throws IOException , ServletException { req . getView ( this , chooseAction ( ) ) . forward ( req , resp ) ; }
|
Select which view to display based on the state of the promotion . Will return the form if user selects to perform promotion . Progress will be returned if the promotion is currently in progress .
| 60
| 36
|
151,252
|
public static org . jfrog . hudson . ArtifactoryServer prepareArtifactoryServer ( String artifactoryServerID , ArtifactoryServer pipelineServer ) { if ( artifactoryServerID == null && pipelineServer == null ) { return null ; } if ( artifactoryServerID != null && pipelineServer != null ) { return null ; } if ( pipelineServer != null ) { CredentialsConfig credentials = pipelineServer . createCredentialsConfig ( ) ; return new org . jfrog . hudson . ArtifactoryServer ( null , pipelineServer . getUrl ( ) , credentials , credentials , pipelineServer . getConnection ( ) . getTimeout ( ) , pipelineServer . isBypassProxy ( ) , pipelineServer . getConnection ( ) . getRetry ( ) , pipelineServer . getDeploymentThreads ( ) ) ; } org . jfrog . hudson . ArtifactoryServer server = RepositoriesUtils . getArtifactoryServer ( artifactoryServerID , RepositoriesUtils . getArtifactoryServers ( ) ) ; if ( server == null ) { return null ; } return server ; }
|
Prepares Artifactory server either from serverID or from ArtifactoryServer .
| 239
| 17
|
151,253
|
public static BuildInfo appendBuildInfo ( CpsScript cpsScript , Map < String , Object > stepVariables ) { BuildInfo buildInfo = ( BuildInfo ) stepVariables . get ( BUILD_INFO ) ; if ( buildInfo == null ) { buildInfo = ( BuildInfo ) cpsScript . invokeMethod ( "newBuildInfo" , Maps . newLinkedHashMap ( ) ) ; stepVariables . put ( BUILD_INFO , buildInfo ) ; } buildInfo . setCpsScript ( cpsScript ) ; return buildInfo ; }
|
Add the buildInfo to step variables if missing and set its cps script .
| 120
| 16
|
151,254
|
public static boolean promoteAndCheckResponse ( Promotion promotion , ArtifactoryBuildInfoClient client , TaskListener listener , String buildName , String buildNumber ) throws IOException { // If failFast is true, perform dry run first if ( promotion . isFailFast ( ) ) { promotion . setDryRun ( true ) ; listener . getLogger ( ) . println ( "Performing dry run promotion (no changes are made during dry run) ..." ) ; HttpResponse dryResponse = client . stageBuild ( buildName , buildNumber , promotion ) ; try { validatePromotionSuccessful ( dryResponse , true , promotion . isFailFast ( ) , listener ) ; } catch ( IOException e ) { listener . error ( e . getMessage ( ) ) ; return false ; } listener . getLogger ( ) . println ( "Dry run finished successfully.\nPerforming promotion ..." ) ; } // Perform promotion promotion . setDryRun ( false ) ; HttpResponse response = client . stageBuild ( buildName , buildNumber , promotion ) ; try { validatePromotionSuccessful ( response , false , promotion . isFailFast ( ) , listener ) ; } catch ( IOException e ) { listener . error ( e . getMessage ( ) ) ; return false ; } listener . getLogger ( ) . println ( "Promotion completed successfully!" ) ; return true ; }
|
Two stage promotion dry run and actual promotion to verify correctness .
| 290
| 12
|
151,255
|
public static FormValidation validateEmails ( String emails ) { if ( ! Strings . isNullOrEmpty ( emails ) ) { String [ ] recipients = StringUtils . split ( emails , " " ) ; for ( String email : recipients ) { FormValidation validation = validateInternetAddress ( email ) ; if ( validation != FormValidation . ok ( ) ) { return validation ; } } } return FormValidation . ok ( ) ; }
|
Validates a space separated list of emails .
| 94
| 9
|
151,256
|
public static FormValidation validateArtifactoryCombinationFilter ( String value ) throws IOException , InterruptedException { String url = Util . fixEmptyAndTrim ( value ) ; if ( url == null ) return FormValidation . error ( "Mandatory field - You don`t have any deploy matches" ) ; return FormValidation . ok ( ) ; }
|
Validate the Combination filter field in Multi configuration jobs
| 78
| 11
|
151,257
|
public static boolean distributeAndCheckResponse ( DistributionBuilder distributionBuilder , ArtifactoryBuildInfoClient client , TaskListener listener , String buildName , String buildNumber , boolean dryRun ) throws IOException { // do a dry run first listener . getLogger ( ) . println ( "Performing dry run distribution (no changes are made during dry run) ..." ) ; if ( ! distribute ( distributionBuilder , client , listener , buildName , buildNumber , true ) ) { return false ; } listener . getLogger ( ) . println ( "Dry run finished successfully" ) ; if ( ! dryRun ) { listener . getLogger ( ) . println ( "Performing distribution ..." ) ; if ( ! distribute ( distributionBuilder , client , listener , buildName , buildNumber , false ) ) { return false ; } listener . getLogger ( ) . println ( "Distribution completed successfully!" ) ; } return true ; }
|
Two stage distribution dry run and actual promotion to verify correctness .
| 193
| 12
|
151,258
|
private T getWrappedPublisher ( Publisher flexiblePublisher , Class < T > type ) { if ( ! ( flexiblePublisher instanceof FlexiblePublisher ) ) { throw new IllegalArgumentException ( String . format ( "Publisher should be of type: '%s'. Found type: '%s'" , FlexiblePublisher . class , flexiblePublisher . getClass ( ) ) ) ; } List < ConditionalPublisher > conditions = ( ( FlexiblePublisher ) flexiblePublisher ) . getPublishers ( ) ; for ( ConditionalPublisher condition : conditions ) { if ( type . isInstance ( condition . getPublisher ( ) ) ) { return type . cast ( condition . getPublisher ( ) ) ; } } return null ; }
|
Gets the publisher wrapped by the specofoed FlexiblePublisher .
| 148
| 15
|
151,259
|
public T find ( AbstractProject < ? , ? > project , Class < T > type ) { // First check that the Flexible Publish plugin is installed: if ( Jenkins . getInstance ( ) . getPlugin ( FLEXIBLE_PUBLISH_PLUGIN ) != null ) { // Iterate all the project's publishers and find the flexible publisher: for ( Publisher publisher : project . getPublishersList ( ) ) { // Found the flexible publisher: if ( publisher instanceof FlexiblePublisher ) { // See if it wraps a publisher of the specified type and if it does, return it: T pub = getWrappedPublisher ( publisher , type ) ; if ( pub != null ) { return pub ; } } } } return null ; }
|
Gets the publisher of the specified type if it is wrapped by the Flexible Publish publisher in a project . Null is returned if no such publisher is found .
| 157
| 33
|
151,260
|
public boolean isPublisherWrapped ( AbstractProject < ? , ? > project , Class < T > type ) { return find ( project , type ) != null ; }
|
Determines whether a project has the specified publisher type wrapped by the Flexible Publish publisher .
| 34
| 20
|
151,261
|
public void commitWorkingCopy ( final String commitMessage ) throws IOException , InterruptedException { build . getWorkspace ( ) . act ( new SVNCommitWorkingCopyCallable ( commitMessage , getLocation ( ) , getSvnAuthenticationProvider ( build ) , buildListener ) ) ; }
|
Commits the working copy .
| 64
| 6
|
151,262
|
public void createTag ( final String tagUrl , final String commitMessage ) throws IOException , InterruptedException { build . getWorkspace ( ) . act ( new SVNCreateTagCallable ( tagUrl , commitMessage , getLocation ( ) , getSvnAuthenticationProvider ( build ) , buildListener ) ) ; }
|
Creates a tag directly from the working copy .
| 70
| 10
|
151,263
|
public void revertWorkingCopy ( ) throws IOException , InterruptedException { build . getWorkspace ( ) . act ( new RevertWorkingCopyCallable ( getLocation ( ) , getSvnAuthenticationProvider ( build ) , buildListener ) ) ; }
|
Revert all the working copy changes .
| 55
| 9
|
151,264
|
public void safeRevertWorkingCopy ( ) { try { revertWorkingCopy ( ) ; } catch ( Exception e ) { debuggingLogger . log ( Level . FINE , "Failed to revert working copy" , e ) ; log ( "Failed to revert working copy: " + e . getLocalizedMessage ( ) ) ; Throwable cause = e . getCause ( ) ; if ( ! ( cause instanceof SVNException ) ) { return ; } SVNException svnException = ( SVNException ) cause ; if ( svnException . getErrorMessage ( ) . getErrorCode ( ) == SVNErrorCode . WC_LOCKED ) { // work space locked attempt cleanup and try to revert again try { cleanupWorkingCopy ( ) ; } catch ( Exception unlockException ) { debuggingLogger . log ( Level . FINE , "Failed to cleanup working copy" , e ) ; log ( "Failed to cleanup working copy: " + e . getLocalizedMessage ( ) ) ; return ; } try { revertWorkingCopy ( ) ; } catch ( Exception revertException ) { log ( "Failed to revert working copy on the 2nd attempt: " + e . getLocalizedMessage ( ) ) ; } } } }
|
Attempts to revert the working copy . In case of failure it just logs the error .
| 263
| 17
|
151,265
|
public void setIssueTrackerInfo ( BuildInfoBuilder builder ) { Issues issues = new Issues ( ) ; issues . setAggregateBuildIssues ( aggregateBuildIssues ) ; issues . setAggregationBuildStatus ( aggregationBuildStatus ) ; issues . setTracker ( new IssueTracker ( "JIRA" , issueTrackerVersion ) ) ; Set < Issue > affectedIssuesSet = IssuesTrackerUtils . getAffectedIssuesSet ( affectedIssues ) ; if ( ! affectedIssuesSet . isEmpty ( ) ) { issues . setAffectedIssues ( affectedIssuesSet ) ; } builder . issues ( issues ) ; }
|
Apply issues tracker info to a build info builder ( used by generic tasks and maven2 which doesn t use the extractor
| 135
| 25
|
151,266
|
public static BuildRetention createBuildRetention ( Run build , boolean discardOldArtifacts ) { BuildRetention buildRetention = new BuildRetention ( discardOldArtifacts ) ; LogRotator rotator = null ; BuildDiscarder buildDiscarder = build . getParent ( ) . getBuildDiscarder ( ) ; if ( buildDiscarder != null && buildDiscarder instanceof LogRotator ) { rotator = ( LogRotator ) buildDiscarder ; } if ( rotator == null ) { return buildRetention ; } if ( rotator . getNumToKeep ( ) > - 1 ) { buildRetention . setCount ( rotator . getNumToKeep ( ) ) ; } if ( rotator . getDaysToKeep ( ) > - 1 ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . add ( Calendar . DAY_OF_YEAR , - rotator . getDaysToKeep ( ) ) ; buildRetention . setMinimumBuildDate ( new Date ( calendar . getTimeInMillis ( ) ) ) ; } List < String > notToBeDeleted = ExtractorUtils . getBuildNumbersNotToBeDeleted ( build ) ; buildRetention . setBuildNumbersNotToBeDiscarded ( notToBeDeleted ) ; return buildRetention ; }
|
Create a Build retention object out of the build
| 282
| 9
|
151,267
|
public static String getImageIdFromTag ( String imageTag , String host ) throws IOException { DockerClient dockerClient = null ; try { dockerClient = getDockerClient ( host ) ; return dockerClient . inspectImageCmd ( imageTag ) . exec ( ) . getId ( ) ; } finally { closeQuietly ( dockerClient ) ; } }
|
Get image Id from imageTag using DockerBuildInfoHelper client .
| 75
| 13
|
151,268
|
public static void pushImage ( String imageTag , String username , String password , String host ) throws IOException { final AuthConfig authConfig = new AuthConfig ( ) ; authConfig . withUsername ( username ) ; authConfig . withPassword ( password ) ; DockerClient dockerClient = null ; try { dockerClient = getDockerClient ( host ) ; dockerClient . pushImageCmd ( imageTag ) . withAuthConfig ( authConfig ) . exec ( new PushImageResultCallback ( ) ) . awaitSuccess ( ) ; } finally { closeQuietly ( dockerClient ) ; } }
|
Push docker image using the docker java client .
| 123
| 9
|
151,269
|
public static void pullImage ( String imageTag , String username , String password , String host ) throws IOException { final AuthConfig authConfig = new AuthConfig ( ) ; authConfig . withUsername ( username ) ; authConfig . withPassword ( password ) ; DockerClient dockerClient = null ; try { dockerClient = getDockerClient ( host ) ; dockerClient . pullImageCmd ( imageTag ) . withAuthConfig ( authConfig ) . exec ( new PullImageResultCallback ( ) ) . awaitSuccess ( ) ; } finally { closeQuietly ( dockerClient ) ; } }
|
Pull docker image using the docker java client .
| 123
| 9
|
151,270
|
public static String getParentId ( String digest , String host ) throws IOException { DockerClient dockerClient = null ; try { dockerClient = getDockerClient ( host ) ; return dockerClient . inspectImageCmd ( digest ) . exec ( ) . getParent ( ) ; } finally { closeQuietly ( dockerClient ) ; } }
|
Get parent digest of an image .
| 71
| 7
|
151,271
|
public static List < String > getLayersDigests ( String manifestContent ) throws IOException { List < String > dockerLayersDependencies = new ArrayList < String > ( ) ; JsonNode manifest = Utils . mapper ( ) . readTree ( manifestContent ) ; JsonNode schemaVersion = manifest . get ( "schemaVersion" ) ; if ( schemaVersion == null ) { throw new IllegalStateException ( "Could not find 'schemaVersion' in manifest" ) ; } boolean isSchemeVersion1 = schemaVersion . asInt ( ) == 1 ; JsonNode fsLayers = getFsLayers ( manifest , isSchemeVersion1 ) ; for ( JsonNode fsLayer : fsLayers ) { JsonNode blobSum = getBlobSum ( isSchemeVersion1 , fsLayer ) ; dockerLayersDependencies . add ( blobSum . asText ( ) ) ; } dockerLayersDependencies . add ( getConfigDigest ( manifestContent ) ) ; //Add manifest sha1 String manifestSha1 = Hashing . sha1 ( ) . hashString ( manifestContent , Charsets . UTF_8 ) . toString ( ) ; dockerLayersDependencies . add ( "sha1:" + manifestSha1 ) ; return dockerLayersDependencies ; }
|
Get a list of layer digests from docker manifest .
| 286
| 11
|
151,272
|
public static String digestToFileName ( String digest ) { if ( StringUtils . startsWith ( digest , "sha1" ) ) { return "manifest.json" ; } return getShaVersion ( digest ) + "__" + getShaValue ( digest ) ; }
|
Digest format to layer file name .
| 61
| 8
|
151,273
|
public static int getNumberOfDependentLayers ( String imageContent ) throws IOException { JsonNode history = Utils . mapper ( ) . readTree ( imageContent ) . get ( "history" ) ; if ( history == null ) { throw new IllegalStateException ( "Could not find 'history' tag" ) ; } int layersNum = history . size ( ) ; boolean newImageLayers = true ; for ( int i = history . size ( ) - 1 ; i >= 0 ; i -- ) { if ( newImageLayers ) { layersNum -- ; } JsonNode layer = history . get ( i ) ; JsonNode emptyLayer = layer . get ( "empty_layer" ) ; if ( ! newImageLayers && emptyLayer != null ) { layersNum -- ; } if ( layer . get ( "created_by" ) == null ) { continue ; } String createdBy = layer . get ( "created_by" ) . textValue ( ) ; if ( createdBy . contains ( "ENTRYPOINT" ) || createdBy . contains ( "MAINTAINER" ) ) { newImageLayers = false ; } } return layersNum ; }
|
Returns number of dependencies layers in the image .
| 253
| 9
|
151,274
|
private List < String > getMavenModules ( MavenModuleSetBuild mavenBuild ) throws IOException , InterruptedException { FilePath pathToModuleRoot = mavenBuild . getModuleRoot ( ) ; FilePath pathToPom = new FilePath ( pathToModuleRoot , mavenBuild . getProject ( ) . getRootPOM ( null ) ) ; return pathToPom . act ( new MavenModulesExtractor ( ) ) ; }
|
Retrieve from the parent pom the path to the modules of the project
| 99
| 15
|
151,275
|
private String getRelativePomPath ( MavenModule mavenModule , MavenModuleSetBuild mavenBuild ) { String relativePath = mavenModule . getRelativePath ( ) ; if ( StringUtils . isBlank ( relativePath ) ) { return POM_NAME ; } // If this is the root module, return the root pom path. if ( mavenModule . getModuleName ( ) . toString ( ) . equals ( mavenBuild . getProject ( ) . getRootModule ( ) . getModuleName ( ) . toString ( ) ) ) { return mavenBuild . getProject ( ) . getRootPOM ( null ) ; } // to remove the project folder name if exists // keeps only the name of the module String modulePath = relativePath . substring ( relativePath . indexOf ( "/" ) + 1 ) ; for ( String moduleName : mavenModules ) { if ( moduleName . contains ( modulePath ) ) { return createPomPath ( relativePath , moduleName ) ; } } // In case this module is not in the parent pom return relativePath + "/" + POM_NAME ; }
|
Retrieve the relative path to the pom of the module
| 248
| 12
|
151,276
|
private String createPomPath ( String relativePath , String moduleName ) { if ( ! moduleName . contains ( ".xml" ) ) { // Inside the parent pom, the reference is to the pom.xml file return relativePath + "/" + POM_NAME ; } // There is a reference to another xml file, which is not the pom. String dirName = relativePath . substring ( 0 , relativePath . indexOf ( "/" ) ) ; return dirName + "/" + moduleName ; }
|
Creates the actual path to the xml file of the module .
| 111
| 13
|
151,277
|
public List < String > invoke ( File f , VirtualChannel channel ) throws IOException , InterruptedException { MavenProject mavenProject = getMavenProject ( f . getAbsolutePath ( ) ) ; return mavenProject . getModel ( ) . getModules ( ) ; }
|
This is needed when running on slaves .
| 61
| 8
|
151,278
|
public static String getVcsRevision ( Map < String , String > env ) { String revision = env . get ( "SVN_REVISION" ) ; if ( StringUtils . isBlank ( revision ) ) { revision = env . get ( GIT_COMMIT ) ; } if ( StringUtils . isBlank ( revision ) ) { revision = env . get ( "P4_CHANGELIST" ) ; } return revision ; }
|
Get the VCS revision from the Jenkins build environment . The search will one of SVN_REVISION GIT_COMMIT P4_CHANGELIST in the environment .
| 100
| 38
|
151,279
|
public static String getVcsUrl ( Map < String , String > env ) { String url = env . get ( "SVN_URL" ) ; if ( StringUtils . isBlank ( url ) ) { url = publicGitUrl ( env . get ( "GIT_URL" ) ) ; } if ( StringUtils . isBlank ( url ) ) { url = env . get ( "P4PORT" ) ; } return url ; }
|
Get the VCS url from the Jenkins build environment . The search will one of SVN_REVISION GIT_COMMIT P4_CHANGELIST in the environment .
| 100
| 38
|
151,280
|
private static long daysBetween ( Date date1 , Date date2 ) { long diff ; if ( date2 . after ( date1 ) ) { diff = date2 . getTime ( ) - date1 . getTime ( ) ; } else { diff = date1 . getTime ( ) - date2 . getTime ( ) ; } return diff / ( 24 * 60 * 60 * 1000 ) ; }
|
Naive implementation of the difference in days between two dates
| 84
| 11
|
151,281
|
public static List < String > getBuildNumbersNotToBeDeleted ( Run build ) { List < String > notToDelete = Lists . newArrayList ( ) ; List < ? extends Run < ? , ? > > builds = build . getParent ( ) . getBuilds ( ) ; for ( Run < ? , ? > run : builds ) { if ( run . isKeepLog ( ) ) { notToDelete . add ( String . valueOf ( run . getNumber ( ) ) ) ; } } return notToDelete ; }
|
Get the list of build numbers that are to be kept forever .
| 113
| 13
|
151,282
|
public static String entityToString ( HttpEntity entity ) throws IOException { if ( entity != null ) { InputStream is = entity . getContent ( ) ; return IOUtils . toString ( is , "UTF-8" ) ; } return "" ; }
|
Converts the http entity to string . If entity is null returns empty string .
| 57
| 16
|
151,283
|
public static FilePath createAndGetTempDir ( final FilePath ws ) throws IOException , InterruptedException { // The token that combines the project name and unique number to create unique workspace directory. String workspaceList = System . getProperty ( "hudson.slaves.WorkspaceList" ) ; return ws . act ( new MasterToSlaveCallable < FilePath , IOException > ( ) { @ Override public FilePath call ( ) { final FilePath tempDir = ws . sibling ( ws . getName ( ) + Objects . toString ( workspaceList , "@" ) + "tmp" ) . child ( "artifactory" ) ; File tempDirFile = new File ( tempDir . getRemote ( ) ) ; tempDirFile . mkdirs ( ) ; tempDirFile . deleteOnExit ( ) ; return tempDir ; } } ) ; }
|
Create a temporary directory under a given workspace
| 188
| 8
|
151,284
|
@ Override public boolean postExecute ( MavenBuildProxy build , MavenProject pom , MojoInfo mojo , BuildListener listener , Throwable error ) { //listener.getLogger().println("[MavenDependenciesRecorder] mojo: " + mojo.getClass() + ":" + mojo.getGoal()); //listener.getLogger().println("[MavenDependenciesRecorder] dependencies: " + pom.getArtifacts()); recordMavenDependencies ( pom . getArtifacts ( ) ) ; return true ; }
|
Mojos perform different dependency resolution so we add dependencies for each mojo .
| 127
| 16
|
151,285
|
@ Override public boolean postBuild ( MavenBuildProxy build , MavenProject pom , BuildListener listener ) throws InterruptedException , IOException { build . executeAsync ( new BuildCallable < Void , IOException > ( ) { // record is transient, so needs to make a copy first private final Set < MavenDependency > d = dependencies ; public Void call ( MavenBuild build ) throws IOException , InterruptedException { // add the action //TODO: [by yl] These actions are persisted into the build.xml of each build run - we need another //context to store these actions build . getActions ( ) . add ( new MavenDependenciesRecord ( build , d ) ) ; return null ; } } ) ; return true ; }
|
Sends the collected dependencies over to the master and record them .
| 165
| 13
|
151,286
|
public static CredentialsConfig getPreferredDeployer ( DeployerOverrider deployerOverrider , ArtifactoryServer server ) { if ( deployerOverrider . isOverridingDefaultDeployer ( ) ) { CredentialsConfig deployerCredentialsConfig = deployerOverrider . getDeployerCredentialsConfig ( ) ; if ( deployerCredentialsConfig != null ) { return deployerCredentialsConfig ; } } if ( server != null ) { CredentialsConfig deployerCredentials = server . getDeployerCredentialsConfig ( ) ; if ( deployerCredentials != null ) { return deployerCredentials ; } } return CredentialsConfig . EMPTY_CREDENTIALS_CONFIG ; }
|
Decides and returns the preferred deployment credentials to use from this builder settings and selected server
| 162
| 17
|
151,287
|
@ Override public boolean perform ( AbstractBuild < ? , ? > build , Launcher launcher , BuildListener listener ) throws InterruptedException , IOException { listener . getLogger ( ) . println ( "Jenkins Artifactory Plugin version: " + ActionableHelper . getArtifactoryPluginVersion ( ) ) ; EnvVars env = build . getEnvironment ( listener ) ; FilePath workDir = build . getModuleRoot ( ) ; FilePath ws = build . getWorkspace ( ) ; FilePath mavenHome = getMavenHome ( listener , env , launcher ) ; if ( ! mavenHome . exists ( ) ) { listener . error ( "Couldn't find Maven home: " + mavenHome . getRemote ( ) ) ; throw new Run . RunnerAbortedException ( ) ; } ArgumentListBuilder cmdLine = buildMavenCmdLine ( build , listener , env , launcher , mavenHome , ws , ws ) ; String [ ] cmds = cmdLine . toCommandArray ( ) ; return RunMaven ( build , launcher , listener , env , workDir , cmds ) ; }
|
Used by FreeStyle Maven jobs only
| 240
| 8
|
151,288
|
public boolean perform ( Run < ? , ? > build , Launcher launcher , TaskListener listener , EnvVars env , FilePath workDir , FilePath tempDir ) throws InterruptedException , IOException { listener . getLogger ( ) . println ( "Jenkins Artifactory Plugin version: " + ActionableHelper . getArtifactoryPluginVersion ( ) ) ; FilePath mavenHome = getMavenHome ( listener , env , launcher ) ; if ( ! mavenHome . exists ( ) ) { listener . getLogger ( ) . println ( "Couldn't find Maven home at " + mavenHome . getRemote ( ) + " on agent " + Utils . getAgentName ( workDir ) + ". This could be because this build is running inside a Docker container." ) ; } ArgumentListBuilder cmdLine = buildMavenCmdLine ( build , listener , env , launcher , mavenHome , workDir , tempDir ) ; String [ ] cmds = cmdLine . toCommandArray ( ) ; return RunMaven ( build , launcher , listener , env , workDir , cmds ) ; }
|
Used by Pipeline jobs only
| 238
| 5
|
151,289
|
private FilePath copyClassWorldsFile ( FilePath ws , URL resource ) { try { FilePath remoteClassworlds = ws . createTextTempFile ( "classworlds" , "conf" , "" ) ; remoteClassworlds . copyFrom ( resource ) ; return remoteClassworlds ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
|
Copies a classworlds file to a temporary location either on the local filesystem or on a slave depending on the node type .
| 82
| 26
|
151,290
|
public static < T extends Publisher > T getPublisher ( AbstractProject < ? , ? > project , Class < T > type ) { // Search for a publisher of the given type in the project and return it if found: T publisher = new PublisherFindImpl < T > ( ) . find ( project , type ) ; if ( publisher != null ) { return publisher ; } // If not found, the publisher might be wrapped by a "Flexible Publish" publisher. The below searches for it inside the // Flexible Publisher: publisher = new PublisherFlexible < T > ( ) . find ( project , type ) ; return publisher ; }
|
Search for a publisher of the given type in a project and return it or null if it is not found .
| 133
| 22
|
151,291
|
public static String getArtifactoryPluginVersion ( ) { String pluginsSortName = "artifactory" ; //Validates Jenkins existence because in some jobs the Jenkins instance is unreachable if ( Jenkins . getInstance ( ) != null && Jenkins . getInstance ( ) . getPlugin ( pluginsSortName ) != null && Jenkins . getInstance ( ) . getPlugin ( pluginsSortName ) . getWrapper ( ) != null ) { return Jenkins . getInstance ( ) . getPlugin ( pluginsSortName ) . getWrapper ( ) . getVersion ( ) ; } return "" ; }
|
Returns the version of Jenkins Artifactory Plugin or empty string if not found
| 122
| 15
|
151,292
|
public static void deleteFilePath ( FilePath workspace , String path ) throws IOException { if ( StringUtils . isNotBlank ( path ) ) { try { FilePath propertiesFile = new FilePath ( workspace , path ) ; propertiesFile . delete ( ) ; } catch ( Exception e ) { throw new IOException ( "Could not delete temp file: " + path ) ; } } }
|
Deletes a FilePath file .
| 83
| 7
|
151,293
|
public String getRemoteUrl ( String defaultRemoteUrl ) { if ( StringUtils . isBlank ( defaultRemoteUrl ) ) { RemoteConfig remoteConfig = getJenkinsScm ( ) . getRepositories ( ) . get ( 0 ) ; URIish uri = remoteConfig . getURIs ( ) . get ( 0 ) ; return uri . toPrivateString ( ) ; } return defaultRemoteUrl ; }
|
This method is currently in use only by the SvnCoordinator
| 88
| 14
|
151,294
|
public String getRepoKey ( ) { String repoKey ; if ( isDynamicMode ( ) ) { repoKey = keyFromText ; } else { repoKey = keyFromSelect ; } return repoKey ; }
|
Used to get the current repository key
| 45
| 7
|
151,295
|
public void collectVariables ( EnvVars env , Run build , TaskListener listener ) { EnvVars buildParameters = Utils . extractBuildParameters ( build , listener ) ; if ( buildParameters != null ) { env . putAll ( buildParameters ) ; } addAllWithFilter ( envVars , env , filter . getPatternFilter ( ) ) ; Map < String , String > sysEnv = new HashMap <> ( ) ; Properties systemProperties = System . getProperties ( ) ; Enumeration < ? > enumeration = systemProperties . propertyNames ( ) ; while ( enumeration . hasMoreElements ( ) ) { String propertyKey = ( String ) enumeration . nextElement ( ) ; sysEnv . put ( propertyKey , systemProperties . getProperty ( propertyKey ) ) ; } addAllWithFilter ( sysVars , sysEnv , filter . getPatternFilter ( ) ) ; }
|
Collect environment variables and system properties under with filter constrains
| 199
| 12
|
151,296
|
protected void append ( Env env ) { addAllWithFilter ( this . envVars , env . envVars , filter . getPatternFilter ( ) ) ; addAllWithFilter ( this . sysVars , env . sysVars , filter . getPatternFilter ( ) ) ; }
|
Append environment variables and system properties from othre PipelineEvn object
| 62
| 15
|
151,297
|
private void addAllWithFilter ( Map < String , String > toMap , Map < String , String > fromMap , IncludeExcludePatterns pattern ) { for ( Object o : fromMap . entrySet ( ) ) { Map . Entry entry = ( Map . Entry ) o ; String key = ( String ) entry . getKey ( ) ; if ( PatternMatcher . pathConflicts ( key , pattern ) ) { continue ; } toMap . put ( key , ( String ) entry . getValue ( ) ) ; } }
|
Adds all pairs from fromMap to toMap excluding once that matching the pattern
| 111
| 15
|
151,298
|
public void credentialsMigration ( T overrider , Class overriderClass ) { try { deployerMigration ( overrider , overriderClass ) ; resolverMigration ( overrider , overriderClass ) ; } catch ( NoSuchFieldException | IllegalAccessException | IOException e ) { converterErrors . add ( getConversionErrorMessage ( overrider , e ) ) ; } }
|
Migrate to Jenkins Credentials plugin from the old credential implementation
| 82
| 13
|
151,299
|
private ServerDetails createInitialResolveDetailsFromDeployDetails ( ServerDetails deployerDetails ) { RepositoryConf oldResolveRepositoryConfig = deployerDetails . getResolveReleaseRepository ( ) ; RepositoryConf oldSnapshotResolveRepositoryConfig = deployerDetails . getResolveSnapshotRepository ( ) ; RepositoryConf resolverReleaseRepos = oldResolveRepositoryConfig == null ? RepositoryConf . emptyRepositoryConfig : oldResolveRepositoryConfig ; RepositoryConf resolveSnapshotRepos = oldSnapshotResolveRepositoryConfig == null ? RepositoryConf . emptyRepositoryConfig : oldSnapshotResolveRepositoryConfig ; return new ServerDetails ( deployerDetails . getArtifactoryName ( ) , deployerDetails . getArtifactoryUrl ( ) , null , null , resolverReleaseRepos , resolveSnapshotRepos , null , null ) ; }
|
Creates a new ServerDetails object for resolver this will take URL and name from the deployer ServerDetails as a default behaviour
| 191
| 26
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.