idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
16,900
@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public Map < JobPropertyDescriptor , JobProperty < ? super JobT > > getProperties ( ) { Map result = Descriptor . toMap ( ( Iterable ) properties ) ; if ( logRotator != null ) { result . put ( Jenkins . getActiveInstance ( ) . getDescriptorByType ( BuildDiscarderProperty . DescriptorImpl . class ) , new BuildDiscarderProperty ( logRotator ) ) ; } return result ; }
Gets all the job properties configured for this job .
16,901
public < T extends JobProperty > T getProperty ( Class < T > clazz ) { if ( clazz == BuildDiscarderProperty . class && logRotator != null ) { return clazz . cast ( new BuildDiscarderProperty ( logRotator ) ) ; } return _getProperty ( clazz ) ; }
Gets the specific property or null if the property is not configured for this job .
16,902
public Collection < ? > getOverrides ( ) { List < Object > r = new ArrayList < > ( ) ; for ( JobProperty < ? super JobT > p : properties ) r . addAll ( p . getJobOverrides ( ) ) ; return r ; }
Overrides from job properties .
16,903
public void renameTo ( String newName ) throws IOException { File oldBuildDir = getBuildDir ( ) ; super . renameTo ( newName ) ; File newBuildDir = getBuildDir ( ) ; if ( oldBuildDir . isDirectory ( ) && ! newBuildDir . isDirectory ( ) ) { if ( ! newBuildDir . getParentFile ( ) . isDirectory ( ) ) { newBuildDir . getParentFile ( ) . mkdirs ( ) ; } if ( ! oldBuildDir . renameTo ( newBuildDir ) ) { throw new IOException ( "failed to rename " + oldBuildDir + " to " + newBuildDir ) ; } } }
Renames a job .
16,904
@ Exported ( name = "allBuilds" , visibility = - 2 ) @ WithBridgeMethods ( List . class ) public RunList < RunT > getBuilds ( ) { return RunList . < RunT > fromRuns ( _getRuns ( ) . values ( ) ) ; }
Gets the read - only view of all the builds .
16,905
public RunT getBuild ( String id ) { for ( RunT r : _getRuns ( ) . values ( ) ) { if ( r . getId ( ) . equals ( id ) ) return r ; } return null ; }
Looks up a build by its ID .
16,906
@ WithBridgeMethods ( List . class ) public RunList < RunT > getBuildsByTimestamp ( long start , long end ) { return getBuilds ( ) . byTimestamp ( start , end ) ; }
Obtains a list of builds in the descending order that are within the specified time range [ start end ) .
16,907
public RunT getLastCompletedBuild ( ) { RunT r = getLastBuild ( ) ; while ( r != null && r . isBuilding ( ) ) r = r . getPreviousBuild ( ) ; return r ; }
Returns the last completed build if any . Otherwise null .
16,908
@ SuppressWarnings ( "unchecked" ) protected List < RunT > getEstimatedDurationCandidates ( ) { List < RunT > candidates = new ArrayList < > ( 3 ) ; RunT lastSuccessful = getLastSuccessfulBuild ( ) ; int lastSuccessfulNumber = - 1 ; if ( lastSuccessful != null ) { candidates . add ( lastSuccessful ) ; lastSuccessfulNumber = lastSuccessful . getNumber ( ) ; } int i = 0 ; RunT r = getLastBuild ( ) ; List < RunT > fallbackCandidates = new ArrayList < > ( 3 ) ; while ( r != null && candidates . size ( ) < 3 && i < 6 ) { if ( ! r . isBuilding ( ) && r . getResult ( ) != null && r . getNumber ( ) != lastSuccessfulNumber ) { Result result = r . getResult ( ) ; if ( result . isBetterOrEqualTo ( Result . UNSTABLE ) ) { candidates . add ( r ) ; } else if ( result . isCompleteBuild ( ) ) { fallbackCandidates . add ( r ) ; } } i ++ ; r = r . getPreviousBuild ( ) ; } while ( candidates . size ( ) < 3 ) { if ( fallbackCandidates . isEmpty ( ) ) break ; RunT run = fallbackCandidates . remove ( 0 ) ; candidates . add ( run ) ; } return candidates ; }
Returns candidate build for calculating the estimated duration of the current run .
16,909
public void doRssChangelog ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { class FeedItem { ChangeLogSet . Entry e ; int idx ; public FeedItem ( ChangeLogSet . Entry e , int idx ) { this . e = e ; this . idx = idx ; } Run < ? , ? > getBuild ( ) { return e . getParent ( ) . build ; } } List < FeedItem > entries = new ArrayList < > ( ) ; String scmDisplayName = "" ; if ( this instanceof SCMTriggerItem ) { SCMTriggerItem scmItem = ( SCMTriggerItem ) this ; List < String > scmNames = new ArrayList < > ( ) ; for ( SCM s : scmItem . getSCMs ( ) ) { scmNames . add ( s . getDescriptor ( ) . getDisplayName ( ) ) ; } scmDisplayName = " " + Util . join ( scmNames , ", " ) ; } for ( RunT r = getLastBuild ( ) ; r != null ; r = r . getPreviousBuild ( ) ) { int idx = 0 ; if ( r instanceof RunWithSCM ) { for ( ChangeLogSet < ? extends ChangeLogSet . Entry > c : ( ( RunWithSCM < ? , ? > ) r ) . getChangeSets ( ) ) { for ( ChangeLogSet . Entry e : c ) { entries . add ( new FeedItem ( e , idx ++ ) ) ; } } } } RSS . forwardToRss ( getDisplayName ( ) + scmDisplayName + " changes" , getUrl ( ) + "changes" , entries , new FeedAdapter < FeedItem > ( ) { public String getEntryTitle ( FeedItem item ) { return "#" + item . getBuild ( ) . number + ' ' + item . e . getMsg ( ) + " (" + item . e . getAuthor ( ) + ")" ; } public String getEntryUrl ( FeedItem item ) { return item . getBuild ( ) . getUrl ( ) + "changes#detail" + item . idx ; } public String getEntryID ( FeedItem item ) { return getEntryUrl ( item ) ; } public String getEntryDescription ( FeedItem item ) { StringBuilder buf = new StringBuilder ( ) ; for ( String path : item . e . getAffectedPaths ( ) ) buf . append ( path ) . append ( '\n' ) ; return buf . toString ( ) ; } public Calendar getEntryTimestamp ( FeedItem item ) { return item . getBuild ( ) . getTimestamp ( ) ; } public String getEntryAuthor ( FeedItem entry ) { return JenkinsLocationConfiguration . get ( ) . getAdminAddress ( ) ; } } , req , rsp ) ; }
RSS feed for changes in this project .
16,910
@ Exported ( visibility = 2 , name = "color" ) public BallColor getIconColor ( ) { RunT lastBuild = getLastBuild ( ) ; while ( lastBuild != null && lastBuild . hasntStartedYet ( ) ) lastBuild = lastBuild . getPreviousBuild ( ) ; if ( lastBuild != null ) return lastBuild . getIconColor ( ) ; else return BallColor . NOTBUILT ; }
Used as the color of the status ball for the project .
16,911
public HealthReport getBuildHealth ( ) { List < HealthReport > reports = getBuildHealthReports ( ) ; return reports . isEmpty ( ) ? new HealthReport ( ) : reports . get ( 0 ) ; }
Get the current health report for a job .
16,912
public void doDescription ( StaplerRequest req , StaplerResponse rsp ) throws IOException { if ( req . getMethod ( ) . equals ( "GET" ) ) { rsp . setContentType ( "text/plain;charset=UTF-8" ) ; rsp . getWriter ( ) . write ( Util . fixNull ( this . getDescription ( ) ) ) ; return ; } if ( req . getMethod ( ) . equals ( "POST" ) ) { checkPermission ( CONFIGURE ) ; if ( req . getParameter ( "description" ) != null ) { this . setDescription ( req . getParameter ( "description" ) ) ; rsp . sendError ( SC_NO_CONTENT ) ; return ; } } rsp . sendError ( SC_BAD_REQUEST ) ; }
Accepts and serves the job description
16,913
public void doBuildStatus ( StaplerRequest req , StaplerResponse rsp ) throws IOException { rsp . sendRedirect2 ( req . getContextPath ( ) + "/images/48x48/" + getBuildStatusUrl ( ) ) ; }
Returns the image that shows the current buildCommand status .
16,914
public void doDoRename ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { String newName = req . getParameter ( "newName" ) ; doConfirmRename ( newName ) . generateResponse ( req , rsp , null ) ; }
Renames this job .
16,915
public List < Item > getQueuedItems ( ) { LinkedList < Item > list = new LinkedList < > ( ) ; for ( Item item : Jenkins . getInstance ( ) . getQueue ( ) . getItems ( ) ) { if ( item . task == owner ) { list . addFirst ( item ) ; } } return list ; }
Returns the queue item if the owner is scheduled for execution in the queue in REVERSE ORDER
16,916
public List < String > get_slaveNames ( ) { return new AbstractList < String > ( ) { final List < Node > nodes = Jenkins . getInstance ( ) . getNodes ( ) ; public String get ( int index ) { return nodes . get ( index ) . getNodeName ( ) ; } public int size ( ) { return nodes . size ( ) ; } } ; }
Gets all the agent names .
16,917
public void doUpdateNow ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { Jenkins . getInstance ( ) . checkPermission ( Jenkins . ADMINISTER ) ; for ( NodeMonitor nodeMonitor : NodeMonitor . getAll ( ) ) { Thread t = nodeMonitor . triggerUpdate ( ) ; String columnCaption = nodeMonitor . getColumnCaption ( ) ; if ( columnCaption != null ) { t . setName ( columnCaption ) ; } } rsp . forwardToPreviousPage ( req ) ; }
Triggers the schedule update now .
16,918
public synchronized Permission find ( String name ) { for ( Permission p : permissions ) { if ( p . name . equals ( name ) ) return p ; } return null ; }
Finds a permission that has the given name .
16,919
public < T > T setIfNull ( Class < T > type , T instance ) { Object o = data . putIfAbsent ( type , instance ) ; if ( o != null ) return type . cast ( o ) ; return instance ; }
Overwrites the value only if the current value is null .
16,920
public boolean add ( T t ) { try { return addSync ( t ) ; } finally { if ( extensions != null ) { fireOnChangeListeners ( ) ; } } }
Write access will put the instance into a legacy store .
16,921
public T getDynamic ( String className ) { for ( T t : this ) if ( t . getClass ( ) . getName ( ) . equals ( className ) ) return t ; return null ; }
Used to bind extension to URLs by their class names .
16,922
protected List < ExtensionComponent < T > > load ( ) { LOGGER . fine ( ( ) -> String . format ( "Loading ExtensionList '%s'" , extensionType . getName ( ) ) ) ; if ( LOGGER . isLoggable ( Level . FINER ) ) { LOGGER . log ( Level . FINER , String . format ( "Loading ExtensionList '%s' from" , extensionType . getName ( ) ) , new Throwable ( "Only present for stacktrace information" ) ) ; } return jenkins . getPluginManager ( ) . getPluginStrategy ( ) . findComponents ( extensionType , hudson ) ; }
Loads all the extensions .
16,923
public UpdateCenterJob getJob ( int id ) { synchronized ( jobs ) { for ( UpdateCenterJob job : jobs ) { if ( job . id == id ) return job ; } } return null ; }
Gets a job by its ID .
16,924
@ Restricted ( DoNotUse . class ) public HttpResponse doIncompleteInstallStatus ( ) { try { Map < String , String > jobs = InstallUtil . getPersistedInstallStatus ( ) ; if ( jobs == null ) { jobs = Collections . emptyMap ( ) ; } return HttpResponses . okJSON ( jobs ) ; } catch ( Exception e ) { return HttpResponses . errorJSON ( String . format ( "ERROR: %s" , e . getMessage ( ) ) ) ; } }
Called to determine if there was an incomplete installation what the statuses of the plugins are
16,925
@ Restricted ( NoExternalUse . class ) public synchronized void persistInstallStatus ( ) { List < UpdateCenterJob > jobs = getJobs ( ) ; boolean activeInstalls = false ; for ( UpdateCenterJob job : jobs ) { if ( job instanceof InstallationJob ) { InstallationJob installationJob = ( InstallationJob ) job ; if ( ! installationJob . status . isSuccess ( ) ) { activeInstalls = true ; } } } if ( activeInstalls ) { InstallUtil . persistInstallStatus ( jobs ) ; } else { InstallUtil . clearInstallStatus ( ) ; } }
Called to persist the currently installing plugin states . This allows us to support install resume if Jenkins is restarted while plugins are being installed .
16,926
public HudsonUpgradeJob getHudsonJob ( ) { List < UpdateCenterJob > jobList = getJobs ( ) ; Collections . reverse ( jobList ) ; for ( UpdateCenterJob job : jobList ) if ( job instanceof HudsonUpgradeJob ) return ( HudsonUpgradeJob ) job ; return null ; }
Returns latest Jenkins upgrade job .
16,927
public void doUpgrade ( StaplerResponse rsp ) throws IOException , ServletException { HudsonUpgradeJob job = new HudsonUpgradeJob ( getCoreSource ( ) , Jenkins . getAuthentication ( ) ) ; if ( ! Lifecycle . get ( ) . canRewriteHudsonWar ( ) ) { sendError ( "Jenkins upgrade not supported in this running mode" ) ; return ; } LOGGER . info ( "Scheduling the core upgrade" ) ; addJob ( job ) ; rsp . sendRedirect2 ( "." ) ; }
Schedules a Jenkins upgrade .
16,928
public HttpResponse doInvalidateData ( ) { for ( UpdateSite site : sites ) { site . doInvalidateData ( ) ; } return HttpResponses . ok ( ) ; }
Invalidates the update center JSON data for all the sites and force re - retrieval .
16,929
public void doSafeRestart ( StaplerRequest request , StaplerResponse response ) throws IOException , ServletException { synchronized ( jobs ) { if ( ! isRestartScheduled ( ) ) { addJob ( new RestartJenkinsJob ( getCoreSource ( ) ) ) ; LOGGER . info ( "Scheduling Jenkins reboot" ) ; } } response . sendRedirect2 ( "." ) ; }
Schedules a Jenkins restart .
16,930
public void doCancelRestart ( StaplerResponse response ) throws IOException , ServletException { synchronized ( jobs ) { for ( UpdateCenterJob job : jobs ) { if ( job instanceof RestartJenkinsJob ) { if ( ( ( RestartJenkinsJob ) job ) . cancel ( ) ) { LOGGER . info ( "Scheduled Jenkins reboot unscheduled" ) ; } } } } response . sendRedirect2 ( "." ) ; }
Cancel all scheduled jenkins restarts
16,931
public String getBackupVersion ( ) { try { try ( JarFile backupWar = new JarFile ( new File ( Lifecycle . get ( ) . getHudsonWar ( ) + ".bak" ) ) ) { Attributes attrs = backupWar . getManifest ( ) . getMainAttributes ( ) ; String v = attrs . getValue ( "Jenkins-Version" ) ; if ( v == null ) v = attrs . getValue ( "Hudson-Version" ) ; return v ; } } catch ( IOException e ) { LOGGER . log ( Level . WARNING , "Failed to read backup version " , e ) ; return null ; } }
Returns String with version of backup . war file if the file does not exists returns null
16,932
protected void renameTo ( final String newName ) throws IOException { final ItemGroup parent = getParent ( ) ; String oldName = this . name ; String oldFullName = getFullName ( ) ; synchronized ( parent ) { synchronized ( this ) { if ( newName == null ) throw new IllegalArgumentException ( "New name is not given" ) ; if ( this . name . equals ( newName ) ) return ; Items . verifyItemDoesNotAlreadyExist ( parent , newName , this ) ; File oldRoot = this . getRootDir ( ) ; doSetName ( newName ) ; File newRoot = this . getRootDir ( ) ; boolean success = false ; try { boolean interrupted = false ; boolean renamed = false ; for ( int retry = 0 ; retry < 5 ; retry ++ ) { if ( oldRoot . renameTo ( newRoot ) ) { renamed = true ; break ; } try { Thread . sleep ( 500 ) ; } catch ( InterruptedException e ) { interrupted = true ; } } if ( interrupted ) Thread . currentThread ( ) . interrupt ( ) ; if ( ! renamed ) { Copy cp = new Copy ( ) ; cp . setProject ( new org . apache . tools . ant . Project ( ) ) ; cp . setTodir ( newRoot ) ; FileSet src = new FileSet ( ) ; src . setDir ( oldRoot ) ; cp . addFileset ( src ) ; cp . setOverwrite ( true ) ; cp . setPreserveLastModified ( true ) ; cp . setFailOnError ( false ) ; cp . execute ( ) ; try { Util . deleteRecursive ( oldRoot ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } success = true ; } finally { if ( ! success ) doSetName ( oldName ) ; } parent . onRenamed ( this , oldName , newName ) ; } } ItemListener . fireLocationChange ( this , oldFullName ) ; }
Renames this item . Not all the Items need to support this operation but if you decide to do so you can use this method .
16,933
public void updateByXml ( Source source ) throws IOException { checkPermission ( CONFIGURE ) ; XmlFile configXmlFile = getConfigFile ( ) ; final AtomicFileWriter out = new AtomicFileWriter ( configXmlFile . getFile ( ) ) ; try { try { XMLUtils . safeTransform ( source , new StreamResult ( out ) ) ; out . close ( ) ; } catch ( TransformerException | SAXException e ) { throw new IOException ( "Failed to persist config.xml" , e ) ; } Object o = new XmlFile ( Items . XSTREAM , out . getTemporaryFile ( ) ) . unmarshalNullingOut ( this ) ; if ( o != this ) { throw new IOException ( "Expecting " + this . getClass ( ) + " but got " + o . getClass ( ) + " instead" ) ; } Items . whileUpdatingByXml ( new NotReallyRoleSensitiveCallable < Void , IOException > ( ) { public Void call ( ) throws IOException { onLoad ( getParent ( ) , getRootDir ( ) . getName ( ) ) ; return null ; } } ) ; Jenkins . getInstance ( ) . rebuildDependencyGraphAsync ( ) ; out . commit ( ) ; SaveableListener . fireOnChange ( this , getConfigFile ( ) ) ; } finally { out . abort ( ) ; } }
Updates an Item by its XML definition .
16,934
public void doReload ( ) throws IOException { checkPermission ( CONFIGURE ) ; getConfigFile ( ) . unmarshal ( this ) ; Items . whileUpdatingByXml ( new NotReallyRoleSensitiveCallable < Void , IOException > ( ) { public Void call ( ) throws IOException { onLoad ( getParent ( ) , getRootDir ( ) . getName ( ) ) ; return null ; } } ) ; Jenkins . getInstance ( ) . rebuildDependencyGraphAsync ( ) ; SaveableListener . fireOnChange ( this , getConfigFile ( ) ) ; }
Reloads this job from the disk .
16,935
@ Restricted ( NoExternalUse . class ) public boolean isUrlNull ( ) { JenkinsLocationConfiguration loc = JenkinsLocationConfiguration . get ( ) ; return loc . getUrl ( ) == null ; }
used by jelly to determined if it s a null url or invalid one
16,936
public Collection < ? extends Action > createFor ( Run target ) { if ( target instanceof AbstractBuild ) return createFor ( ( AbstractBuild ) target ) ; else return Collections . emptyList ( ) ; }
Creates actions for the given build .
16,937
public List < Action > getActions ( ) { if ( actions == null ) { synchronized ( this ) { if ( actions == null ) { actions = new CopyOnWriteArrayList < > ( ) ; } } } return actions ; }
Gets actions contributed to this object .
16,938
public < T extends Action > List < T > getActions ( Class < T > type ) { List < T > _actions = Util . filter ( getActions ( ) , type ) ; for ( TransientActionFactory < ? > taf : TransientActionFactory . factoriesFor ( getClass ( ) , type ) ) { _actions . addAll ( Util . filter ( createFor ( taf ) , type ) ) ; } return Collections . unmodifiableList ( _actions ) ; }
Gets all actions of a specified type that contributed to this object .
16,939
private void closeChannel ( ) { Channel c ; synchronized ( channelLock ) { c = channel ; channel = null ; absoluteRemoteFs = null ; isUnix = null ; } if ( c != null ) { try { c . close ( ) ; } catch ( IOException e ) { logger . log ( Level . SEVERE , "Failed to terminate channel to " + getDisplayName ( ) , e ) ; } for ( ComputerListener cl : ComputerListener . all ( ) ) cl . onOffline ( this , offlineCause ) ; } }
If still connected disconnect .
16,940
public static String convertEOL ( String input , EOLType type ) { if ( null == input || 0 == input . length ( ) ) { return input ; } input = input . replace ( "\r\n" , "\n" ) ; input = input . replace ( "\r" , "\n" ) ; switch ( type ) { case CR : case Mac : input = input . replace ( "\n" , "\r" ) ; break ; case CRLF : case Windows : input = input . replace ( "\n" , "\r\n" ) ; break ; default : case LF : case Unix : return input ; case LFCR : input = input . replace ( "\n" , "\n\r" ) ; break ; } return input ; }
Convert line endings of a string to the given type . Default to Unix type .
16,941
public Slave getSlave ( String name ) { Node n = getNode ( name ) ; if ( n instanceof Slave ) return ( Slave ) n ; return null ; }
Gets the agent of the give name hooked under this Hudson .
16,942
public void writeObject ( Object o ) throws IOException { ObjectOutputStream oos = AnonymousClassWarnings . checkingObjectOutputStream ( out ) ; oos . writeObject ( o ) ; }
Sends a serializable object .
16,943
public Connection encryptConnection ( SecretKey sessionKey , String algorithm ) throws IOException , GeneralSecurityException { Cipher cout = Cipher . getInstance ( algorithm ) ; cout . init ( Cipher . ENCRYPT_MODE , sessionKey , new IvParameterSpec ( sessionKey . getEncoded ( ) ) ) ; CipherOutputStream o = new CipherOutputStream ( out , cout ) ; Cipher cin = Cipher . getInstance ( algorithm ) ; cin . init ( Cipher . DECRYPT_MODE , sessionKey , new IvParameterSpec ( sessionKey . getEncoded ( ) ) ) ; CipherInputStream i = new CipherInputStream ( in , cin ) ; return new Connection ( i , o ) ; }
Upgrades a connection with transport encryption by the specified symmetric cipher .
16,944
public static byte [ ] fold ( byte [ ] bytes , int size ) { byte [ ] r = new byte [ size ] ; for ( int i = Math . max ( bytes . length , size ) - 1 ; i >= 0 ; i -- ) { r [ i % r . length ] ^= bytes [ i % bytes . length ] ; } return r ; }
Given a byte array that contains arbitrary number of bytes digests or expands those bits into the specified number of bytes without loss of entropy .
16,945
public PublicKey verifyIdentity ( byte [ ] sharedSecret ) throws IOException , GeneralSecurityException { try { String serverKeyAlgorithm = readUTF ( ) ; PublicKey spk = KeyFactory . getInstance ( serverKeyAlgorithm ) . generatePublic ( readKey ( ) ) ; Signature sig = Signature . getInstance ( "SHA1with" + serverKeyAlgorithm ) ; sig . initVerify ( spk ) ; sig . update ( spk . getEncoded ( ) ) ; sig . update ( sharedSecret ) ; sig . verify ( ( byte [ ] ) readObject ( ) ) ; return spk ; } catch ( ClassNotFoundException e ) { throw new Error ( e ) ; } }
Verifies that we are talking to a peer that actually owns the private key corresponding to the public key we get .
16,946
public String getTimestampString ( ) { long duration = System . currentTimeMillis ( ) - timestamp . getTime ( ) ; return Util . getPastTimeString ( duration ) ; }
Gets the string that says how long since this build has scheduled .
16,947
public RangeSet getRangeSet ( String jobFullName ) { RangeSet r = usages . get ( jobFullName ) ; if ( r == null ) r = new RangeSet ( ) ; return r ; }
Gets the build range set for the given job name .
16,948
public List < String > getJobs ( ) { List < String > r = new ArrayList < > ( ) ; r . addAll ( usages . keySet ( ) ) ; Collections . sort ( r ) ; return r ; }
Gets the sorted list of job names where this jar is used .
16,949
@ Exported ( name = "usage" ) public List < RangeItem > _getUsages ( ) { List < RangeItem > r = new ArrayList < > ( ) ; final Jenkins instance = Jenkins . getInstance ( ) ; for ( Entry < String , RangeSet > e : usages . entrySet ( ) ) { final String itemName = e . getKey ( ) ; if ( instance . hasPermission ( Jenkins . ADMINISTER ) || canDiscoverItem ( itemName ) ) { r . add ( new RangeItem ( itemName , e . getValue ( ) ) ) ; } } return r ; }
this is for remote API
16,950
public synchronized boolean isAlive ( ) { if ( original != null && original . isAlive ( ) ) return true ; for ( Entry < String , RangeSet > e : usages . entrySet ( ) ) { Job j = Jenkins . getInstance ( ) . getItemByFullName ( e . getKey ( ) , Job . class ) ; if ( j == null ) continue ; Run firstBuild = j . getFirstBuild ( ) ; if ( firstBuild == null ) continue ; int oldest = firstBuild . getNumber ( ) ; if ( ! e . getValue ( ) . isSmallerThan ( oldest ) ) return true ; } return false ; }
Returns true if any of the builds recorded in this fingerprint is still retained .
16,951
public synchronized boolean trim ( ) throws IOException { boolean modified = false ; for ( Entry < String , RangeSet > e : new Hashtable < > ( usages ) . entrySet ( ) ) { Job j = Jenkins . getInstance ( ) . getItemByFullName ( e . getKey ( ) , Job . class ) ; if ( j == null ) { modified = true ; usages . remove ( e . getKey ( ) ) ; continue ; } Run firstBuild = j . getFirstBuild ( ) ; if ( firstBuild == null ) { modified = true ; usages . remove ( e . getKey ( ) ) ; continue ; } RangeSet cur = e . getValue ( ) ; RangeSet kept = new RangeSet ( ) ; Run r = firstBuild ; while ( r != null && r . isKeepLog ( ) ) { kept . add ( r . getNumber ( ) ) ; r = r . getNextBuild ( ) ; } if ( r == null ) { modified |= cur . retainAll ( kept ) ; } else { RangeSet discarding = new RangeSet ( new Range ( - 1 , r . getNumber ( ) ) ) ; discarding . removeAll ( kept ) ; modified |= cur . removeAll ( discarding ) ; } if ( cur . isEmpty ( ) ) { usages . remove ( e . getKey ( ) ) ; modified = true ; } } if ( modified ) { if ( logger . isLoggable ( Level . FINE ) ) { logger . log ( Level . FINE , "Saving trimmed {0}" , getFingerprintFile ( md5sum ) ) ; } save ( ) ; } return modified ; }
Trim off references to non - existent builds and jobs thereby making the fingerprint smaller .
16,952
public synchronized void rename ( String oldName , String newName ) throws IOException { boolean touched = false ; if ( original != null ) { if ( original . getName ( ) . equals ( oldName ) ) { original . setName ( newName ) ; touched = true ; } } if ( usages != null ) { RangeSet r = usages . get ( oldName ) ; if ( r != null ) { usages . put ( newName , r ) ; usages . remove ( oldName ) ; touched = true ; } } if ( touched ) { save ( ) ; } }
Update references to a renamed job in the fingerprint
16,953
private static boolean canDiscoverItem ( final String fullName ) { final Jenkins jenkins = Jenkins . getInstance ( ) ; Item item = null ; try { item = jenkins . getItemByFullName ( fullName ) ; } catch ( AccessDeniedException ex ) { } if ( item != null ) { return true ; } final Authentication userAuth = Jenkins . getAuthentication ( ) ; try ( ACLContext acl = ACL . as ( ACL . SYSTEM ) ) { final Item itemBySystemUser = jenkins . getItemByFullName ( fullName ) ; if ( itemBySystemUser == null ) { return false ; } boolean canDiscoverTheItem = itemBySystemUser . hasPermission ( userAuth , Item . DISCOVER ) ; if ( canDiscoverTheItem ) { ItemGroup < ? > current = itemBySystemUser . getParent ( ) ; do { if ( current instanceof Item ) { final Item i = ( Item ) current ; current = i . getParent ( ) ; if ( ! i . hasPermission ( userAuth , Item . READ ) ) { canDiscoverTheItem = false ; } } else { current = null ; } } while ( canDiscoverTheItem && current != null ) ; } return canDiscoverTheItem ; } }
Checks if the current user can Discover the item . If yes it may be displayed as a text in Fingerprint UIs .
16,954
public void rename ( String newName ) throws Failure , FormException { if ( name . equals ( newName ) ) return ; Jenkins . checkGoodName ( newName ) ; if ( owner . getView ( newName ) != null ) throw new FormException ( Messages . Hudson_ViewAlreadyExists ( newName ) , "name" ) ; String oldName = name ; name = newName ; owner . onViewRenamed ( this , oldName , newName ) ; }
Renames this view .
16,955
public DescribableList < ViewProperty , ViewPropertyDescriptor > getProperties ( ) { synchronized ( PropertyList . class ) { if ( properties == null ) { properties = new PropertyList ( this ) ; } else { properties . setOwner ( this ) ; } return properties ; } }
Gets the view properties configured for this view .
16,956
public synchronized void doDoDelete ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { checkPermission ( DELETE ) ; owner . deleteView ( this ) ; rsp . sendRedirect2 ( req . getContextPath ( ) + "/" + owner . getUrl ( ) ) ; }
Deletes this view .
16,957
public void updateByXml ( Source source ) throws IOException { checkPermission ( CONFIGURE ) ; StringWriter out = new StringWriter ( ) ; try { XMLUtils . safeTransform ( source , new StreamResult ( out ) ) ; out . close ( ) ; } catch ( TransformerException | SAXException e ) { throw new IOException ( "Failed to persist configuration.xml" , e ) ; } try ( InputStream in = new BufferedInputStream ( new ByteArrayInputStream ( out . toString ( ) . getBytes ( StandardCharsets . UTF_8 ) ) ) ) { String oldname = name ; ViewGroup oldOwner = owner ; Object o = Jenkins . XSTREAM2 . unmarshal ( XStream2 . getDefaultDriver ( ) . createReader ( in ) , this , null , true ) ; if ( ! o . getClass ( ) . equals ( getClass ( ) ) ) { throw new IOException ( "Expecting view type: " + this . getClass ( ) + " but got: " + o . getClass ( ) + " instead." + "\nShould you needed to change to a new view type, you must first delete and then re-create " + "the view with the new view type." ) ; } name = oldname ; owner = oldOwner ; } catch ( StreamException | ConversionException | Error e ) { throw new IOException ( "Unable to read" , e ) ; } save ( ) ; }
Updates the View with the new XML definition .
16,958
public static View createViewFromXML ( String name , InputStream xml ) throws IOException { try ( InputStream in = new BufferedInputStream ( xml ) ) { View v = ( View ) Jenkins . XSTREAM . fromXML ( in ) ; if ( name != null ) v . name = name ; Jenkins . checkGoodName ( v . name ) ; return v ; } catch ( StreamException | ConversionException | Error e ) { throw new IOException ( "Unable to read" , e ) ; } }
Instantiate View subtype from XML stream .
16,959
protected boolean isUpToDate ( FilePath expectedLocation , Installable i ) throws IOException , InterruptedException { FilePath marker = expectedLocation . child ( ".installedFrom" ) ; return marker . exists ( ) && marker . readToString ( ) . equals ( i . url ) ; }
Checks if the specified expected location already contains the installed version of the tool .
16,960
protected FilePath findPullUpDirectory ( FilePath root ) throws IOException , InterruptedException { List < FilePath > children = root . list ( ) ; if ( children . size ( ) != 1 ) return null ; if ( children . get ( 0 ) . isDirectory ( ) ) return children . get ( 0 ) ; return null ; }
Often an archive contains an extra top - level directory that s unnecessary when extracted on the disk into the expected location . If your installation sources provide that kind of archives override this method to find the real root location .
16,961
public String read ( ) throws IOException { StringWriter out = new StringWriter ( ) ; PrintWriter w = new PrintWriter ( out ) ; try ( BufferedReader in = Files . newBufferedReader ( Util . fileToPath ( file ) , StandardCharsets . UTF_8 ) ) { String line ; while ( ( line = in . readLine ( ) ) != null ) w . println ( line ) ; } catch ( Exception e ) { throw new IOException ( "Failed to fully read " + file , e ) ; } return out . toString ( ) ; }
Reads the entire contents and returns it .
16,962
public void write ( String text ) throws IOException { file . getParentFile ( ) . mkdirs ( ) ; AtomicFileWriter w = new AtomicFileWriter ( file ) ; try { w . write ( text ) ; w . commit ( ) ; } finally { w . abort ( ) ; } }
Overwrites the file by the given string .
16,963
public String head ( int numChars ) throws IOException { char [ ] buf = new char [ numChars ] ; int read = 0 ; try ( Reader r = new FileReader ( file ) ) { while ( read < numChars ) { int d = r . read ( buf , read , buf . length - read ) ; if ( d < 0 ) break ; read += d ; } return new String ( buf , 0 , read ) ; } }
Reads the first N characters or until we hit EOF .
16,964
private DefaultLdapAuthoritiesPopulator create ( ) { DefaultLdapAuthoritiesPopulator populator = new DefaultLdapAuthoritiesPopulator ( initialDirContextFactory , groupSearchBase ) ; populator . setConvertToUpperCase ( convertToUpperCase ) ; if ( defaultRole != null ) { populator . setDefaultRole ( defaultRole ) ; } populator . setGroupRoleAttribute ( groupRoleAttribute ) ; populator . setGroupSearchFilter ( groupSearchFilter ) ; populator . setRolePrefix ( rolePrefix ) ; populator . setSearchSubtree ( searchSubtree ) ; return populator ; }
Create a new DefaultLdapAuthoritiesPopulator object .
16,965
public void buildEnvironment ( Run < ? , ? > build , EnvVars env ) { env . put ( name , originalFileName ) ; }
Exposes the originalFileName as an environment variable .
16,966
public HttpResponse doAct ( StaplerRequest req ) throws ServletException , IOException { Jenkins . getInstance ( ) . checkPermission ( Jenkins . ADMINISTER ) ; if ( req . hasParameter ( "n" ) ) { disable ( true ) ; return HttpResponses . redirectViaContextPath ( "/manage" ) ; } return new HttpRedirect ( "confirm" ) ; }
Called from the management screen .
16,967
private String createZfsFileSystem ( final TaskListener listener , String rootUsername , String rootPassword ) throws IOException , InterruptedException , ZFSException { final int uid = LIBC . geteuid ( ) ; final int gid = LIBC . getegid ( ) ; passwd pwd = LIBC . getpwuid ( uid ) ; if ( pwd == null ) throw new IOException ( "Failed to obtain the current user information for " + uid ) ; final String userName = pwd . pw_name ; final File home = Jenkins . getInstance ( ) . getRootDir ( ) ; return SU . execute ( listener , rootUsername , rootPassword , new Create ( listener , home , uid , gid , userName ) ) ; }
Creates a ZFS file system to migrate the data to .
16,968
protected final void requirePOST ( ) throws ServletException { StaplerRequest req = Stapler . getCurrentRequest ( ) ; if ( req == null ) return ; String method = req . getMethod ( ) ; if ( ! method . equalsIgnoreCase ( "POST" ) ) throw new ServletException ( "Must be POST, Can't be " + method ) ; }
Convenience method to verify that the current request is a POST request .
16,969
public void reportAsHeaders ( HttpServletResponse rsp ) { rsp . addHeader ( "X-You-Are-Authenticated-As" , authentication . getName ( ) ) ; if ( REPORT_GROUP_HEADERS ) { for ( GrantedAuthority auth : authentication . getAuthorities ( ) ) { rsp . addHeader ( "X-You-Are-In-Group" , auth . getAuthority ( ) ) ; } } else { rsp . addHeader ( "X-You-Are-In-Group-Disabled" , "JENKINS-39402: use -Dhudson.security.AccessDeniedException2.REPORT_GROUP_HEADERS=true or use /whoAmI to diagnose" ) ; } rsp . addHeader ( "X-Required-Permission" , permission . getId ( ) ) ; for ( Permission p = permission . impliedBy ; p != null ; p = p . impliedBy ) { rsp . addHeader ( "X-Permission-Implied-By" , p . getId ( ) ) ; } }
Reports the details of the access failure in HTTP headers to assist diagnosis .
16,970
public static void proceedToNextStateFrom ( InstallState prior ) { InstallState next = getNextInstallState ( prior ) ; if ( next != null ) { Jenkins . getInstance ( ) . setInstallState ( next ) ; } }
Proceed to the state following the provided one
16,971
public static String getLastExecVersion ( ) { File lastExecVersionFile = getLastExecVersionFile ( ) ; if ( lastExecVersionFile . exists ( ) ) { try { String version = FileUtils . readFileToString ( lastExecVersionFile ) ; if ( StringUtils . isBlank ( version ) ) { return FORCE_NEW_INSTALL_VERSION . toString ( ) ; } return version ; } catch ( IOException e ) { LOGGER . log ( SEVERE , "Unexpected Error. Unable to read " + lastExecVersionFile . getAbsolutePath ( ) , e ) ; LOGGER . log ( WARNING , "Unable to determine the last running version (see error above). Treating this as a restart. No plugins will be updated." ) ; return getCurrentExecVersion ( ) ; } } else { File configFile = getConfigFile ( ) ; if ( configFile . exists ( ) ) { try { String lastVersion = XMLUtils . getValue ( "/hudson/version" , configFile ) ; if ( lastVersion . length ( ) > 0 ) { LOGGER . log ( Level . FINE , "discovered serialized lastVersion {0}" , lastVersion ) ; return lastVersion ; } } catch ( Exception e ) { LOGGER . log ( SEVERE , "Unexpected error reading global config.xml" , e ) ; } } return NEW_INSTALL_VERSION . toString ( ) ; } }
Get the last saved Jenkins instance version .
16,972
@ SuppressWarnings ( "unchecked" ) public static synchronized Map < String , String > getPersistedInstallStatus ( ) { File installingPluginsFile = getInstallingPluginsFile ( ) ; if ( installingPluginsFile == null || ! installingPluginsFile . exists ( ) ) { return null ; } return ( Map < String , String > ) new XStream ( ) . fromXML ( installingPluginsFile ) ; }
Returns a list of any plugins that are persisted in the installing list
16,973
public static synchronized void persistInstallStatus ( List < UpdateCenterJob > installingPlugins ) { File installingPluginsFile = getInstallingPluginsFile ( ) ; if ( installingPlugins == null || installingPlugins . isEmpty ( ) ) { installingPluginsFile . delete ( ) ; return ; } LOGGER . fine ( "Writing install state to: " + installingPluginsFile . getAbsolutePath ( ) ) ; Map < String , String > statuses = new HashMap < > ( ) ; for ( UpdateCenterJob j : installingPlugins ) { if ( j instanceof InstallationJob && j . getCorrelationId ( ) != null ) { InstallationJob ij = ( InstallationJob ) j ; InstallationStatus status = ij . status ; String statusText = status . getType ( ) ; if ( status instanceof Installing ) { statusText = "Pending" ; } statuses . put ( ij . plugin . name , statusText ) ; } } try { String installingPluginXml = new XStream ( ) . toXML ( statuses ) ; FileUtils . write ( installingPluginsFile , installingPluginXml ) ; } catch ( IOException e ) { LOGGER . log ( SEVERE , "Failed to save " + installingPluginsFile . getAbsolutePath ( ) , e ) ; } }
Persists a list of installing plugins ; this is used in the case Jenkins fails mid - installation and needs to be restarted
16,974
public V start ( ) throws Exception { V result = null ; int currentAttempt = 0 ; boolean success = false ; while ( currentAttempt < attempts && ! success ) { currentAttempt ++ ; try { if ( LOGGER . isLoggable ( Level . INFO ) ) { LOGGER . log ( Level . INFO , Messages . Retrier_Attempt ( currentAttempt , action ) ) ; } result = callable . call ( ) ; } catch ( Exception e ) { if ( duringActionExceptions == null || Stream . of ( duringActionExceptions ) . noneMatch ( exception -> exception . isAssignableFrom ( e . getClass ( ) ) ) ) { LOGGER . log ( Level . WARNING , Messages . Retrier_ExceptionThrown ( currentAttempt , action ) , e ) ; throw e ; } else { LOGGER . log ( Level . INFO , Messages . Retrier_ExceptionFailed ( currentAttempt , action ) , e ) ; if ( duringActionExceptionListener != null ) { LOGGER . log ( Level . INFO , Messages . Retrier_CallingListener ( e . getLocalizedMessage ( ) , currentAttempt , action ) ) ; result = duringActionExceptionListener . apply ( currentAttempt , e ) ; } } } success = checkResult . test ( currentAttempt , result ) ; if ( ! success ) { if ( currentAttempt < attempts ) { LOGGER . log ( Level . WARNING , Messages . Retrier_AttemptFailed ( currentAttempt , action ) ) ; LOGGER . log ( Level . FINE , Messages . Retrier_Sleeping ( delay , action ) ) ; try { Thread . sleep ( delay ) ; } catch ( InterruptedException ie ) { LOGGER . log ( Level . FINE , Messages . Retrier_Interruption ( action ) ) ; Thread . currentThread ( ) . interrupt ( ) ; currentAttempt = attempts ; } } else { LOGGER . log ( Level . INFO , Messages . Retrier_NoSuccess ( action , attempts ) ) ; } } else { LOGGER . log ( Level . INFO , Messages . Retrier_Success ( action , currentAttempt ) ) ; } } return result ; }
Start to do retries to perform the set action .
16,975
public void setClassPath ( Path classpath ) { pathComponents . removeAllElements ( ) ; if ( classpath != null ) { Path actualClasspath = classpath . concatSystemClasspath ( "ignore" ) ; String [ ] pathElements = actualClasspath . list ( ) ; for ( int i = 0 ; i < pathElements . length ; ++ i ) { try { addPathElement ( pathElements [ i ] ) ; } catch ( BuildException e ) { } } } }
Set the classpath to search for classes to load . This should not be changed once the classloader starts to server classes
16,976
protected void log ( String message , int priority ) { if ( project != null ) { project . log ( message , priority ) ; } }
Logs a message through the project object if one has been provided .
16,977
public void setThreadContextLoader ( ) { if ( isContextLoaderSaved ) { throw new BuildException ( "Context loader has not been reset" ) ; } if ( LoaderUtils . isContextLoaderAvailable ( ) ) { savedContextLoader = LoaderUtils . getContextClassLoader ( ) ; ClassLoader loader = this ; if ( project != null && "only" . equals ( project . getProperty ( "build.sysclasspath" ) ) ) { loader = this . getClass ( ) . getClassLoader ( ) ; } LoaderUtils . setContextClassLoader ( loader ) ; isContextLoaderSaved = true ; } }
Sets the current thread s context loader to this classloader storing the current loader value for later resetting .
16,978
public void resetThreadContextLoader ( ) { if ( LoaderUtils . isContextLoaderAvailable ( ) && isContextLoaderSaved ) { LoaderUtils . setContextClassLoader ( savedContextLoader ) ; savedContextLoader = null ; isContextLoaderSaved = false ; } }
Resets the current thread s context loader to its original value .
16,979
public void addPathElement ( String pathElement ) throws BuildException { File pathComponent = project != null ? project . resolveFile ( pathElement ) : new File ( pathElement ) ; try { addPathFile ( pathComponent ) ; } catch ( IOException e ) { throw new BuildException ( e ) ; } }
Adds an element to the classpath to be searched .
16,980
protected void addPathFile ( File pathComponent ) throws IOException { if ( ! pathComponents . contains ( pathComponent ) ) { pathComponents . addElement ( pathComponent ) ; } if ( pathComponent . isDirectory ( ) ) { return ; } String absPathPlusTimeAndLength = pathComponent . getAbsolutePath ( ) + pathComponent . lastModified ( ) + "-" + pathComponent . length ( ) ; String classpath = ( String ) pathMap . get ( absPathPlusTimeAndLength ) ; if ( classpath == null ) { JarFile jarFile = null ; try { jarFile = new JarFile ( pathComponent ) ; Manifest manifest = jarFile . getManifest ( ) ; if ( manifest == null ) { return ; } classpath = manifest . getMainAttributes ( ) . getValue ( Attributes . Name . CLASS_PATH ) ; } finally { if ( jarFile != null ) { jarFile . close ( ) ; } } if ( classpath == null ) { classpath = "" ; } pathMap . put ( absPathPlusTimeAndLength , classpath ) ; } if ( ! "" . equals ( classpath ) ) { URL baseURL = FILE_UTILS . getFileURL ( pathComponent ) ; StringTokenizer st = new StringTokenizer ( classpath ) ; while ( st . hasMoreTokens ( ) ) { String classpathElement = st . nextToken ( ) ; URL libraryURL = new URL ( baseURL , classpathElement ) ; if ( ! libraryURL . getProtocol ( ) . equals ( "file" ) ) { log ( "Skipping jar library " + classpathElement + " since only relative URLs are supported by this" + " loader" , Project . MSG_VERBOSE ) ; continue ; } String decodedPath = Locator . decodeUri ( libraryURL . getFile ( ) ) ; File libraryFile = new File ( decodedPath ) ; if ( libraryFile . exists ( ) && ! isInPath ( libraryFile ) ) { addPathFile ( libraryFile ) ; } } } }
Add a file to the path . Reads the manifest if available and adds any additional class path jars specified in the manifest .
16,981
public String getClasspath ( ) { StringBuilder sb = new StringBuilder ( ) ; boolean firstPass = true ; Enumeration componentEnum = pathComponents . elements ( ) ; while ( componentEnum . hasMoreElements ( ) ) { if ( ! firstPass ) { sb . append ( System . getProperty ( "path.separator" ) ) ; } else { firstPass = false ; } sb . append ( ( ( File ) componentEnum . nextElement ( ) ) . getAbsolutePath ( ) ) ; } return sb . toString ( ) ; }
Returns the classpath this classloader will consult .
16,982
public static void initializeClass ( Class theClass ) { final Constructor [ ] cons = theClass . getDeclaredConstructors ( ) ; if ( cons != null ) { if ( cons . length > 0 && cons [ 0 ] != null ) { final String [ ] strs = new String [ NUMBER_OF_STRINGS ] ; try { cons [ 0 ] . newInstance ( ( Object [ ] ) strs ) ; } catch ( Exception e ) { } } } }
Forces initialization of a class in a JDK 1 . 1 compatible albeit hacky way .
16,983
public Class forceLoadClass ( String classname ) throws ClassNotFoundException { log ( "force loading " + classname , Project . MSG_DEBUG ) ; Class theClass = findLoadedClass ( classname ) ; if ( theClass == null ) { theClass = findClass ( classname ) ; } return theClass ; }
Loads a class through this class loader even if that class is available on the parent classpath .
16,984
public Class forceLoadSystemClass ( String classname ) throws ClassNotFoundException { log ( "force system loading " + classname , Project . MSG_DEBUG ) ; Class theClass = findLoadedClass ( classname ) ; if ( theClass == null ) { theClass = findBaseClass ( classname ) ; } return theClass ; }
Loads a class through this class loader but defer to the parent class loader .
16,985
public InputStream getResourceAsStream ( String name ) { InputStream resourceStream = null ; if ( isParentFirst ( name ) ) { resourceStream = loadBaseResource ( name ) ; } if ( resourceStream != null ) { log ( "ResourceStream for " + name + " loaded from parent loader" , Project . MSG_DEBUG ) ; } else { resourceStream = loadResource ( name ) ; if ( resourceStream != null ) { log ( "ResourceStream for " + name + " loaded from ant loader" , Project . MSG_DEBUG ) ; } } if ( resourceStream == null && ! isParentFirst ( name ) ) { if ( ignoreBase ) { resourceStream = getRootLoader ( ) == null ? null : getRootLoader ( ) . getResourceAsStream ( name ) ; } else { resourceStream = loadBaseResource ( name ) ; } if ( resourceStream != null ) { log ( "ResourceStream for " + name + " loaded from parent loader" , Project . MSG_DEBUG ) ; } } if ( resourceStream == null ) { log ( "Couldn't load ResourceStream for " + name , Project . MSG_DEBUG ) ; } return resourceStream ; }
Returns a stream to read the requested resource name .
16,986
private InputStream loadResource ( String name ) { InputStream stream = null ; Enumeration e = pathComponents . elements ( ) ; while ( e . hasMoreElements ( ) && stream == null ) { File pathComponent = ( File ) e . nextElement ( ) ; stream = getResourceStream ( pathComponent , name ) ; } return stream ; }
Returns a stream to read the requested resource name from this loader .
16,987
private InputStream getResourceStream ( File file , String resourceName ) { try { JarFile jarFile = ( JarFile ) jarFiles . get ( file ) ; if ( jarFile == null && file . isDirectory ( ) ) { File resource = new File ( file , resourceName ) ; if ( resource . exists ( ) ) { return Files . newInputStream ( resource . toPath ( ) ) ; } } else { if ( jarFile == null ) { if ( file . exists ( ) ) { jarFile = new JarFile ( file ) ; jarFiles . put ( file , jarFile ) ; } else { return null ; } jarFile = ( JarFile ) jarFiles . get ( file ) ; } JarEntry entry = jarFile . getJarEntry ( resourceName ) ; if ( entry != null ) { return jarFile . getInputStream ( entry ) ; } } } catch ( Exception e ) { log ( "Ignoring Exception " + e . getClass ( ) . getName ( ) + ": " + e . getMessage ( ) + " reading resource " + resourceName + " from " + file , Project . MSG_VERBOSE ) ; } return null ; }
Returns an inputstream to a given resource in the given file which may either be a directory or a zip file .
16,988
private boolean isParentFirst ( String resourceName ) { boolean useParentFirst = parentFirst ; for ( Enumeration e = systemPackages . elements ( ) ; e . hasMoreElements ( ) ; ) { String packageName = ( String ) e . nextElement ( ) ; if ( resourceName . startsWith ( packageName ) ) { useParentFirst = true ; break ; } } for ( Enumeration e = loaderPackages . elements ( ) ; e . hasMoreElements ( ) ; ) { String packageName = ( String ) e . nextElement ( ) ; if ( resourceName . startsWith ( packageName ) ) { useParentFirst = false ; break ; } } return useParentFirst ; }
Tests whether or not the parent classloader should be checked for a resource before this one . If the resource matches both the use parent classloader first and the use this classloader first lists the latter takes priority .
16,989
private ClassLoader getRootLoader ( ) { ClassLoader ret = getClass ( ) . getClassLoader ( ) ; while ( ret != null && ret . getParent ( ) != null ) { ret = ret . getParent ( ) ; } return ret ; }
Used for isolated resource seaching .
16,990
protected Enumeration findResources ( String name , boolean parentHasBeenSearched ) throws IOException { Enumeration mine = new ResourceEnumeration ( name ) ; Enumeration base ; if ( parent != null && ( ! parentHasBeenSearched || parent != getParent ( ) ) ) { base = parent . getResources ( name ) ; } else { base = new CollectionUtils . EmptyEnumeration ( ) ; } if ( isParentFirst ( name ) ) { return CollectionUtils . append ( base , mine ) ; } if ( ignoreBase ) { return getRootLoader ( ) == null ? mine : CollectionUtils . append ( mine , getRootLoader ( ) . getResources ( name ) ) ; } return CollectionUtils . append ( mine , base ) ; }
Returns an enumeration of URLs representing all the resources with the given name by searching the class loader s classpath .
16,991
protected URL getResourceURL ( File file , String resourceName ) { try { JarFile jarFile = ( JarFile ) jarFiles . get ( file ) ; if ( jarFile == null && file . isDirectory ( ) ) { File resource = new File ( file , resourceName ) ; if ( resource . exists ( ) ) { try { return FILE_UTILS . getFileURL ( resource ) ; } catch ( MalformedURLException ex ) { return null ; } } } else { if ( jarFile == null ) { if ( file . exists ( ) ) { jarFile = new JarFile ( file ) ; jarFiles . put ( file , jarFile ) ; } else { return null ; } jarFile = ( JarFile ) jarFiles . get ( file ) ; } JarEntry entry = jarFile . getJarEntry ( resourceName ) ; if ( entry != null ) { try { return new URL ( "jar:" + FILE_UTILS . getFileURL ( file ) + "!/" + entry ) ; } catch ( MalformedURLException ex ) { return null ; } } } } catch ( Exception e ) { String msg = "Unable to obtain resource from " + file + ": " ; log ( msg + e , Project . MSG_WARN ) ; System . err . println ( msg ) ; e . printStackTrace ( ) ; } return null ; }
Returns the URL of a given resource in the given file which may either be a directory or a zip file .
16,992
protected synchronized Class loadClass ( String classname , boolean resolve ) throws ClassNotFoundException { Class theClass = findLoadedClass ( classname ) ; if ( theClass != null ) { return theClass ; } if ( isParentFirst ( classname ) ) { try { theClass = findBaseClass ( classname ) ; log ( "Class " + classname + " loaded from parent loader " + "(parentFirst)" , Project . MSG_DEBUG ) ; } catch ( ClassNotFoundException cnfe ) { theClass = findClass ( classname ) ; log ( "Class " + classname + " loaded from ant loader " + "(parentFirst)" , Project . MSG_DEBUG ) ; } } else { try { theClass = findClass ( classname ) ; log ( "Class " + classname + " loaded from ant loader" , Project . MSG_DEBUG ) ; } catch ( ClassNotFoundException cnfe ) { if ( ignoreBase ) { throw cnfe ; } theClass = findBaseClass ( classname ) ; log ( "Class " + classname + " loaded from parent loader" , Project . MSG_DEBUG ) ; } } if ( resolve ) { resolveClass ( theClass ) ; } return theClass ; }
Loads a class with this class loader .
16,993
protected Class defineClassFromData ( File container , byte [ ] classData , String classname ) throws IOException { definePackage ( container , classname ) ; ProtectionDomain currentPd = Project . class . getProtectionDomain ( ) ; String classResource = getClassFilename ( classname ) ; CodeSource src = new CodeSource ( FILE_UTILS . getFileURL ( container ) , getCertificates ( container , classResource ) ) ; ProtectionDomain classesPd = new ProtectionDomain ( src , currentPd . getPermissions ( ) , this , currentPd . getPrincipals ( ) ) ; return defineClass ( classname , classData , 0 , classData . length , classesPd ) ; }
Define a class given its bytes
16,994
protected void definePackage ( File container , String className ) throws IOException { int classIndex = className . lastIndexOf ( '.' ) ; if ( classIndex == - 1 ) { return ; } String packageName = className . substring ( 0 , classIndex ) ; if ( getPackage ( packageName ) != null ) { return ; } Manifest manifest = getJarManifest ( container ) ; if ( manifest == null ) { definePackage ( packageName , null , null , null , null , null , null , null ) ; } else { definePackage ( container , packageName , manifest ) ; } }
Define the package information associated with a class .
16,995
private Manifest getJarManifest ( File container ) throws IOException { if ( container . isDirectory ( ) ) { return null ; } JarFile jarFile = ( JarFile ) jarFiles . get ( container ) ; if ( jarFile == null ) { return null ; } return jarFile . getManifest ( ) ; }
Get the manifest from the given jar if it is indeed a jar and it has a manifest
16,996
private Certificate [ ] getCertificates ( File container , String entry ) throws IOException { if ( container . isDirectory ( ) ) { return null ; } JarFile jarFile = ( JarFile ) jarFiles . get ( container ) ; if ( jarFile == null ) { return null ; } JarEntry ent = jarFile . getJarEntry ( entry ) ; return ent == null ? null : ent . getCertificates ( ) ; }
Get the certificates for a given jar entry if it is indeed a jar .
16,997
protected void definePackage ( File container , String packageName , Manifest manifest ) { String sectionName = packageName . replace ( '.' , '/' ) + "/" ; String specificationTitle = null ; String specificationVendor = null ; String specificationVersion = null ; String implementationTitle = null ; String implementationVendor = null ; String implementationVersion = null ; String sealedString = null ; URL sealBase = null ; Attributes sectionAttributes = manifest . getAttributes ( sectionName ) ; if ( sectionAttributes != null ) { specificationTitle = sectionAttributes . getValue ( Name . SPECIFICATION_TITLE ) ; specificationVendor = sectionAttributes . getValue ( Name . SPECIFICATION_VENDOR ) ; specificationVersion = sectionAttributes . getValue ( Name . SPECIFICATION_VERSION ) ; implementationTitle = sectionAttributes . getValue ( Name . IMPLEMENTATION_TITLE ) ; implementationVendor = sectionAttributes . getValue ( Name . IMPLEMENTATION_VENDOR ) ; implementationVersion = sectionAttributes . getValue ( Name . IMPLEMENTATION_VERSION ) ; sealedString = sectionAttributes . getValue ( Name . SEALED ) ; } Attributes mainAttributes = manifest . getMainAttributes ( ) ; if ( mainAttributes != null ) { if ( specificationTitle == null ) { specificationTitle = mainAttributes . getValue ( Name . SPECIFICATION_TITLE ) ; } if ( specificationVendor == null ) { specificationVendor = mainAttributes . getValue ( Name . SPECIFICATION_VENDOR ) ; } if ( specificationVersion == null ) { specificationVersion = mainAttributes . getValue ( Name . SPECIFICATION_VERSION ) ; } if ( implementationTitle == null ) { implementationTitle = mainAttributes . getValue ( Name . IMPLEMENTATION_TITLE ) ; } if ( implementationVendor == null ) { implementationVendor = mainAttributes . getValue ( Name . IMPLEMENTATION_VENDOR ) ; } if ( implementationVersion == null ) { implementationVersion = mainAttributes . getValue ( Name . IMPLEMENTATION_VERSION ) ; } if ( sealedString == null ) { sealedString = mainAttributes . getValue ( Name . SEALED ) ; } } if ( sealedString != null && sealedString . equalsIgnoreCase ( "true" ) ) { try { sealBase = new URL ( FileUtils . getFileUtils ( ) . toURI ( container . getAbsolutePath ( ) ) ) ; } catch ( MalformedURLException e ) { } } definePackage ( packageName , specificationTitle , specificationVersion , specificationVendor , implementationTitle , implementationVersion , implementationVendor , sealBase ) ; }
Define the package information when the class comes from a jar with a manifest
16,998
private Class getClassFromStream ( InputStream stream , String classname , File container ) throws IOException , SecurityException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; int bytesRead = - 1 ; byte [ ] buffer = new byte [ BUFFER_SIZE ] ; while ( ( bytesRead = stream . read ( buffer , 0 , BUFFER_SIZE ) ) != - 1 ) { baos . write ( buffer , 0 , bytesRead ) ; } byte [ ] classData = baos . toByteArray ( ) ; return defineClassFromData ( container , classData , classname ) ; }
Reads a class definition from a stream .
16,999
public Class findClass ( String name ) throws ClassNotFoundException { log ( "Finding class " + name , Project . MSG_DEBUG ) ; return findClassInComponents ( name ) ; }
Searches for and load a class on the classpath of this class loader .