idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
27,800 | 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 . |
27,801 | private void copyResources ( File outputDirectory ) throws IOException { copyClasspathResource ( outputDirectory , "reportng.css" , "reportng.css" ) ; copyClasspathResource ( outputDirectory , "reportng.js" , "reportng.js" ) ; File customStylesheet = META . getStylesheetPath ( ) ; if ( customStylesheet != null ) { if ( customStylesheet . exists ( ) ) { copyFile ( outputDirectory , customStylesheet , CUSTOM_STYLE_FILE ) ; } else { 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 . |
27,802 | 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 . |
27,803 | 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 . |
27,804 | 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 . |
27,805 | 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 . |
27,806 | private long getEndTime ( ISuite suite , IInvokedMethod method ) { 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 ( ) ; } } 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 . |
27,807 | public void waitForBuffer ( long timeoutMilli ) { 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" ) ; } logger . trace ( "Waited" ) ; } } } | What is something came in between when we last checked and when this method is called |
27,808 | 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 |
27,809 | 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 . |
27,810 | 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 . |
27,811 | protected ExpectState prepareClosure ( int pairIndex , MatchResult result ) { ExpectState state ; Map < String , Object > prevMap = null ; if ( g_state != null ) { prevMap = g_state . getVars ( ) ; } int matchedWhere = result . beginOffset ( 0 ) ; String matchedText = result . toString ( ) ; 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 . |
27,812 | 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" ) ; } 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 ( ) ; } 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 . |
27,813 | 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 . |
27,814 | 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 . |
27,815 | 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 ( ":" ) ; 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 . |
27,816 | 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 . |
27,817 | 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 . |
27,818 | 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 . |
27,819 | public Deployment setServerGroups ( final Collection < String > serverGroups ) { this . serverGroups . clear ( ) ; this . serverGroups . addAll ( serverGroups ) ; return this ; } | Sets the server groups for the deployment . |
27,820 | 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 . |
27,821 | 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 . |
27,822 | 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 |
27,823 | 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 . |
27,824 | public static ContainerDescription getContainerDescription ( final ModelControllerClient client ) throws IOException , OperationExecutionException { return DefaultContainerDescription . lookup ( Assert . checkNotNullParam ( "client" , client ) ) ; } | Returns the description of the running container . |
27,825 | 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 . |
27,826 | public static void shutdownDomain ( final ModelControllerClient client , final int timeout ) throws IOException , OperationExecutionException { 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 ) ; } final ModelNode address = determineHostAddress ( client ) ; final ModelNode shutdownOp = Operations . createOperation ( "shutdown" , address ) ; response = client . execute ( shutdownOp ) ; if ( Operations . isSuccessfulOutcome ( response ) ) { 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 . |
27,827 | 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 . |
27,828 | 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 . |
27,829 | 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 . |
27,830 | 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 . |
27,831 | 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 . |
27,832 | 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 . |
27,833 | public static UndeployDescription of ( final DeploymentDescription deploymentDescription ) { Assert . checkNotNullParam ( "deploymentDescription" , deploymentDescription ) ; return of ( deploymentDescription . getName ( ) ) . addServerGroups ( deploymentDescription . getServerGroups ( ) ) ; } | Creates a new undeploy description . |
27,834 | 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 . |
27,835 | 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 |
27,836 | static void addDeployOperationStep ( final CompositeOperationBuilder builder , final DeploymentDescription deployment ) { final String name = deployment . getName ( ) ; final Set < String > serverGroups = deployment . getServerGroups ( ) ; 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 . |
27,837 | 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 . |
27,838 | 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 . |
27,839 | 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 . |
27,840 | 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 . |
27,841 | 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 . |
27,842 | 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 . |
27,843 | 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 . |
27,844 | 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 . |
27,845 | 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 . |
27,846 | 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 . |
27,847 | @ SuppressWarnings ( { "UnusedDeclaration" } ) public LoadBuildsResponse loadBuild ( String buildId ) { LoadBuildsResponse response = new LoadBuildsResponse ( ) ; 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 . |
27,848 | @ 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 . |
27,849 | 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 . |
27,850 | 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 . |
27,851 | public static boolean promoteAndCheckResponse ( Promotion promotion , ArtifactoryBuildInfoClient client , TaskListener listener , String buildName , String buildNumber ) throws IOException { 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 ..." ) ; } 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 . |
27,852 | 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 . |
27,853 | 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 |
27,854 | public static boolean distributeAndCheckResponse ( DistributionBuilder distributionBuilder , ArtifactoryBuildInfoClient client , TaskListener listener , String buildName , String buildNumber , boolean dryRun ) throws IOException { 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 . |
27,855 | 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 . |
27,856 | public T find ( AbstractProject < ? , ? > project , Class < T > type ) { if ( Jenkins . getInstance ( ) . getPlugin ( FLEXIBLE_PUBLISH_PLUGIN ) != null ) { for ( Publisher publisher : project . getPublishersList ( ) ) { if ( publisher instanceof FlexiblePublisher ) { 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 . |
27,857 | 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 . |
27,858 | public void commitWorkingCopy ( final String commitMessage ) throws IOException , InterruptedException { build . getWorkspace ( ) . act ( new SVNCommitWorkingCopyCallable ( commitMessage , getLocation ( ) , getSvnAuthenticationProvider ( build ) , buildListener ) ) ; } | Commits the working copy . |
27,859 | 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 . |
27,860 | public void revertWorkingCopy ( ) throws IOException , InterruptedException { build . getWorkspace ( ) . act ( new RevertWorkingCopyCallable ( getLocation ( ) , getSvnAuthenticationProvider ( build ) , buildListener ) ) ; } | Revert all the working copy changes . |
27,861 | 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 ) { 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 . |
27,862 | 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 |
27,863 | 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 |
27,864 | 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 . |
27,865 | 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 . |
27,866 | 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 . |
27,867 | 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 . |
27,868 | 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 ) ) ; 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 . |
27,869 | 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 . |
27,870 | 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 . |
27,871 | 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 |
27,872 | private String getRelativePomPath ( MavenModule mavenModule , MavenModuleSetBuild mavenBuild ) { String relativePath = mavenModule . getRelativePath ( ) ; if ( StringUtils . isBlank ( relativePath ) ) { return POM_NAME ; } if ( mavenModule . getModuleName ( ) . toString ( ) . equals ( mavenBuild . getProject ( ) . getRootModule ( ) . getModuleName ( ) . toString ( ) ) ) { return mavenBuild . getProject ( ) . getRootPOM ( null ) ; } String modulePath = relativePath . substring ( relativePath . indexOf ( "/" ) + 1 ) ; for ( String moduleName : mavenModules ) { if ( moduleName . contains ( modulePath ) ) { return createPomPath ( relativePath , moduleName ) ; } } return relativePath + "/" + POM_NAME ; } | Retrieve the relative path to the pom of the module |
27,873 | private String createPomPath ( String relativePath , String moduleName ) { if ( ! moduleName . contains ( ".xml" ) ) { return relativePath + "/" + POM_NAME ; } String dirName = relativePath . substring ( 0 , relativePath . indexOf ( "/" ) ) ; return dirName + "/" + moduleName ; } | Creates the actual path to the xml file of the module . |
27,874 | 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 . |
27,875 | 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 . |
27,876 | 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 . |
27,877 | 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 |
27,878 | 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 . |
27,879 | 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 . |
27,880 | public static FilePath createAndGetTempDir ( final FilePath ws ) throws IOException , InterruptedException { String workspaceList = System . getProperty ( "hudson.slaves.WorkspaceList" ) ; return ws . act ( new MasterToSlaveCallable < FilePath , IOException > ( ) { 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 |
27,881 | public boolean postExecute ( MavenBuildProxy build , MavenProject pom , MojoInfo mojo , BuildListener listener , Throwable error ) { recordMavenDependencies ( pom . getArtifacts ( ) ) ; return true ; } | Mojos perform different dependency resolution so we add dependencies for each mojo . |
27,882 | public boolean postBuild ( MavenBuildProxy build , MavenProject pom , BuildListener listener ) throws InterruptedException , IOException { build . executeAsync ( new BuildCallable < Void , IOException > ( ) { private final Set < MavenDependency > d = dependencies ; public Void call ( MavenBuild build ) throws IOException , InterruptedException { build . getActions ( ) . add ( new MavenDependenciesRecord ( build , d ) ) ; return null ; } } ) ; return true ; } | Sends the collected dependencies over to the master and record them . |
27,883 | 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 |
27,884 | 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 |
27,885 | 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 |
27,886 | 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 . |
27,887 | public static < T extends Publisher > T getPublisher ( AbstractProject < ? , ? > project , Class < T > type ) { T publisher = new PublisherFindImpl < T > ( ) . find ( project , type ) ; if ( publisher != null ) { return 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 . |
27,888 | public static String getArtifactoryPluginVersion ( ) { String pluginsSortName = "artifactory" ; 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 |
27,889 | 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 . |
27,890 | 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 |
27,891 | public String getRepoKey ( ) { String repoKey ; if ( isDynamicMode ( ) ) { repoKey = keyFromText ; } else { repoKey = keyFromSelect ; } return repoKey ; } | Used to get the current repository key |
27,892 | 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 |
27,893 | 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 |
27,894 | 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 |
27,895 | 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 |
27,896 | 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 |
27,897 | private ServerDetails createInitialDeployDetailsFromOldDeployDetails ( ServerDetails oldDeployerDetails ) { RepositoryConf oldDeployRepositoryConfig = oldDeployerDetails . getDeployReleaseRepository ( ) ; RepositoryConf oldSnapshotDeployRepositoryConfig = oldDeployerDetails . getDeploySnapshotRepository ( ) ; RepositoryConf deployReleaseRepos = oldDeployRepositoryConfig == null ? RepositoryConf . emptyRepositoryConfig : oldDeployRepositoryConfig ; RepositoryConf deploySnapshotRepos = oldSnapshotDeployRepositoryConfig == null ? RepositoryConf . emptyRepositoryConfig : oldSnapshotDeployRepositoryConfig ; return new ServerDetails ( oldDeployerDetails . getArtifactoryName ( ) , oldDeployerDetails . getArtifactoryUrl ( ) , deployReleaseRepos , deploySnapshotRepos , null , null , null , null ) ; } | Creates a new ServerDetails object for deployer this will take URL and name from the oldDeployer ServerDetails |
27,898 | private static Properties loadGradleProperties ( FilePath gradlePropertiesFilePath ) throws IOException , InterruptedException { return gradlePropertiesFilePath . act ( new MasterToSlaveFileCallable < Properties > ( ) { public Properties invoke ( File gradlePropertiesFile , VirtualChannel channel ) throws IOException , InterruptedException { Properties gradleProps = new Properties ( ) ; if ( gradlePropertiesFile . exists ( ) ) { debuggingLogger . fine ( "Gradle properties file exists at: " + gradlePropertiesFile . getAbsolutePath ( ) ) ; FileInputStream stream = null ; try { stream = new FileInputStream ( gradlePropertiesFile ) ; gradleProps . load ( stream ) ; } catch ( IOException e ) { debuggingLogger . fine ( "IO exception occurred while trying to read properties file from: " + gradlePropertiesFile . getAbsolutePath ( ) ) ; throw new RuntimeException ( e ) ; } finally { IOUtils . closeQuietly ( stream ) ; } } return gradleProps ; } } ) ; } | Load a properties file from a file path |
27,899 | public Module generateBuildInfoModule ( Run build , TaskListener listener , ArtifactoryConfigurator config , String buildName , String buildNumber , String timestamp ) throws IOException { if ( artifactsProps == null ) { artifactsProps = ArrayListMultimap . create ( ) ; } artifactsProps . put ( "build.name" , buildName ) ; artifactsProps . put ( "build.number" , buildNumber ) ; artifactsProps . put ( "build.timestamp" , timestamp ) ; String artifactsPropsStr = ExtractorUtils . buildPropertiesString ( artifactsProps ) ; Properties buildInfoItemsProps = new Properties ( ) ; buildInfoItemsProps . setProperty ( "build.name" , buildName ) ; buildInfoItemsProps . setProperty ( "build.number" , buildNumber ) ; buildInfoItemsProps . setProperty ( "build.timestamp" , timestamp ) ; ArtifactoryServer server = config . getArtifactoryServer ( ) ; CredentialsConfig preferredResolver = server . getDeployerCredentialsConfig ( ) ; ArtifactoryDependenciesClient dependenciesClient = null ; ArtifactoryBuildInfoClient propertyChangeClient = null ; try { dependenciesClient = server . createArtifactoryDependenciesClient ( preferredResolver . provideUsername ( build . getParent ( ) ) , preferredResolver . providePassword ( build . getParent ( ) ) , server . createProxyConfiguration ( Jenkins . getInstance ( ) . proxy ) , listener ) ; CredentialsConfig preferredDeployer = CredentialManager . getPreferredDeployer ( config , server ) ; propertyChangeClient = server . createArtifactoryClient ( preferredDeployer . provideUsername ( build . getParent ( ) ) , preferredDeployer . providePassword ( build . getParent ( ) ) , server . createProxyConfiguration ( Jenkins . getInstance ( ) . proxy ) ) ; Module buildInfoModule = new Module ( ) ; buildInfoModule . setId ( imageTag . substring ( imageTag . indexOf ( "/" ) + 1 ) ) ; if ( ( StringUtils . isEmpty ( manifest ) || StringUtils . isEmpty ( imagePath ) ) && ! findAndSetManifestFromArtifactory ( server , dependenciesClient , listener ) ) { return buildInfoModule ; } listener . getLogger ( ) . println ( "Fetching details of published docker layers from Artifactory..." ) ; boolean includeVirtualReposSupported = propertyChangeClient . getArtifactoryVersion ( ) . isAtLeast ( VIRTUAL_REPOS_SUPPORTED_VERSION ) ; DockerLayers layers = createLayers ( dependenciesClient , includeVirtualReposSupported ) ; listener . getLogger ( ) . println ( "Tagging published docker layers with build properties in Artifactory..." ) ; setDependenciesAndArtifacts ( buildInfoModule , layers , artifactsPropsStr , buildInfoItemsProps , dependenciesClient , propertyChangeClient , server ) ; setBuildInfoModuleProps ( buildInfoModule ) ; return buildInfoModule ; } finally { if ( dependenciesClient != null ) { dependenciesClient . close ( ) ; } if ( propertyChangeClient != null ) { propertyChangeClient . close ( ) ; } } } | Generates the build - info module for this docker image . Additionally . this method tags the deployed docker layers with properties such as build . name build . number and custom properties defined in the Jenkins build . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.