idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
16,600
public PluginWrapper getPlugin ( String shortName ) { for ( PluginWrapper p : getPlugins ( ) ) { if ( p . getShortName ( ) . equals ( shortName ) ) return p ; } return null ; }
Get the plugin instance with the given short name .
16,601
public void stop ( ) { for ( PluginWrapper p : activePlugins ) { p . stop ( ) ; p . releaseClassLoader ( ) ; } activePlugins . clear ( ) ; LogFactory . release ( uberClassLoader ) ; }
Orderly terminates all the plugins .
16,602
@ Restricted ( DoNotUse . class ) public HttpResponse doPlugins ( ) { Jenkins . getInstance ( ) . checkPermission ( Jenkins . ADMINISTER ) ; JSONArray response = new JSONArray ( ) ; Map < String , JSONObject > allPlugins = new HashMap < > ( ) ; for ( PluginWrapper plugin : plugins ) { JSONObject pluginInfo = new JSONObject ( ) ; pluginInfo . put ( "installed" , true ) ; pluginInfo . put ( "name" , plugin . getShortName ( ) ) ; pluginInfo . put ( "title" , plugin . getDisplayName ( ) ) ; pluginInfo . put ( "active" , plugin . isActive ( ) ) ; pluginInfo . put ( "enabled" , plugin . isEnabled ( ) ) ; pluginInfo . put ( "bundled" , plugin . isBundled ) ; pluginInfo . put ( "deleted" , plugin . isDeleted ( ) ) ; pluginInfo . put ( "downgradable" , plugin . isDowngradable ( ) ) ; pluginInfo . put ( "website" , plugin . getUrl ( ) ) ; List < Dependency > dependencies = plugin . getDependencies ( ) ; if ( dependencies != null && ! dependencies . isEmpty ( ) ) { Map < String , String > dependencyMap = new HashMap < > ( ) ; for ( Dependency dependency : dependencies ) { dependencyMap . put ( dependency . shortName , dependency . version ) ; } pluginInfo . put ( "dependencies" , dependencyMap ) ; } else { pluginInfo . put ( "dependencies" , Collections . emptyMap ( ) ) ; } response . add ( pluginInfo ) ; } for ( UpdateSite site : Jenkins . getActiveInstance ( ) . getUpdateCenter ( ) . getSiteList ( ) ) { for ( UpdateSite . Plugin plugin : site . getAvailables ( ) ) { JSONObject pluginInfo = allPlugins . get ( plugin . name ) ; if ( pluginInfo == null ) { pluginInfo = new JSONObject ( ) ; pluginInfo . put ( "installed" , false ) ; } pluginInfo . put ( "name" , plugin . name ) ; pluginInfo . put ( "title" , plugin . getDisplayName ( ) ) ; pluginInfo . put ( "excerpt" , plugin . excerpt ) ; pluginInfo . put ( "site" , site . getId ( ) ) ; pluginInfo . put ( "dependencies" , plugin . dependencies ) ; pluginInfo . put ( "website" , plugin . wiki ) ; response . add ( pluginInfo ) ; } } return hudson . util . HttpResponses . okJSON ( response ) ; }
Get the list of all plugins - available and installed .
16,603
@ Restricted ( DoNotUse . class ) public HttpResponse doInstallPlugins ( StaplerRequest req ) throws IOException { Jenkins . getInstance ( ) . checkPermission ( Jenkins . ADMINISTER ) ; String payload = IOUtils . toString ( req . getInputStream ( ) , req . getCharacterEncoding ( ) ) ; JSONObject request = JSONObject . fromObject ( payload ) ; JSONArray pluginListJSON = request . getJSONArray ( "plugins" ) ; List < String > plugins = new ArrayList < > ( ) ; for ( int i = 0 ; i < pluginListJSON . size ( ) ; i ++ ) { plugins . add ( pluginListJSON . getString ( i ) ) ; } UUID correlationId = UUID . randomUUID ( ) ; try { boolean dynamicLoad = request . getBoolean ( "dynamicLoad" ) ; install ( plugins , dynamicLoad , correlationId ) ; JSONObject responseData = new JSONObject ( ) ; responseData . put ( "correlationId" , correlationId . toString ( ) ) ; return hudson . util . HttpResponses . okJSON ( responseData ) ; } catch ( Exception e ) { return hudson . util . HttpResponses . errorJSON ( e . getMessage ( ) ) ; } }
Installs a list of plugins from a JSON POST .
16,604
public HttpResponse doUploadPlugin ( StaplerRequest req ) throws IOException , ServletException { try { Jenkins . getInstance ( ) . checkPermission ( UPLOAD_PLUGINS ) ; ServletFileUpload upload = new ServletFileUpload ( new DiskFileItemFactory ( ) ) ; FileItem fileItem = upload . parseRequest ( req ) . get ( 0 ) ; String fileName = Util . getFileName ( fileItem . getName ( ) ) ; if ( "" . equals ( fileName ) ) { return new HttpRedirect ( "advanced" ) ; } if ( ! fileName . endsWith ( ".jpi" ) && ! fileName . endsWith ( ".hpi" ) ) { throw new Failure ( hudson . model . Messages . Hudson_NotAPlugin ( fileName ) ) ; } File t = File . createTempFile ( "uploaded" , ".jpi" ) ; t . deleteOnExit ( ) ; try { fileItem . write ( t ) ; } catch ( Exception e ) { throw new ServletException ( e ) ; } fileItem . delete ( ) ; final String baseName = identifyPluginShortName ( t ) ; pluginUploaded = true ; JSONArray dependencies = new JSONArray ( ) ; try { Manifest m = new JarFile ( t ) . getManifest ( ) ; String deps = m . getMainAttributes ( ) . getValue ( "Plugin-Dependencies" ) ; if ( StringUtils . isNotBlank ( deps ) ) { String [ ] plugins = deps . split ( "," ) ; for ( String p : plugins ) { String [ ] attrs = p . split ( "[:;]" ) ; dependencies . add ( new JSONObject ( ) . element ( "name" , attrs [ 0 ] ) . element ( "version" , attrs [ 1 ] ) . element ( "optional" , p . contains ( "resolution:=optional" ) ) ) ; } } } catch ( IOException e ) { LOGGER . log ( WARNING , "Unable to setup dependency list for plugin upload" , e ) ; } JSONObject cfg = new JSONObject ( ) . element ( "name" , baseName ) . element ( "version" , "0" ) . element ( "url" , t . toURI ( ) . toString ( ) ) . element ( "dependencies" , dependencies ) ; new UpdateSite ( UpdateCenter . ID_UPLOAD , null ) . new Plugin ( UpdateCenter . ID_UPLOAD , cfg ) . deploy ( true ) ; return new HttpRedirect ( "../updateCenter" ) ; } catch ( FileUploadException e ) { throw new ServletException ( e ) ; } }
Uploads a plugin .
16,605
public Map < String , VersionNumber > parseRequestedPlugins ( InputStream configXml ) throws IOException { final Map < String , VersionNumber > requestedPlugins = new TreeMap < > ( ) ; try { SAXParserFactory . newInstance ( ) . newSAXParser ( ) . parse ( configXml , new DefaultHandler ( ) { public void startElement ( String uri , String localName , String qName , Attributes attributes ) throws SAXException { String plugin = attributes . getValue ( "plugin" ) ; if ( plugin == null ) { return ; } if ( ! plugin . matches ( "[^@]+@[^@]+" ) ) { throw new SAXException ( "Malformed plugin attribute: " + plugin ) ; } int at = plugin . indexOf ( '@' ) ; String shortName = plugin . substring ( 0 , at ) ; VersionNumber existing = requestedPlugins . get ( shortName ) ; VersionNumber requested = new VersionNumber ( plugin . substring ( at + 1 ) ) ; if ( existing == null || existing . compareTo ( requested ) < 0 ) { requestedPlugins . put ( shortName , requested ) ; } } public InputSource resolveEntity ( String publicId , String systemId ) throws IOException , SAXException { return RestrictiveEntityResolver . INSTANCE . resolveEntity ( publicId , systemId ) ; } } ) ; } catch ( SAXException x ) { throw new IOException ( "Failed to parse XML" , x ) ; } catch ( ParserConfigurationException e ) { throw new AssertionError ( e ) ; } return requestedPlugins ; }
Parses configuration XML files and picks up references to XML files .
16,606
public JFreeChart createChart ( CategoryDataset ds ) { final JFreeChart chart = ChartFactory . createLineChart ( null , null , null , ds , PlotOrientation . VERTICAL , true , true , false ) ; chart . setBackgroundPaint ( Color . white ) ; final CategoryPlot plot = chart . getCategoryPlot ( ) ; plot . setBackgroundPaint ( Color . WHITE ) ; plot . setOutlinePaint ( null ) ; plot . setRangeGridlinesVisible ( true ) ; plot . setRangeGridlinePaint ( Color . black ) ; final LineAndShapeRenderer renderer = ( LineAndShapeRenderer ) plot . getRenderer ( ) ; renderer . setBaseStroke ( new BasicStroke ( 3 ) ) ; configureRenderer ( renderer ) ; final CategoryAxis domainAxis = new NoOverlapCategoryAxis ( null ) ; plot . setDomainAxis ( domainAxis ) ; domainAxis . setCategoryLabelPositions ( CategoryLabelPositions . UP_90 ) ; domainAxis . setLowerMargin ( 0.0 ) ; domainAxis . setUpperMargin ( 0.0 ) ; domainAxis . setCategoryMargin ( 0.0 ) ; final NumberAxis rangeAxis = ( NumberAxis ) plot . getRangeAxis ( ) ; rangeAxis . setStandardTickUnits ( NumberAxis . createIntegerTickUnits ( ) ) ; plot . setInsets ( new RectangleInsets ( 0 , 0 , 0 , 5.0 ) ) ; return chart ; }
Creates a trend chart .
16,607
protected void updateCounts ( LoadStatisticsSnapshot current ) { definedExecutors . update ( current . getDefinedExecutors ( ) ) ; onlineExecutors . update ( current . getOnlineExecutors ( ) ) ; connectingExecutors . update ( current . getConnectingExecutors ( ) ) ; busyExecutors . update ( current . getBusyExecutors ( ) ) ; idleExecutors . update ( current . getIdleExecutors ( ) ) ; availableExecutors . update ( current . getAvailableExecutors ( ) ) ; queueLength . update ( current . getQueueLength ( ) ) ; }
Updates all the series from the current snapshot .
16,608
public LoadStatisticsSnapshot computeSnapshot ( ) { if ( modern ) { return computeSnapshot ( Jenkins . getInstance ( ) . getQueue ( ) . getBuildableItems ( ) ) ; } else { int t = computeTotalExecutors ( ) ; int i = computeIdleExecutors ( ) ; return new LoadStatisticsSnapshot ( t , t , Math . max ( i - t , 0 ) , Math . max ( t - i , 0 ) , i , i , computeQueueLength ( ) ) ; } }
Computes a self - consistent snapshot of the load statistics .
16,609
protected LoadStatisticsSnapshot computeSnapshot ( Iterable < Queue . BuildableItem > queue ) { final LoadStatisticsSnapshot . Builder builder = LoadStatisticsSnapshot . builder ( ) ; final Iterable < Node > nodes = getNodes ( ) ; if ( nodes != null ) { for ( Node node : nodes ) { builder . with ( node ) ; } } int q = 0 ; if ( queue != null ) { for ( Queue . BuildableItem item : queue ) { for ( SubTask st : item . task . getSubTasks ( ) ) { if ( matches ( item , st ) ) q ++ ; } } } return builder . withQueueLength ( q ) . build ( ) ; }
Computes the self - consistent snapshot with the specified queue items .
16,610
protected void eol ( byte [ ] in , int sz ) throws IOException { int next = ConsoleNote . findPreamble ( in , 0 , sz ) ; int written = 0 ; while ( next >= 0 ) { if ( next > written ) { out . write ( in , written , next - written ) ; written = next ; } else { assert next == written ; } int rest = sz - next ; ByteArrayInputStream b = new ByteArrayInputStream ( in , next , rest ) ; ConsoleNote . skip ( new DataInputStream ( b ) ) ; int bytesUsed = rest - b . available ( ) ; written += bytesUsed ; next = ConsoleNote . findPreamble ( in , written , sz - written ) ; } out . write ( in , written , sz - written ) ; }
Called after we read the whole line of plain text .
16,611
public final void process ( ) throws IOException , ServletException { if ( permission != null ) try { if ( subject == null ) throw new AccessDeniedException ( "No subject" ) ; subject . checkPermission ( permission ) ; } catch ( AccessDeniedException e ) { if ( ! Jenkins . getInstance ( ) . hasPermission ( Jenkins . ADMINISTER ) ) throw e ; } check ( ) ; }
Runs the validation code .
16,612
protected final File getFileParameter ( String paramName ) { return new File ( Util . fixNull ( request . getParameter ( paramName ) ) ) ; }
Gets the parameter as a file .
16,613
public void respond ( String html ) throws IOException , ServletException { response . setContentType ( "text/html" ) ; response . getWriter ( ) . print ( html ) ; }
Sends out an arbitrary HTML fragment .
16,614
public void doPng ( StaplerRequest req , StaplerResponse rsp ) throws IOException { if ( req . checkIfModified ( timestamp , rsp ) ) return ; try { BufferedImage image = render ( req , null ) ; rsp . setContentType ( "image/png" ) ; ServletOutputStream os = rsp . getOutputStream ( ) ; ImageIO . write ( image , "PNG" , os ) ; os . close ( ) ; } catch ( Error e ) { if ( e . getMessage ( ) . contains ( "Probable fatal error:No fonts found" ) ) { rsp . sendRedirect2 ( req . getContextPath ( ) + "/images/headless.png" ) ; return ; } throw e ; } catch ( HeadlessException e ) { rsp . sendRedirect2 ( req . getContextPath ( ) + "/images/headless.png" ) ; } }
Renders a graph .
16,615
public void doMap ( StaplerRequest req , StaplerResponse rsp ) throws IOException { if ( req . checkIfModified ( timestamp , rsp ) ) return ; ChartRenderingInfo info = new ChartRenderingInfo ( ) ; render ( req , info ) ; rsp . setContentType ( "text/plain;charset=UTF-8" ) ; rsp . getWriter ( ) . println ( ChartUtilities . getImageMap ( "map" , info ) ) ; }
Renders a clickable map .
16,616
public long getInitialDelay ( ) { long l = RANDOM . nextLong ( ) ; if ( l == Long . MIN_VALUE ) l ++ ; return Math . abs ( l ) % getRecurrencePeriod ( ) ; }
Gets the number of milliseconds til the first execution .
16,617
public void recordCauseOfInterruption ( Run < ? , ? > build , TaskListener listener ) { List < CauseOfInterruption > r ; lock . writeLock ( ) . lock ( ) ; try { if ( causes . isEmpty ( ) ) return ; r = new ArrayList < > ( causes ) ; causes . clear ( ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } build . addAction ( new InterruptedBuildAction ( r ) ) ; for ( CauseOfInterruption c : r ) c . print ( listener ) ; }
report cause of interruption and record it to the build if available .
16,618
public Queue . Executable getCurrentExecutable ( ) { lock . readLock ( ) . lock ( ) ; try { return executable ; } finally { lock . readLock ( ) . unlock ( ) ; } }
Returns the current build this executor is running .
16,619
public AsynchronousExecution getAsynchronousExecution ( ) { lock . readLock ( ) . lock ( ) ; try { return asynchronousExecution ; } finally { lock . readLock ( ) . unlock ( ) ; } }
If currently running in asynchronous mode returns that handle .
16,620
public int getProgress ( ) { long d = executableEstimatedDuration ; if ( d <= 0 ) { return DEFAULT_ESTIMATED_DURATION ; } int num = ( int ) ( getElapsedTime ( ) * 100 / d ) ; if ( num >= 100 ) { num = 99 ; } return num ; }
Returns the progress of the current build in the number between 0 - 100 .
16,621
public boolean isLikelyStuck ( ) { lock . readLock ( ) . lock ( ) ; try { if ( executable == null ) { return false ; } } finally { lock . readLock ( ) . unlock ( ) ; } long elapsed = getElapsedTime ( ) ; long d = executableEstimatedDuration ; if ( d >= 0 ) { return d * 10 < elapsed ; } else { return TimeUnit . MILLISECONDS . toHours ( elapsed ) > 24 ; } }
Returns true if the current build is likely stuck .
16,622
public long getTimeSpentInQueue ( ) { lock . readLock ( ) . lock ( ) ; try { return startTime - workUnit . context . item . buildableStartMilliseconds ; } finally { lock . readLock ( ) . unlock ( ) ; } }
Returns the number of milli - seconds the currently executing job spent in the queue waiting for an available executor . This excludes the quiet period time of the job .
16,623
public String getEstimatedRemainingTime ( ) { long d = executableEstimatedDuration ; if ( d < 0 ) { return Messages . Executor_NotAvailable ( ) ; } long eta = d - getElapsedTime ( ) ; if ( eta <= 0 ) { return Messages . Executor_NotAvailable ( ) ; } return Util . getTimeSpanString ( eta ) ; }
Computes a human - readable text that shows the expected remaining time until the build completes .
16,624
public HttpResponse doStop ( ) { lock . writeLock ( ) . lock ( ) ; try { if ( executable != null ) { getParentOf ( executable ) . getOwnerTask ( ) . checkAbortPermission ( ) ; interrupt ( ) ; } } finally { lock . writeLock ( ) . unlock ( ) ; } return HttpResponses . forwardToPreviousPage ( ) ; }
Stops the current build .
16,625
public boolean hasStopPermission ( ) { lock . readLock ( ) . lock ( ) ; try { return executable != null && getParentOf ( executable ) . getOwnerTask ( ) . hasAbortPermission ( ) ; } finally { lock . readLock ( ) . unlock ( ) ; } }
Checks if the current user has a permission to stop this build .
16,626
public long getIdleStartMilliseconds ( ) { if ( isIdle ( ) ) return Math . max ( creationTime , owner . getConnectTime ( ) ) ; else { return Math . max ( startTime + Math . max ( 0 , executableEstimatedDuration ) , System . currentTimeMillis ( ) + 15000 ) ; } }
Returns when this executor started or should start being idle .
16,627
public < T > T newImpersonatingProxy ( Class < T > type , T core ) { return new InterceptingProxy ( ) { protected Object call ( Object o , Method m , Object [ ] args ) throws Throwable { final Executor old = IMPERSONATION . get ( ) ; IMPERSONATION . set ( Executor . this ) ; try { return m . invoke ( o , args ) ; } finally { IMPERSONATION . set ( old ) ; } } } . wrap ( type , core ) ; }
Creates a proxy object that executes the callee in the context that impersonates this executor . Useful to export an object to a remote channel .
16,628
public static Executor currentExecutor ( ) { Thread t = Thread . currentThread ( ) ; if ( t instanceof Executor ) return ( Executor ) t ; return IMPERSONATION . get ( ) ; }
Returns the executor of the current thread or null if current thread is not an executor .
16,629
public static Executor of ( Executable executable ) { Jenkins jenkins = Jenkins . getInstanceOrNull ( ) ; if ( jenkins == null ) { return null ; } for ( Computer computer : jenkins . getComputers ( ) ) { for ( Executor executor : computer . getAllExecutors ( ) ) { if ( executor . getCurrentExecutable ( ) == executable ) { return executor ; } } } return null ; }
Finds the executor currently running a given process .
16,630
public SearchResult getSuggestions ( StaplerRequest req , String query ) { Set < String > paths = new HashSet < > ( ) ; SearchResultImpl r = new SearchResultImpl ( ) ; int max = req . hasParameter ( "max" ) ? Integer . parseInt ( req . getParameter ( "max" ) ) : 100 ; SearchableModelObject smo = findClosestSearchableModelObject ( req ) ; for ( SuggestedItem i : suggest ( makeSuggestIndex ( req ) , query , smo ) ) { if ( r . size ( ) >= max ) { r . hasMoreResults = true ; break ; } if ( paths . add ( i . getPath ( ) ) ) r . add ( i ) ; } return r ; }
Gets the list of suggestions that match the given query .
16,631
private SearchIndex makeSuggestIndex ( StaplerRequest req ) { SearchIndexBuilder builder = new SearchIndexBuilder ( ) ; for ( Ancestor a : req . getAncestors ( ) ) { if ( a . getObject ( ) instanceof SearchableModelObject ) { SearchableModelObject smo = ( SearchableModelObject ) a . getObject ( ) ; builder . add ( smo . getSearchIndex ( ) ) ; } } return builder . make ( ) ; }
Creates merged search index for suggestion .
16,632
static SuggestedItem findClosestSuggestedItem ( List < SuggestedItem > r , String query ) { for ( SuggestedItem curItem : r ) { if ( LOGGER . isLoggable ( Level . FINE ) ) { LOGGER . fine ( String . format ( "item's searchUrl:%s;query=%s" , curItem . item . getSearchUrl ( ) , query ) ) ; } if ( curItem . item . getSearchUrl ( ) . contains ( Util . rawEncode ( query ) ) ) { return curItem ; } } return r . get ( 0 ) ; }
When there are multiple suggested items this method can narrow down the resultset to the SuggestedItem that has a url that contains the query . This is useful is one job has a display name that matches another job s project name .
16,633
public static SuggestedItem find ( SearchIndex index , String query , SearchableModelObject searchContext ) { List < SuggestedItem > r = find ( Mode . FIND , index , query , searchContext ) ; if ( r . isEmpty ( ) ) { return null ; } else if ( 1 == r . size ( ) ) { return r . get ( 0 ) ; } else { return findClosestSuggestedItem ( r , query ) ; } }
Performs a search and returns the match or null if no match was found or more than one match was found .
16,634
private InputStream transformForWindows ( InputStream src ) throws IOException { BufferedReader r = new BufferedReader ( new InputStreamReader ( src ) ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; try ( PrintStream p = new PrintStream ( out ) ) { String line ; while ( ( line = r . readLine ( ) ) != null ) { if ( ! line . startsWith ( "#" ) && Functions . isWindows ( ) ) line = line . replace ( "/" , "\\\\" ) ; p . println ( line ) ; } } return new ByteArrayInputStream ( out . toByteArray ( ) ) ; }
Transform path for Windows .
16,635
public HttpResponse doApproveAll ( ) throws IOException { StringBuilder buf = new StringBuilder ( ) ; for ( Class c : rejected . get ( ) ) { buf . append ( c . getName ( ) ) . append ( '\n' ) ; } whitelisted . append ( buf . toString ( ) ) ; return HttpResponses . ok ( ) ; }
Approves all the currently rejected subjects
16,636
public void setCrumbSalt ( String salt ) { if ( Util . fixEmptyAndTrim ( salt ) == null ) { crumbSalt = "hudson.crumb" ; } else { crumbSalt = salt ; } }
Set the salt value . Must not be null .
16,637
public void setCrumbRequestField ( String requestField ) { if ( Util . fixEmptyAndTrim ( requestField ) == null ) { crumbRequestField = CrumbIssuer . DEFAULT_CRUMB_NAME ; } else { crumbRequestField = requestField ; } }
Set the request parameter name . Must not be null .
16,638
public String sign ( String msg ) { try { RSAPrivateKey key = getPrivateKey ( ) ; Signature sig = Signature . getInstance ( SIGNING_ALGORITHM + "with" + key . getAlgorithm ( ) ) ; sig . initSign ( key ) ; sig . update ( msg . getBytes ( StandardCharsets . UTF_8 ) ) ; return hudson . remoting . Base64 . encode ( sig . sign ( ) ) ; } catch ( GeneralSecurityException e ) { throw new SecurityException ( e ) ; } }
Sign a message and base64 encode the signature .
16,639
public static void drain ( InputStream in ) throws IOException { org . apache . commons . io . IOUtils . copy ( in , new NullStream ( ) ) ; in . close ( ) ; }
Drains the input stream and closes it .
16,640
public static InputStream skip ( InputStream in , long size ) throws IOException { DataInputStream di = new DataInputStream ( in ) ; while ( size > 0 ) { int chunk = ( int ) Math . min ( SKIP_BUFFER . length , size ) ; di . readFully ( SKIP_BUFFER , 0 , chunk ) ; size -= chunk ; } return in ; }
Fully skips the specified size from the given input stream .
16,641
public static String readFirstLine ( InputStream is , String encoding ) throws IOException { try ( BufferedReader reader = new BufferedReader ( encoding == null ? new InputStreamReader ( is ) : new InputStreamReader ( is , encoding ) ) ) { return reader . readLine ( ) ; } }
Read the first line of the given stream close it and return that line .
16,642
private static void _transform ( Source source , Result out ) throws TransformerException { TransformerFactory factory = TransformerFactory . newInstance ( ) ; factory . setFeature ( XMLConstants . FEATURE_SECURE_PROCESSING , true ) ; Transformer t = factory . newTransformer ( ) ; t . transform ( source , out ) ; }
potentially unsafe XML transformation .
16,643
public void calcFillSettings ( String field , Map < String , Object > attributes ) { String capitalizedFieldName = StringUtils . capitalize ( field ) ; String methodName = "doFill" + capitalizedFieldName + "Items" ; Method method = ReflectionUtils . getPublicMethodNamed ( getClass ( ) , methodName ) ; if ( method == null ) throw new IllegalStateException ( String . format ( "%s doesn't have the %s method for filling a drop-down list" , getClass ( ) , methodName ) ) ; List < String > depends = buildFillDependencies ( method , new ArrayList < > ( ) ) ; if ( ! depends . isEmpty ( ) ) attributes . put ( "fillDependsOn" , Util . join ( depends , " " ) ) ; attributes . put ( "fillUrl" , String . format ( "%s/%s/fill%sItems" , getCurrentDescriptorByNameUrl ( ) , getDescriptorUrl ( ) , capitalizedFieldName ) ) ; }
Computes the list of other form fields that the given field depends on via the doFillXyzItems method and sets that as the fillDependsOn attribute . Also computes the URL of the doFillXyzItems and sets that as the fillUrl attribute .
16,644
public void calcAutoCompleteSettings ( String field , Map < String , Object > attributes ) { String capitalizedFieldName = StringUtils . capitalize ( field ) ; String methodName = "doAutoComplete" + capitalizedFieldName ; Method method = ReflectionUtils . getPublicMethodNamed ( getClass ( ) , methodName ) ; if ( method == null ) return ; attributes . put ( "autoCompleteUrl" , String . format ( "%s/%s/autoComplete%s" , getCurrentDescriptorByNameUrl ( ) , getDescriptorUrl ( ) , capitalizedFieldName ) ) ; }
Computes the auto - completion setting
16,645
public PropertyType getGlobalPropertyType ( String field ) { if ( globalPropertyTypes == null ) globalPropertyTypes = buildPropertyTypes ( getClass ( ) ) ; return globalPropertyTypes . get ( field ) ; }
Obtains the property type of the given field of this descriptor .
16,646
protected void addHelpFileRedirect ( String fieldName , Class < ? extends Describable > owner , String fieldNameToRedirectTo ) { helpRedirect . put ( fieldName , new HelpRedirect ( owner , fieldNameToRedirectTo ) ) ; }
Tells Jenkins that the help file for the field fieldName is defined in the help file for the fieldNameToRedirectTo in the owner class .
16,647
public static < T extends Descriptor > T findById ( Collection < ? extends T > list , String id ) { for ( T d : list ) { if ( d . getId ( ) . equals ( id ) ) return d ; } return null ; }
Finds a descriptor from a collection by its ID .
16,648
public static < T extends Descriptor > T find ( Collection < ? extends T > list , String string ) { T d = findByClassName ( list , string ) ; if ( d != null ) { return d ; } return findById ( list , string ) ; }
Finds a descriptor from a collection by its class name or ID .
16,649
private URL tryToResolveRedirects ( URL base , String authorization ) { try { HttpURLConnection con = ( HttpURLConnection ) base . openConnection ( ) ; if ( authorization != null ) { con . addRequestProperty ( "Authorization" , authorization ) ; } con . getInputStream ( ) . close ( ) ; base = con . getURL ( ) ; } catch ( Exception ex ) { LOGGER . log ( Level . FINE , "Failed to resolve potential redirects" , ex ) ; } return base ; }
As this transport mode is using POST it is necessary to resolve possible redirections using GET first .
16,650
protected final Result < T > monitorDetailed ( ) throws InterruptedException { Map < Computer , Future < T > > futures = new HashMap < > ( ) ; Set < Computer > skipped = new HashSet < > ( ) ; for ( Computer c : Jenkins . getInstance ( ) . getComputers ( ) ) { try { VirtualChannel ch = c . getChannel ( ) ; futures . put ( c , null ) ; if ( ch != null ) { Callable < T , ? > cc = createCallable ( c ) ; if ( cc != null ) futures . put ( c , ch . callAsync ( cc ) ) ; } } catch ( RuntimeException | IOException e ) { LOGGER . log ( WARNING , "Failed to monitor " + c . getDisplayName ( ) + " for " + getDisplayName ( ) , e ) ; } } final long now = System . currentTimeMillis ( ) ; final long end = now + getMonitoringTimeOut ( ) ; final Map < Computer , T > data = new HashMap < > ( ) ; for ( Entry < Computer , Future < T > > e : futures . entrySet ( ) ) { Computer c = e . getKey ( ) ; Future < T > f = futures . get ( c ) ; data . put ( c , null ) ; if ( f != null ) { try { data . put ( c , f . get ( Math . max ( 0 , end - System . currentTimeMillis ( ) ) , MILLISECONDS ) ) ; } catch ( RuntimeException | TimeoutException | ExecutionException x ) { LOGGER . log ( WARNING , "Failed to monitor " + c . getDisplayName ( ) + " for " + getDisplayName ( ) , x ) ; } } else { skipped . add ( c ) ; } } return new Result < > ( data , skipped ) ; }
Perform monitoring with detailed reporting .
16,651
private static HttpURLConnection open ( URL url ) throws IOException { HttpURLConnection c = ( HttpURLConnection ) url . openConnection ( ) ; c . setReadTimeout ( TIMEOUT ) ; c . setConnectTimeout ( TIMEOUT ) ; return c ; }
Connects to the given HTTP URL and configure time out to avoid infinite hang .
16,652
public boolean shouldDisplay ( ) throws IOException , ServletException { if ( ! Functions . hasPermission ( Jenkins . ADMINISTER ) ) { return false ; } StaplerRequest req = Stapler . getCurrentRequest ( ) ; if ( req == null ) { return false ; } List < Ancestor > ancestors = req . getAncestors ( ) ; if ( ancestors == null || ancestors . size ( ) == 0 ) { return false ; } Ancestor a = ancestors . get ( ancestors . size ( ) - 1 ) ; Object o = a . getObject ( ) ; if ( o instanceof HudsonIsLoading ) { return false ; } if ( o instanceof HudsonIsRestarting ) { return false ; } if ( o instanceof Jenkins ) { String url = a . getRestOfUrl ( ) ; if ( ignoredJenkinsRestOfUrls . contains ( url ) ) { return false ; } } if ( getActiveAdministrativeMonitorsCount ( ) == 0 ) { return false ; } return true ; }
Whether the administrative monitors notifier should be shown .
16,653
public static synchronized ScheduledExecutorService get ( ) { if ( executorService == null ) { executorService = new ImpersonatingScheduledExecutorService ( new ErrorLoggingScheduledThreadPoolExecutor ( 10 , new NamingThreadFactory ( new ClassLoaderSanityThreadFactory ( new DaemonThreadFactory ( ) ) , "jenkins.util.Timer" ) ) , ACL . SYSTEM ) ; } return executorService ; }
Returns the scheduled executor service used by all timed tasks in Jenkins .
16,654
protected void onUnsuccessfulAuthentication ( HttpServletRequest request , HttpServletResponse response , AuthenticationException failed ) throws IOException { super . onUnsuccessfulAuthentication ( request , response , failed ) ; LOGGER . log ( Level . FINE , "Login attempt failed" , failed ) ; Authentication auth = failed . getAuthentication ( ) ; if ( auth != null ) { SecurityListener . fireFailedToLogIn ( auth . getName ( ) ) ; } }
Leave the information about login failure .
16,655
public static boolean hasFilter ( Filter filter ) { Jenkins j = Jenkins . getInstanceOrNull ( ) ; PluginServletFilter container = null ; if ( j != null ) { container = getInstance ( j . servletContext ) ; } if ( j == null || container == null ) { return LEGACY . contains ( filter ) ; } else { return container . list . contains ( filter ) ; } }
Checks whether the given filter is already registered in the chain .
16,656
protected void updateComputerList ( final boolean automaticSlaveLaunch ) { final Map < Node , Computer > computers = getComputerMap ( ) ; final Set < Computer > old = new HashSet < Computer > ( computers . size ( ) ) ; Queue . withLock ( new Runnable ( ) { public void run ( ) { Map < String , Computer > byName = new HashMap < String , Computer > ( ) ; for ( Computer c : computers . values ( ) ) { old . add ( c ) ; Node node = c . getNode ( ) ; if ( node == null ) continue ; byName . put ( node . getNodeName ( ) , c ) ; } Set < Computer > used = new HashSet < > ( old . size ( ) ) ; updateComputer ( AbstractCIBase . this , byName , used , automaticSlaveLaunch ) ; for ( Node s : getNodes ( ) ) { long start = System . currentTimeMillis ( ) ; updateComputer ( s , byName , used , automaticSlaveLaunch ) ; if ( LOG_STARTUP_PERFORMANCE && LOGGER . isLoggable ( Level . FINE ) ) { LOGGER . fine ( String . format ( "Took %dms to update node %s" , System . currentTimeMillis ( ) - start , s . getNodeName ( ) ) ) ; } } old . removeAll ( used ) ; for ( Computer c : old ) { c . inflictMortalWound ( ) ; } } } ) ; for ( Computer c : old ) { killComputer ( c ) ; } getQueue ( ) . scheduleMaintenance ( ) ; for ( ComputerListener cl : ComputerListener . all ( ) ) { try { cl . onConfigurationChange ( ) ; } catch ( Throwable t ) { LOGGER . log ( Level . WARNING , null , t ) ; } } }
Updates Computers .
16,657
public static FormValidation error ( Throwable e , String message ) { return _error ( Kind . ERROR , e , message ) ; }
Sends out a string error message with optional show details link that expands to the full stack trace .
16,658
public static FormValidation validateExecutable ( String exe , FileValidator exeValidator ) { if ( ! Jenkins . getInstance ( ) . hasPermission ( Jenkins . ADMINISTER ) ) return ok ( ) ; exe = fixEmpty ( exe ) ; if ( exe == null ) return ok ( ) ; if ( exe . indexOf ( File . separatorChar ) >= 0 ) { File f = new File ( exe ) ; if ( f . exists ( ) ) return exeValidator . validate ( f ) ; File fexe = new File ( exe + ".exe" ) ; if ( fexe . exists ( ) ) return exeValidator . validate ( fexe ) ; return error ( "There's no such file: " + exe ) ; } String path = EnvVars . masterEnvVars . get ( "PATH" ) ; String tokenizedPath = "" ; String delimiter = null ; if ( path != null ) { for ( String _dir : Util . tokenize ( path . replace ( "\\" , "\\\\" ) , File . pathSeparator ) ) { if ( delimiter == null ) { delimiter = ", " ; } else { tokenizedPath += delimiter ; } tokenizedPath += _dir . replace ( '\\' , '/' ) ; File dir = new File ( _dir ) ; File f = new File ( dir , exe ) ; if ( f . exists ( ) ) return exeValidator . validate ( f ) ; File fexe = new File ( dir , exe + ".exe" ) ; if ( fexe . exists ( ) ) return exeValidator . validate ( fexe ) ; } tokenizedPath += "." ; } else { tokenizedPath = "unavailable." ; } return error ( "There's no such executable " + exe + " in PATH: " + tokenizedPath ) ; }
Makes sure that the given string points to an executable file .
16,659
public static FormValidation validateNonNegativeInteger ( String value ) { try { if ( Integer . parseInt ( value ) < 0 ) return error ( hudson . model . Messages . Hudson_NotANonNegativeNumber ( ) ) ; return ok ( ) ; } catch ( NumberFormatException e ) { return error ( hudson . model . Messages . Hudson_NotANumber ( ) ) ; } }
Makes sure that the given string is a non - negative integer .
16,660
public static FormValidation validatePositiveInteger ( String value ) { try { if ( Integer . parseInt ( value ) <= 0 ) return error ( hudson . model . Messages . Hudson_NotAPositiveNumber ( ) ) ; return ok ( ) ; } catch ( NumberFormatException e ) { return error ( hudson . model . Messages . Hudson_NotANumber ( ) ) ; } }
Makes sure that the given string is a positive integer .
16,661
public static FormValidation validateRequired ( String value ) { if ( Util . fixEmptyAndTrim ( value ) == null ) return error ( Messages . FormValidation_ValidateRequired ( ) ) ; return ok ( ) ; }
Makes sure that the given string is not null or empty .
16,662
public static FormValidation validateBase64 ( String value , boolean allowWhitespace , boolean allowEmpty , String errorMessage ) { try { String v = value ; if ( ! allowWhitespace ) { if ( v . indexOf ( ' ' ) >= 0 || v . indexOf ( '\n' ) >= 0 ) return error ( errorMessage ) ; } v = v . trim ( ) ; if ( ! allowEmpty && v . length ( ) == 0 ) return error ( errorMessage ) ; Base64 . getDecoder ( ) . decode ( v . getBytes ( StandardCharsets . UTF_8 ) ) ; return ok ( ) ; } catch ( IllegalArgumentException e ) { return error ( errorMessage ) ; } }
Makes sure that the given string is a base64 encoded text .
16,663
public synchronized byte [ ] mac ( byte [ ] message ) { ConfidentialStore cs = ConfidentialStore . get ( ) ; if ( mac == null || cs != lastCS ) { lastCS = cs ; mac = createMac ( ) ; } return chop ( mac . doFinal ( message ) ) ; }
Computes the message authentication code for the specified byte sequence .
16,664
public String mac ( String message ) { return Util . toHexString ( mac ( message . getBytes ( StandardCharsets . UTF_8 ) ) ) ; }
Computes the message authentication code and return it as a string . While redundant often convenient .
16,665
public < U extends T > List < U > getAll ( Class < U > type ) { List < U > r = new ArrayList < > ( ) ; for ( T t : data ) if ( type . isInstance ( t ) ) r . add ( type . cast ( t ) ) ; return r ; }
Gets all instances that matches the given type .
16,666
public void remove ( Class < ? extends T > type ) throws IOException { for ( T t : data ) { if ( t . getClass ( ) == type ) { data . remove ( t ) ; onModified ( ) ; return ; } } }
Removes an instance by its type .
16,667
public void replace ( T from , T to ) throws IOException { List < T > copy = new ArrayList < > ( data . getView ( ) ) ; for ( int i = 0 ; i < copy . size ( ) ; i ++ ) { if ( copy . get ( i ) . equals ( from ) ) copy . set ( i , to ) ; } data . replaceBy ( copy ) ; }
A convenience method to replace a single item .
16,668
private RunList < R > limit ( final CountingPredicate < R > predicate ) { size = null ; first = null ; final Iterable < R > nested = base ; base = new Iterable < R > ( ) { public Iterator < R > iterator ( ) { return hudson . util . Iterators . limit ( nested . iterator ( ) , predicate ) ; } public String toString ( ) { return Iterables . toString ( this ) ; } } ; return this ; }
Returns the first streak of the elements that satisfy the given predicate .
16,669
public RunList < R > byTimestamp ( final long start , final long end ) { return limit ( new CountingPredicate < R > ( ) { public boolean apply ( int index , R r ) { return start <= r . getTimeInMillis ( ) ; } } ) . filter ( new Predicate < R > ( ) { public boolean apply ( R r ) { return r . getTimeInMillis ( ) < end ; } } ) ; }
Filter the list by timestamp .
16,670
public void rewriteHudsonWar ( File by ) throws IOException { File dest = getHudsonWar ( ) ; if ( dest == null ) throw new IOException ( "jenkins.war location is not known." ) ; File bak = new File ( dest . getPath ( ) + ".bak" ) ; if ( ! by . equals ( bak ) ) FileUtils . copyFile ( dest , bak ) ; String baseName = dest . getName ( ) ; baseName = baseName . substring ( 0 , baseName . indexOf ( '.' ) ) ; File baseDir = getBaseDir ( ) ; File copyFiles = new File ( baseDir , baseName + ".copies" ) ; try ( FileWriter w = new FileWriter ( copyFiles , true ) ) { w . write ( by . getAbsolutePath ( ) + '>' + getHudsonWar ( ) . getAbsolutePath ( ) + '\n' ) ; } }
On Windows jenkins . war is locked so we place a new version under a special name which is picked up by the service wrapper upon restart .
16,671
public static boolean isAllReady ( ) throws IOException , InterruptedException { for ( RestartListener listener : all ( ) ) { if ( ! listener . isReadyToRestart ( ) ) return false ; } return true ; }
Returns true iff all the listeners OKed the restart .
16,672
protected boolean isIgnoredDir ( File dir ) { String n = dir . getName ( ) ; return n . equals ( "workspace" ) || n . equals ( "artifacts" ) || n . equals ( "plugins" ) || n . equals ( "." ) || n . equals ( ".." ) ; }
Decides if this directory is worth visiting or not .
16,673
public long skip ( long n ) throws IOException { byte [ ] buf = new byte [ ( int ) Math . min ( n , 64 * 1024 ) ] ; return read ( buf , 0 , buf . length ) ; }
To record the bytes we ve skipped convert the call to read .
16,674
public static List < ComputerPanelBox > all ( Computer computer ) { List < ComputerPanelBox > boxs = new ArrayList < > ( ) ; for ( ComputerPanelBox box : ExtensionList . lookup ( ComputerPanelBox . class ) ) { box . setComputer ( computer ) ; boxs . add ( box ) ; } return boxs ; }
Create boxes for the given computer in its page .
16,675
public static String [ ] internInPlace ( String [ ] input ) { if ( input == null ) { return null ; } else if ( input . length == 0 ) { return EMPTY_STRING_ARRAY ; } for ( int i = 0 ; i < input . length ; i ++ ) { input [ i ] = Util . intern ( input [ i ] ) ; } return input ; }
Returns the input strings but with all values interned .
16,676
public boolean pollChanges ( AbstractProject < ? , ? > project , Launcher launcher , FilePath workspace , TaskListener listener ) throws IOException , InterruptedException { throw new AbstractMethodError ( "you must override compareRemoteRevisionWith" ) ; }
Checks if there has been any changes to this module in the repository .
16,677
public final PollingResult poll ( AbstractProject < ? , ? > project , Launcher launcher , FilePath workspace , TaskListener listener , SCMRevisionState baseline ) throws IOException , InterruptedException { if ( is1_346OrLater ( ) ) { SCMRevisionState baseline2 ; if ( baseline != SCMRevisionState . NONE ) { baseline2 = baseline ; } else { baseline2 = calcRevisionsFromBuild ( project . getLastBuild ( ) , launcher , listener ) ; } return compareRemoteRevisionWith ( project , launcher , workspace , listener , baseline2 ) ; } else { return pollChanges ( project , launcher , workspace , listener ) ? PollingResult . SIGNIFICANT : PollingResult . NO_CHANGES ; } }
Convenience method for the caller to handle the backward compatibility between pre 1 . 345 SCMs .
16,678
public FilePath [ ] getModuleRoots ( FilePath workspace , AbstractBuild build ) { if ( Util . isOverridden ( SCM . class , getClass ( ) , "getModuleRoots" , FilePath . class ) ) return getModuleRoots ( workspace ) ; return new FilePath [ ] { getModuleRoot ( workspace , build ) } ; }
Gets the top directories of all the checked out modules .
16,679
public static List < SCMDescriptor < ? > > _for ( final Job project ) { if ( project == null ) return all ( ) ; final Descriptor pd = Jenkins . getInstance ( ) . getDescriptor ( ( Class ) project . getClass ( ) ) ; List < SCMDescriptor < ? > > r = new ArrayList < SCMDescriptor < ? > > ( ) ; for ( SCMDescriptor < ? > scmDescriptor : all ( ) ) { if ( ! scmDescriptor . isApplicable ( project ) ) continue ; if ( pd instanceof TopLevelItemDescriptor ) { TopLevelItemDescriptor apd = ( TopLevelItemDescriptor ) pd ; if ( ! apd . isApplicable ( scmDescriptor ) ) continue ; } r . add ( scmDescriptor ) ; } return r ; }
Determines which kinds of SCMs are applicable to a given project .
16,680
private boolean hasPermissionToSeeToken ( ) { if ( SHOW_LEGACY_TOKEN_TO_ADMINS && Jenkins . get ( ) . hasPermission ( Jenkins . ADMINISTER ) ) { return true ; } User current = User . current ( ) ; if ( current == null ) { return false ; } if ( Jenkins . getAuthentication ( ) == ACL . SYSTEM ) { return true ; } return User . idStrategy ( ) . equals ( user . getId ( ) , current . getId ( ) ) ; }
Only for legacy token
16,681
@ Restricted ( NoExternalUse . class ) public Collection < TokenInfoAndStats > getTokenList ( ) { return tokenStore . getTokenListSortedByName ( ) . stream ( ) . map ( token -> { ApiTokenStats . SingleTokenStats stats = tokenStats . findTokenStatsById ( token . getUuid ( ) ) ; return new TokenInfoAndStats ( token , stats ) ; } ) . collect ( Collectors . toList ( ) ) ; }
only for Jelly
16,682
public void changeApiToken ( ) throws IOException { user . checkPermission ( Jenkins . ADMINISTER ) ; LOGGER . log ( Level . FINE , "Deprecated usage of changeApiToken" ) ; ApiTokenStore . HashedToken existingLegacyToken = tokenStore . getLegacyToken ( ) ; _changeApiToken ( ) ; tokenStore . regenerateTokenFromLegacy ( apiToken ) ; if ( existingLegacyToken != null ) { tokenStats . removeId ( existingLegacyToken . getUuid ( ) ) ; } user . save ( ) ; }
Only usable if the user still has the legacy API token .
16,683
public void run ( Action [ ] additionalActions ) { if ( job == null ) { return ; } DescriptorImpl d = getDescriptor ( ) ; LOGGER . fine ( "Scheduling a polling for " + job ) ; if ( d . synchronousPolling ) { LOGGER . fine ( "Running the trigger directly without threading, " + "as it's already taken care of by Trigger.Cron" ) ; new Runner ( additionalActions ) . run ( ) ; } else { LOGGER . fine ( "scheduling the trigger to (asynchronously) run" ) ; d . queue . execute ( new Runner ( additionalActions ) ) ; d . clogCheck ( ) ; } }
Run the SCM trigger with additional build actions . Used by SubversionRepositoryStatus to trigger a build at a specific revision number .
16,684
public static boolean execute ( AbstractBuild build , BuildListener listener ) { PrintStream logger = listener . getLogger ( ) ; final DependencyGraph graph = Jenkins . getInstance ( ) . getDependencyGraph ( ) ; List < Dependency > downstreamProjects = new ArrayList < > ( graph . getDownstreamDependencies ( build . getProject ( ) ) ) ; downstreamProjects . sort ( new Comparator < Dependency > ( ) { public int compare ( Dependency lhs , Dependency rhs ) { return graph . compare ( rhs . getDownstreamProject ( ) , lhs . getDownstreamProject ( ) ) ; } } ) ; for ( Dependency dep : downstreamProjects ) { List < Action > buildActions = new ArrayList < > ( ) ; if ( dep . shouldTriggerBuild ( build , listener , buildActions ) ) { AbstractProject p = dep . getDownstreamProject ( ) ; if ( p . isDisabled ( ) ) { logger . println ( Messages . BuildTrigger_Disabled ( ModelHyperlinkNote . encodeTo ( p ) ) ) ; continue ; } boolean scheduled = p . scheduleBuild ( p . getQuietPeriod ( ) , new UpstreamCause ( ( Run ) build ) , buildActions . toArray ( new Action [ 0 ] ) ) ; if ( Jenkins . getInstance ( ) . getItemByFullName ( p . getFullName ( ) ) == p ) { String name = ModelHyperlinkNote . encodeTo ( p ) ; if ( scheduled ) { logger . println ( Messages . BuildTrigger_Triggering ( name ) ) ; } else { logger . println ( Messages . BuildTrigger_InQueue ( name ) ) ; } } } } return true ; }
Convenience method to trigger downstream builds .
16,685
public boolean canRun ( final ResourceList resources ) { try { return _withLock ( new Callable < Boolean > ( ) { public Boolean call ( ) { return ! inUse . isCollidingWith ( resources ) ; } } ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Inner callable does not throw exception" ) ; } }
Checks if an activity that requires the given resource list can run immediately .
16,686
public Resource getMissingResource ( final ResourceList resources ) { try { return _withLock ( new Callable < Resource > ( ) { public Resource call ( ) { return resources . getConflict ( inUse ) ; } } ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Inner callable does not throw exception" ) ; } }
Of the resource in the given resource list return the one that s currently in use .
16,687
public void add ( TopLevelItem item ) throws IOException { synchronized ( this ) { jobNames . add ( item . getRelativeNameFrom ( getOwner ( ) . getItemGroup ( ) ) ) ; } save ( ) ; }
Adds the given item to this view .
16,688
public boolean remove ( TopLevelItem item ) throws IOException { synchronized ( this ) { String name = item . getRelativeNameFrom ( getOwner ( ) . getItemGroup ( ) ) ; if ( ! jobNames . remove ( name ) ) return false ; } save ( ) ; return true ; }
Removes given item from this view .
16,689
@ Restricted ( NoExternalUse . class ) @ SuppressWarnings ( "unused" ) public boolean isAddToCurrentView ( ) { synchronized ( this ) { return ! jobNames . isEmpty ( ) || ( jobFilters . isEmpty ( ) && includePattern == null ) ; } }
Determines the initial state of the checkbox .
16,690
public void onOnline ( Computer c , TaskListener listener ) throws IOException , InterruptedException { synchronized ( this ) { future . cancel ( false ) ; future = Timer . get ( ) . schedule ( MONITOR_UPDATER , 5 , TimeUnit . SECONDS ) ; } }
Triggers the update with 5 seconds quiet period to avoid triggering data check too often when multiple agents become online at about the same time .
16,691
@ Exported ( name = "labelExpression" ) public String getAssignedLabelString ( ) { if ( canRoam || assignedNode == null ) return null ; try { LabelExpression . parseExpression ( assignedNode ) ; return assignedNode ; } catch ( ANTLRException e ) { return LabelAtom . escape ( assignedNode ) ; } }
Gets the textual representation of the assigned label as it was entered by the user .
16,692
public void setAssignedLabel ( Label l ) throws IOException { if ( l == null ) { canRoam = true ; assignedNode = null ; } else { canRoam = false ; if ( l == Jenkins . getInstance ( ) . getSelfLabel ( ) ) assignedNode = null ; else assignedNode = l . getExpression ( ) ; } save ( ) ; }
Sets the assigned label .
16,693
public final FilePath getWorkspace ( ) { AbstractBuild b = getBuildForDeprecatedMethods ( ) ; return b != null ? b . getWorkspace ( ) : null ; }
Gets the directory where the module is checked out .
16,694
private AbstractBuild getBuildForDeprecatedMethods ( ) { Executor e = Executor . currentExecutor ( ) ; if ( e != null ) { Executable exe = e . getCurrentExecutable ( ) ; if ( exe instanceof AbstractBuild ) { AbstractBuild b = ( AbstractBuild ) exe ; if ( b . getProject ( ) == this ) return b ; } } R lb = getLastBuild ( ) ; if ( lb != null ) return lb ; return null ; }
Various deprecated methods in this class all need the current build . This method returns the build suitable for that purpose .
16,695
public final FilePath getSomeWorkspace ( ) { R b = getSomeBuildWithWorkspace ( ) ; if ( b != null ) return b . getWorkspace ( ) ; for ( WorkspaceBrowser browser : ExtensionList . lookup ( WorkspaceBrowser . class ) ) { FilePath f = browser . getWorkspace ( this ) ; if ( f != null ) return f ; } return null ; }
Gets a workspace for some build of this project .
16,696
public final R getSomeBuildWithWorkspace ( ) { int cnt = 0 ; for ( R b = getLastBuild ( ) ; cnt < 5 && b != null ; b = b . getPreviousBuild ( ) ) { FilePath ws = b . getWorkspace ( ) ; if ( ws != null ) return b ; } return null ; }
Gets some build that has a live workspace .
16,697
public boolean scheduleBuild ( int quietPeriod , Cause c , Action ... actions ) { return scheduleBuild2 ( quietPeriod , c , actions ) != null ; }
Schedules a build .
16,698
public boolean schedulePolling ( ) { if ( isDisabled ( ) ) return false ; SCMTrigger scmt = getTrigger ( SCMTrigger . class ) ; if ( scmt == null ) return false ; scmt . run ( ) ; return true ; }
Schedules a polling of this project .
16,699
public ResourceList getResourceList ( ) { final Set < ResourceActivity > resourceActivities = getResourceActivities ( ) ; final List < ResourceList > resourceLists = new ArrayList < ResourceList > ( 1 + resourceActivities . size ( ) ) ; for ( ResourceActivity activity : resourceActivities ) { if ( activity != this && activity != null ) { resourceLists . add ( activity . getResourceList ( ) ) ; } } return ResourceList . union ( resourceLists ) ; }
List of necessary resources to perform the build of this project .