idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
16,700
private void calcPollingBaseline ( AbstractBuild build , Launcher launcher , TaskListener listener ) throws IOException , InterruptedException { SCMRevisionState baseline = build . getAction ( SCMRevisionState . class ) ; if ( baseline == null ) { try { baseline = getScm ( ) . calcRevisionsFromBuild ( build , launcher , listener ) ; } catch ( AbstractMethodError e ) { baseline = SCMRevisionState . NONE ; } if ( baseline != null ) build . addAction ( baseline ) ; } pollingBaseline = baseline ; }
Pushes the baseline up to the newly checked out revision .
16,701
public PollingResult poll ( TaskListener listener ) { SCM scm = getScm ( ) ; if ( scm == null ) { listener . getLogger ( ) . println ( Messages . AbstractProject_NoSCM ( ) ) ; return NO_CHANGES ; } if ( ! isBuildable ( ) ) { listener . getLogger ( ) . println ( Messages . AbstractProject_Disabled ( ) ) ; return NO_CHANGES ; } SCMDecisionHandler veto = SCMDecisionHandler . firstShouldPollVeto ( this ) ; if ( veto != null ) { listener . getLogger ( ) . println ( Messages . AbstractProject_PollingVetoed ( veto ) ) ; return NO_CHANGES ; } R lb = getLastBuild ( ) ; if ( lb == null ) { listener . getLogger ( ) . println ( Messages . AbstractProject_NoBuilds ( ) ) ; return isInQueue ( ) ? NO_CHANGES : BUILD_NOW ; } if ( pollingBaseline == null ) { R success = getLastSuccessfulBuild ( ) ; for ( R r = lb ; r != null ; r = r . getPreviousBuild ( ) ) { SCMRevisionState s = r . getAction ( SCMRevisionState . class ) ; if ( s != null ) { pollingBaseline = s ; break ; } if ( r == success ) break ; } } try { SCMPollListener . fireBeforePolling ( this , listener ) ; PollingResult r = _poll ( listener , scm ) ; SCMPollListener . firePollingSuccess ( this , listener , r ) ; return r ; } catch ( AbortException e ) { listener . getLogger ( ) . println ( e . getMessage ( ) ) ; listener . fatalError ( Messages . AbstractProject_Aborted ( ) ) ; LOGGER . log ( Level . FINE , "Polling " + this + " aborted" , e ) ; SCMPollListener . firePollingFailed ( this , listener , e ) ; return NO_CHANGES ; } catch ( IOException e ) { Functions . printStackTrace ( e , listener . fatalError ( e . getMessage ( ) ) ) ; SCMPollListener . firePollingFailed ( this , listener , e ) ; return NO_CHANGES ; } catch ( InterruptedException e ) { Functions . printStackTrace ( e , listener . fatalError ( Messages . AbstractProject_PollingABorted ( ) ) ) ; SCMPollListener . firePollingFailed ( this , listener , e ) ; return NO_CHANGES ; } catch ( RuntimeException e ) { SCMPollListener . firePollingFailed ( this , listener , e ) ; throw e ; } catch ( Error e ) { SCMPollListener . firePollingFailed ( this , listener , e ) ; throw e ; } }
Checks if there s any update in SCM and returns true if any is found .
16,702
private boolean isAllSuitableNodesOffline ( R build ) { Label label = getAssignedLabel ( ) ; List < Node > allNodes = Jenkins . getInstance ( ) . getNodes ( ) ; if ( label != null ) { if ( label . getNodes ( ) . isEmpty ( ) ) { return false ; } return label . isOffline ( ) ; } else { if ( canRoam ) { for ( Node n : Jenkins . getInstance ( ) . getNodes ( ) ) { Computer c = n . toComputer ( ) ; if ( c != null && c . isOnline ( ) && c . isAcceptingTasks ( ) && n . getMode ( ) == Mode . NORMAL ) { return false ; } } return Jenkins . getInstance ( ) . getMode ( ) == Mode . EXCLUSIVE ; } } return true ; }
Returns true if all suitable nodes for the job are offline .
16,703
public boolean hasParticipant ( User user ) { for ( R build = getLastBuild ( ) ; build != null ; build = build . getPreviousBuild ( ) ) if ( build . hasParticipant ( user ) ) return true ; return false ; }
Returns true if this user has made a commit to this project .
16,704
public < T extends Trigger > T getTrigger ( Class < T > clazz ) { for ( Trigger p : triggers ( ) ) { if ( clazz . isInstance ( p ) ) return clazz . cast ( p ) ; } return null ; }
Gets the specific trigger or null if the property is not configured for this job .
16,705
private void checkAndRecord ( AbstractProject that , TreeMap < Integer , RangeSet > r , Collection < R > builds ) { for ( R build : builds ) { RangeSet rs = build . getDownstreamRelationship ( that ) ; if ( rs == null || rs . isEmpty ( ) ) continue ; int n = build . getNumber ( ) ; RangeSet value = r . get ( n ) ; if ( value == null ) r . put ( n , rs ) ; else value . add ( rs ) ; } }
Helper method for getDownstreamRelationship .
16,706
public int getDelay ( StaplerRequest req ) throws ServletException { String delay = req . getParameter ( "delay" ) ; if ( delay == null ) return getQuietPeriod ( ) ; try { if ( delay . endsWith ( "sec" ) ) delay = delay . substring ( 0 , delay . length ( ) - 3 ) ; if ( delay . endsWith ( "secs" ) ) delay = delay . substring ( 0 , delay . length ( ) - 4 ) ; return Integer . parseInt ( delay ) ; } catch ( NumberFormatException e ) { throw new ServletException ( "Invalid delay parameter value: " + delay ) ; } }
Computes the delay by taking the default value and the override in the request parameter into the account .
16,707
public DirectoryBrowserSupport doWs ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException , InterruptedException { checkPermission ( Item . WORKSPACE ) ; FilePath ws = getSomeWorkspace ( ) ; if ( ( ws == null ) || ( ! ws . exists ( ) ) ) { req . getView ( this , "noWorkspace.jelly" ) . forward ( req , rsp ) ; return null ; } else { Computer c = ws . toComputer ( ) ; String title ; if ( c == null ) { title = Messages . AbstractProject_WorkspaceTitle ( getDisplayName ( ) ) ; } else { title = Messages . AbstractProject_WorkspaceTitleOnComputer ( getDisplayName ( ) , c . getDisplayName ( ) ) ; } return new DirectoryBrowserSupport ( this , ws , title , "folder.png" , true ) ; } }
Serves the workspace files .
16,708
public HttpResponse doDoWipeOutWorkspace ( ) throws IOException , ServletException , InterruptedException { checkPermission ( Functions . isWipeOutPermissionEnabled ( ) ? WIPEOUT : BUILD ) ; R b = getSomeBuildWithWorkspace ( ) ; FilePath ws = b != null ? b . getWorkspace ( ) : null ; if ( ws != null && getScm ( ) . processWorkspaceBeforeDeletion ( this , ws , b . getBuiltOn ( ) ) ) { ws . deleteRecursive ( ) ; for ( WorkspaceListener wl : WorkspaceListener . all ( ) ) { wl . afterDelete ( this ) ; } return new HttpRedirect ( "." ) ; } else { return new ForwardToView ( this , "wipeOutWorkspaceBlocked.jelly" ) ; } }
Wipes out the workspace .
16,709
static String paren ( LabelOperatorPrecedence op , Label l ) { if ( op . compareTo ( l . precedence ( ) ) < 0 ) return '(' + l . getExpression ( ) + ')' ; return l . getExpression ( ) ; }
Puts the label name into a parenthesis if the given operator will have a higher precedence .
16,710
public static List < Integer > sequence ( final int start , int end , final int step ) { final int size = ( end - start ) / step ; if ( size < 0 ) throw new IllegalArgumentException ( "List size is negative" ) ; return new AbstractList < Integer > ( ) { public Integer get ( int index ) { if ( index < 0 || index >= size ) throw new IndexOutOfBoundsException ( ) ; return start + index * step ; } public int size ( ) { return size ; } } ; }
Returns a list that represents [ start end ) .
16,711
public static < T > Iterator < T > removeNull ( final Iterator < T > itr ) { return com . google . common . collect . Iterators . filter ( itr , Predicates . notNull ( ) ) ; }
Wraps another iterator and throws away nulls .
16,712
public static < T > Iterator < T > limit ( final Iterator < ? extends T > base , final CountingPredicate < ? super T > filter ) { return new Iterator < T > ( ) { private T next ; private boolean end ; private int index = 0 ; public boolean hasNext ( ) { fetch ( ) ; return next != null ; } public T next ( ) { fetch ( ) ; T r = next ; next = null ; return r ; } private void fetch ( ) { if ( next == null && ! end ) { if ( base . hasNext ( ) ) { next = base . next ( ) ; if ( ! filter . apply ( index ++ , next ) ) { next = null ; end = true ; } } else { end = true ; } } } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }
Returns the elements in the base iterator until it hits any element that doesn t satisfy the filter . Then the rest of the elements in the base iterator gets ignored .
16,713
public static InitStrategy get ( ClassLoader cl ) throws IOException { Iterator < InitStrategy > it = ServiceLoader . load ( InitStrategy . class , cl ) . iterator ( ) ; if ( ! it . hasNext ( ) ) { return new InitStrategy ( ) ; } InitStrategy s = it . next ( ) ; LOGGER . log ( Level . FINE , "Using {0} as InitStrategy" , s ) ; return s ; }
Obtains the instance to be used .
16,714
public void override ( String key , String value ) { if ( value == null || value . length ( ) == 0 ) { remove ( key ) ; return ; } int idx = key . indexOf ( '+' ) ; if ( idx > 0 ) { String realKey = key . substring ( 0 , idx ) ; String v = get ( realKey ) ; if ( v == null ) v = value ; else { char ch = platform == null ? File . pathSeparatorChar : platform . pathSeparator ; v = value + ch + v ; } put ( realKey , v ) ; return ; } put ( key , value ) ; }
Overrides the current entry by the given entry .
16,715
public static void resolve ( Map < String , String > env ) { for ( Map . Entry < String , String > entry : env . entrySet ( ) ) { entry . setValue ( Util . replaceMacro ( entry . getValue ( ) , env ) ) ; } }
Resolves environment variables against each other .
16,716
public void addLine ( String line ) { int sep = line . indexOf ( '=' ) ; if ( sep > 0 ) { put ( line . substring ( 0 , sep ) , line . substring ( sep + 1 ) ) ; } }
Takes a string that looks like a = b and adds that to this map .
16,717
public static EnvVars getRemote ( VirtualChannel channel ) throws IOException , InterruptedException { if ( channel == null ) return new EnvVars ( "N/A" , "N/A" ) ; return channel . call ( new GetEnvVars ( ) ) ; }
Obtains the environment variables of a remote peer .
16,718
public ACL getACL ( final View item ) { return ACL . lambda ( ( a , permission ) -> { ACL base = item . getOwner ( ) . getACL ( ) ; boolean hasPermission = base . hasPermission ( a , permission ) ; if ( ! hasPermission && permission == View . READ ) { return base . hasPermission ( a , View . CONFIGURE ) || ! item . getItems ( ) . isEmpty ( ) ; } return hasPermission ; } ) ; }
Implementation can choose to provide different ACL for different views . This can be used as a basis for more fine - grained access control .
16,719
public HttpResponse doDoDelete ( ) throws IOException { checkPermission ( DELETE ) ; try { T node = getNode ( ) ; if ( node != null ) { node . terminate ( ) ; } return new HttpRedirect ( ".." ) ; } catch ( InterruptedException e ) { return HttpResponses . error ( 500 , e ) ; } }
When the agent is deleted free the node right away .
16,720
public synchronized boolean remove ( E e ) { List < E > n = new ArrayList < > ( core ) ; boolean r = n . remove ( e ) ; core = n ; return r ; }
Removes an item from the list .
16,721
public Iterator < E > iterator ( ) { final Iterator < ? extends E > itr = core . iterator ( ) ; return new Iterator < E > ( ) { private E last ; public boolean hasNext ( ) { return itr . hasNext ( ) ; } public E next ( ) { return last = itr . next ( ) ; } public void remove ( ) { CopyOnWriteList . this . remove ( last ) ; } } ; }
Returns an iterator .
16,722
public static File getLogsRoot ( ) { String tagsLogsPath = SystemProperties . getString ( LOGS_ROOT_PATH_PROPERTY ) ; if ( tagsLogsPath == null ) { return new File ( Jenkins . get ( ) . getRootDir ( ) , "logs" ) ; } else { Level logLevel = Level . INFO ; if ( ALREADY_LOGGED ) { logLevel = Level . FINE ; } LOGGER . log ( logLevel , "Using non default root path for tasks logging: {0}. (Beware: no automated migration if you change or remove it again)" , LOGS_ROOT_PATH_PROPERTY ) ; ALREADY_LOGGED = true ; return new File ( tagsLogsPath ) ; } }
The root path that should be used to put logs related to the tasks running in Jenkins .
16,723
private < R > Collection < R > copy ( Iterable < R > src ) { return Lists . newArrayList ( src ) ; }
Creates a copy since we ll be deleting some entries from them .
16,724
public void closeEntry ( ) throws IOException { if ( this . assemLen > 0 ) { for ( int i = this . assemLen ; i < this . assemBuf . length ; ++ i ) { this . assemBuf [ i ] = 0 ; } this . buffer . writeRecord ( this . assemBuf ) ; this . currBytes += this . assemLen ; this . assemLen = 0 ; } if ( this . currBytes < this . currSize ) { throw new IOException ( "entry '" + currName + "' closed at '" + this . currBytes + "' before the '" + this . currSize + "' bytes specified in the header were written" ) ; } }
Close an entry . This method MUST be called for all file entries that contain data . The reason is that we must buffer data written to the stream in order to satisfy the buffer s record based writes . Thus there may be data fragments still being assembled that must be written to the output stream before this entry is closed and the next entry written .
16,725
public void setFullName ( String name ) { if ( Util . fixEmptyAndTrim ( name ) == null ) name = id ; this . fullName = name ; }
Sets the human readable name of the user . If the input parameter is empty the user s ID will be set .
16,726
public < T extends UserProperty > T getProperty ( Class < T > clazz ) { for ( UserProperty p : properties ) { if ( clazz . isInstance ( p ) ) return clazz . cast ( p ) ; } return null ; }
Gets the specific property or null .
16,727
public static Collection < User > getAll ( ) { final IdStrategy strategy = idStrategy ( ) ; ArrayList < User > users = new ArrayList < > ( AllUsers . values ( ) ) ; users . sort ( ( o1 , o2 ) -> strategy . compare ( o1 . getId ( ) , o2 . getId ( ) ) ) ; return users ; }
Gets all the users .
16,728
public static void clear ( ) { if ( ExtensionList . lookup ( AllUsers . class ) . isEmpty ( ) ) { return ; } UserIdMapper . getInstance ( ) . clear ( ) ; AllUsers . clear ( ) ; }
Called by tests in the JTH . Otherwise this shouldn t be called . Even in the tests this usage is questionable .
16,729
public synchronized void save ( ) throws IOException { if ( ! isIdOrFullnameAllowed ( id ) ) { throw FormValidation . error ( Messages . User_IllegalUsername ( id ) ) ; } if ( ! isIdOrFullnameAllowed ( fullName ) ) { throw FormValidation . error ( Messages . User_IllegalFullname ( fullName ) ) ; } if ( BulkChange . contains ( this ) ) { return ; } XmlFile xmlFile = new XmlFile ( XSTREAM , constructUserConfigFile ( ) ) ; xmlFile . write ( this ) ; SaveableListener . fireOnChange ( this , xmlFile ) ; }
Save the user configuration .
16,730
public void delete ( ) throws IOException { String idKey = idStrategy ( ) . keyFor ( id ) ; File existingUserFolder = getExistingUserFolder ( ) ; UserIdMapper . getInstance ( ) . remove ( id ) ; AllUsers . remove ( id ) ; deleteExistingUserFolder ( existingUserFolder ) ; UserDetailsCache . get ( ) . invalidate ( idKey ) ; }
Deletes the data directory and removes this user from Hudson .
16,731
public void doDoDelete ( StaplerRequest req , StaplerResponse rsp ) throws IOException { checkPermission ( Jenkins . ADMINISTER ) ; if ( idStrategy ( ) . equals ( id , Jenkins . getAuthentication ( ) . getName ( ) ) ) { rsp . sendError ( HttpServletResponse . SC_BAD_REQUEST , "Cannot delete self" ) ; return ; } delete ( ) ; rsp . sendRedirect2 ( "../.." ) ; }
Deletes this user from Hudson .
16,732
public boolean canDelete ( ) { final IdStrategy strategy = idStrategy ( ) ; return hasPermission ( Jenkins . ADMINISTER ) && ! strategy . equals ( id , Jenkins . getAuthentication ( ) . getName ( ) ) && UserIdMapper . getInstance ( ) . isMapped ( id ) ; }
With ADMINISTER permission can delete users with persisted data but can t delete self .
16,733
public List < Action > getPropertyActions ( ) { List < Action > actions = new ArrayList < > ( ) ; for ( UserProperty userProp : getProperties ( ) . values ( ) ) { if ( userProp instanceof Action ) { actions . add ( ( Action ) userProp ) ; } } return Collections . unmodifiableList ( actions ) ; }
Return all properties that are also actions .
16,734
public List < Action > getTransientActions ( ) { List < Action > actions = new ArrayList < > ( ) ; for ( TransientUserActionFactory factory : TransientUserActionFactory . all ( ) ) { actions . addAll ( factory . createFor ( this ) ) ; } return Collections . unmodifiableList ( actions ) ; }
Return all transient actions associated with this user .
16,735
public boolean isCollidingWith ( Resource that , int count ) { assert that != null ; for ( Resource r = that ; r != null ; r = r . parent ) if ( this . equals ( r ) && r . numConcurrentWrite < count ) return true ; for ( Resource r = this ; r != null ; r = r . parent ) if ( that . equals ( r ) && r . numConcurrentWrite < count ) return true ; return false ; }
Checks the resource collision .
16,736
public void doDoInstall ( StaplerRequest req , StaplerResponse rsp , @ QueryParameter ( "dir" ) String _dir ) throws IOException , ServletException { Jenkins . getInstance ( ) . checkPermission ( Jenkins . ADMINISTER ) ; if ( installationDir != null ) { sendError ( "Installation is already complete" , req , rsp ) ; return ; } if ( ! DotNet . isInstalled ( 2 , 0 ) ) { sendError ( ".NET Framework 2.0 or later is required for this feature" , req , rsp ) ; return ; } File dir = new File ( _dir ) . getAbsoluteFile ( ) ; dir . mkdirs ( ) ; if ( ! dir . exists ( ) ) { sendError ( "Failed to create installation directory: " + dir , req , rsp ) ; return ; } try { copy ( req , rsp , dir , getClass ( ) . getResource ( "/windows-service/jenkins.exe" ) , "jenkins.exe" ) ; copy ( req , rsp , dir , getClass ( ) . getResource ( "/windows-service/jenkins.exe.config" ) , "jenkins.exe.config" ) ; copy ( req , rsp , dir , getClass ( ) . getResource ( "/windows-service/jenkins.xml" ) , "jenkins.xml" ) ; if ( ! hudsonWar . getCanonicalFile ( ) . equals ( new File ( dir , "jenkins.war" ) . getCanonicalFile ( ) ) ) copy ( req , rsp , dir , hudsonWar . toURI ( ) . toURL ( ) , "jenkins.war" ) ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; StreamTaskListener task = new StreamTaskListener ( baos ) ; task . getLogger ( ) . println ( "Installing a service" ) ; int r = runElevated ( new File ( dir , "jenkins.exe" ) , "install" , task , dir ) ; if ( r != 0 ) { sendError ( baos . toString ( ) , req , rsp ) ; return ; } installationDir = dir ; rsp . sendRedirect ( "." ) ; } catch ( AbortException e ) { } catch ( InterruptedException e ) { throw new ServletException ( e ) ; } }
Performs installation .
16,737
private void copy ( StaplerRequest req , StaplerResponse rsp , File dir , URL src , String name ) throws ServletException , IOException { try { FileUtils . copyURLToFile ( src , new File ( dir , name ) ) ; } catch ( IOException e ) { LOGGER . log ( Level . SEVERE , "Failed to copy " + name , e ) ; sendError ( "Failed to copy " + name + ": " + e . getMessage ( ) , req , rsp ) ; throw new AbortException ( ) ; } }
Copies a single resource into the target folder by the given name and handle errors gracefully .
16,738
protected final void sendError ( Exception e , StaplerRequest req , StaplerResponse rsp ) throws ServletException , IOException { sendError ( e . getMessage ( ) , req , rsp ) ; }
Displays the error in a page .
16,739
static int runElevated ( File jenkinsExe , String command , TaskListener out , File pwd ) throws IOException , InterruptedException { try { return new LocalLauncher ( out ) . launch ( ) . cmds ( jenkinsExe , command ) . stdout ( out ) . pwd ( pwd ) . join ( ) ; } catch ( IOException e ) { if ( e . getMessage ( ) . contains ( "CreateProcess" ) && e . getMessage ( ) . contains ( "=740" ) ) { } else { throw e ; } } SHELLEXECUTEINFO sei = new SHELLEXECUTEINFO ( ) ; sei . fMask = SEE_MASK_NOCLOSEPROCESS ; sei . lpVerb = "runas" ; sei . lpFile = jenkinsExe . getAbsolutePath ( ) ; sei . lpParameters = "/redirect redirect.log " + command ; sei . lpDirectory = pwd . getAbsolutePath ( ) ; sei . nShow = SW_HIDE ; if ( ! Shell32 . INSTANCE . ShellExecuteEx ( sei ) ) throw new IOException ( "Failed to shellExecute: " + Native . getLastError ( ) ) ; try { return Kernel32Utils . waitForExitProcess ( sei . hProcess ) ; } finally { try ( InputStream fin = Files . newInputStream ( new File ( pwd , "redirect.log" ) . toPath ( ) ) ) { IOUtils . copy ( fin , out . getLogger ( ) ) ; } catch ( InvalidPathException e ) { } } }
Invokes jenkins . exe with a SCM management command .
16,740
private void keepLastUpdatedUnique ( ) { Map < String , SingleTokenStats > temp = new HashMap < > ( ) ; this . tokenStats . forEach ( candidate -> { SingleTokenStats current = temp . get ( candidate . tokenUuid ) ; if ( current == null ) { temp . put ( candidate . tokenUuid , candidate ) ; } else { int comparison = SingleTokenStats . COMP_BY_LAST_USE_THEN_COUNTER . compare ( current , candidate ) ; if ( comparison < 0 ) { temp . put ( candidate . tokenUuid , candidate ) ; } } } ) ; this . tokenStats = new ArrayList < > ( temp . values ( ) ) ; }
In case of duplicate entries we keep only the last updated element
16,741
@ Exported ( visibility = 2 ) public List < Cause > getCauses ( ) { List < Cause > r = new ArrayList < > ( ) ; for ( Map . Entry < Cause , Integer > entry : causeBag . entrySet ( ) ) { r . addAll ( Collections . nCopies ( entry . getValue ( ) , entry . getKey ( ) ) ) ; } return Collections . unmodifiableList ( r ) ; }
Lists all causes of this build . Note that the current implementation does not preserve insertion order of duplicates .
16,742
public < T extends Cause > T findCause ( Class < T > type ) { for ( Cause c : causeBag . keySet ( ) ) if ( type . isInstance ( c ) ) return type . cast ( c ) ; return null ; }
Finds the cause of the specific type .
16,743
public static String getValidTimezone ( String timezone ) { String [ ] validIDs = TimeZone . getAvailableIDs ( ) ; for ( String str : validIDs ) { if ( str != null && str . equals ( timezone ) ) { return timezone ; } } return null ; }
Checks if given timezone string is supported by TimeZone and returns the same string if valid null otherwise
16,744
public static Iterable < Descriptor > listLegacyInstances ( ) { return new Iterable < Descriptor > ( ) { public Iterator < Descriptor > iterator ( ) { return new AdaptedIterator < ExtensionComponent < Descriptor > , Descriptor > ( new FlattenIterator < ExtensionComponent < Descriptor > , CopyOnWriteArrayList < ExtensionComponent < Descriptor > > > ( legacyDescriptors . values ( ) ) { protected Iterator < ExtensionComponent < Descriptor > > expand ( CopyOnWriteArrayList < ExtensionComponent < Descriptor > > v ) { return v . iterator ( ) ; } } ) { protected Descriptor adapt ( ExtensionComponent < Descriptor > item ) { return item . getInstance ( ) ; } } ; } } ; }
List up all the legacy instances currently in use .
16,745
public void setValue ( String name , String value ) { byte [ ] bytes = value . getBytes ( StandardCharsets . UTF_16LE ) ; int newLength = bytes . length + 2 ; byte [ ] with0 = new byte [ newLength ] ; System . arraycopy ( bytes , 0 , with0 , 0 , newLength ) ; check ( Advapi32 . INSTANCE . RegSetValueEx ( handle , name , 0 , WINNT . REG_SZ , with0 , with0 . length ) ) ; }
Writes a String value .
16,746
public void setValue ( String name , int value ) { byte [ ] data = new byte [ 4 ] ; data [ 0 ] = ( byte ) ( value & 0xff ) ; data [ 1 ] = ( byte ) ( ( value >> 8 ) & 0xff ) ; data [ 2 ] = ( byte ) ( ( value >> 16 ) & 0xff ) ; data [ 3 ] = ( byte ) ( ( value >> 24 ) & 0xff ) ; check ( Advapi32 . INSTANCE . RegSetValueEx ( handle , name , 0 , WINNT . REG_DWORD , data , data . length ) ) ; }
Writes a DWORD value .
16,747
public boolean valueExists ( String name ) { IntByReference pType , lpcbData ; byte [ ] lpData = new byte [ 1 ] ; pType = new IntByReference ( ) ; lpcbData = new IntByReference ( ) ; OUTER : while ( true ) { int r = Advapi32 . INSTANCE . RegQueryValueEx ( handle , name , null , pType , lpData , lpcbData ) ; switch ( r ) { case WINERROR . ERROR_MORE_DATA : lpData = new byte [ lpcbData . getValue ( ) ] ; continue OUTER ; case WINERROR . ERROR_FILE_NOT_FOUND : return false ; case WINERROR . ERROR_SUCCESS : return true ; default : throw new JnaException ( r ) ; } } }
Does a specified value exist?
16,748
public Collection < String > getSubKeys ( ) { WINBASE . FILETIME lpftLastWriteTime ; TreeSet < String > subKeys = new TreeSet < > ( ) ; char [ ] lpName = new char [ 256 ] ; IntByReference lpcName = new IntByReference ( 256 ) ; lpftLastWriteTime = new WINBASE . FILETIME ( ) ; int dwIndex = 0 ; while ( Advapi32 . INSTANCE . RegEnumKeyEx ( handle , dwIndex , lpName , lpcName , null , null , null , lpftLastWriteTime ) == WINERROR . ERROR_SUCCESS ) { subKeys . add ( new String ( lpName , 0 , lpcName . getValue ( ) ) ) ; lpcName . setValue ( 256 ) ; dwIndex ++ ; } return subKeys ; }
Get all sub keys of a key .
16,749
public TreeMap < String , Object > getValues ( ) { int dwIndex , result ; char [ ] lpValueName ; byte [ ] lpData ; IntByReference lpcchValueName , lpType , lpcbData ; String name ; TreeMap < String , Object > values = new TreeMap < > ( String . CASE_INSENSITIVE_ORDER ) ; lpValueName = new char [ 16384 ] ; lpcchValueName = new IntByReference ( 16384 ) ; lpType = new IntByReference ( ) ; lpData = new byte [ 1 ] ; lpcbData = new IntByReference ( ) ; lpcbData . setValue ( 0 ) ; dwIndex = 0 ; OUTER : while ( true ) { result = Advapi32 . INSTANCE . RegEnumValue ( handle , dwIndex , lpValueName , lpcchValueName , null , lpType , lpData , lpcbData ) ; switch ( result ) { case WINERROR . ERROR_NO_MORE_ITEMS : return values ; case WINERROR . ERROR_MORE_DATA : lpData = new byte [ lpcbData . getValue ( ) ] ; lpcchValueName = new IntByReference ( 16384 ) ; continue OUTER ; case WINERROR . ERROR_SUCCESS : name = new String ( lpValueName , 0 , lpcchValueName . getValue ( ) ) ; switch ( lpType . getValue ( ) ) { case WINNT . REG_SZ : values . put ( name , convertBufferToString ( lpData ) ) ; break ; case WINNT . REG_DWORD : values . put ( name , convertBufferToInt ( lpData ) ) ; break ; default : break ; } break ; default : check ( result ) ; } dwIndex ++ ; lpcbData . setValue ( 0 ) ; } }
Get all values under a key .
16,750
public void preCheckout ( AbstractBuild < ? , ? > build , Launcher launcher , BuildListener listener ) throws IOException , InterruptedException { AbstractProject < ? , ? > project = build . getProject ( ) ; if ( project instanceof BuildableItemWithBuildWrappers ) { BuildableItemWithBuildWrappers biwbw = ( BuildableItemWithBuildWrappers ) project ; for ( BuildWrapper bw : biwbw . getBuildWrappersList ( ) ) bw . preCheckout ( build , launcher , listener ) ; } }
Performs the pre checkout step .
16,751
public Solution getSolution ( String id ) { for ( Solution s : Solution . all ( ) ) if ( s . id . equals ( id ) ) return s ; return null ; }
Binds a solution to the URL .
16,752
public URL getIndexPage ( ) { URL idx = null ; try { Enumeration < URL > en = classLoader . getResources ( "index.jelly" ) ; while ( en . hasMoreElements ( ) ) idx = en . nextElement ( ) ; } catch ( IOException ignore ) { } return idx != null && idx . toString ( ) . contains ( shortName ) ? idx : null ; }
Returns the URL of the index page jelly script .
16,753
public String getUrl ( ) { String url = manifest . getMainAttributes ( ) . getValue ( "Url" ) ; if ( url != null ) return url ; UpdateSite . Plugin ui = getInfo ( ) ; if ( ui != null ) return ui . wiki ; return null ; }
Gets the URL that shows more information about this plugin .
16,754
public String getLongName ( ) { String name = manifest . getMainAttributes ( ) . getValue ( "Long-Name" ) ; if ( name != null ) return name ; return shortName ; }
Returns a one - line descriptive name of this plugin .
16,755
public YesNoMaybe supportsDynamicLoad ( ) { String v = manifest . getMainAttributes ( ) . getValue ( "Support-Dynamic-Loading" ) ; if ( v == null ) return YesNoMaybe . MAYBE ; return Boolean . parseBoolean ( v ) ? YesNoMaybe . YES : YesNoMaybe . NO ; }
Does this plugin supports dynamic loading?
16,756
public String getRequiredCoreVersion ( ) { String v = manifest . getMainAttributes ( ) . getValue ( "Jenkins-Version" ) ; if ( v != null ) return v ; v = manifest . getMainAttributes ( ) . getValue ( "Hudson-Version" ) ; if ( v != null ) return v ; return null ; }
Returns the required Jenkins core version of this plugin .
16,757
public void stop ( ) { Plugin plugin = getPlugin ( ) ; if ( plugin != null ) { try { LOGGER . log ( Level . FINE , "Stopping {0}" , shortName ) ; plugin . stop ( ) ; } catch ( Throwable t ) { LOGGER . log ( WARNING , "Failed to shut down " + shortName , t ) ; } } else { LOGGER . log ( Level . FINE , "Could not find Plugin instance to stop for {0}" , shortName ) ; } LogFactory . release ( classLoader ) ; }
Terminates the plugin .
16,758
public void enable ( ) throws IOException { if ( ! disableFile . exists ( ) ) { LOGGER . log ( Level . FINEST , "Plugin {0} has been already enabled. Skipping the enable() operation" , getShortName ( ) ) ; return ; } if ( ! disableFile . delete ( ) ) throw new IOException ( "Failed to delete " + disableFile ) ; }
Enables this plugin next time Jenkins runs .
16,759
private void disableWithoutCheck ( ) throws IOException { try ( OutputStream os = Files . newOutputStream ( disableFile . toPath ( ) ) ) { os . close ( ) ; } catch ( InvalidPathException e ) { throw new IOException ( e ) ; } }
Disable a plugin wihout checking any dependency . Only add the disable file .
16,760
public String getBackupVersion ( ) { File backup = getBackupFile ( ) ; if ( backup . exists ( ) ) { try { try ( JarFile backupPlugin = new JarFile ( backup ) ) { return backupPlugin . getManifest ( ) . getMainAttributes ( ) . getValue ( "Plugin-Version" ) ; } } catch ( IOException e ) { LOGGER . log ( WARNING , "Failed to get backup version from " + backup , e ) ; return null ; } } else { return null ; } }
returns the version of the backed up plugin or null if there s no back up .
16,761
protected synchronized Thread start ( boolean forceRestart ) { if ( ! forceRestart && isFixingActive ( ) ) { fixThread . interrupt ( ) ; } if ( forceRestart || ! isFixingActive ( ) ) { fixThread = new FixThread ( ) ; fixThread . start ( ) ; } return fixThread ; }
Starts the background fixing activity .
16,762
public static void doTrackback ( Object it , StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { String url = req . getParameter ( "url" ) ; rsp . setStatus ( HttpServletResponse . SC_OK ) ; rsp . setContentType ( "application/xml; charset=UTF-8" ) ; try ( PrintWriter pw = rsp . getWriter ( ) ) { pw . println ( "<response>" ) ; pw . println ( "<error>" + ( url != null ? 0 : 1 ) + "</error>" ) ; if ( url == null ) { pw . println ( "<message>url must be specified</message>" ) ; } pw . println ( "</response>" ) ; } }
Parses trackback ping .
16,763
public static < E > void forwardToRss ( String title , String url , Collection < ? extends E > entries , FeedAdapter < E > adapter , StaplerRequest req , HttpServletResponse rsp ) throws IOException , ServletException { req . setAttribute ( "adapter" , adapter ) ; req . setAttribute ( "title" , title ) ; req . setAttribute ( "url" , url ) ; req . setAttribute ( "entries" , entries ) ; req . setAttribute ( "rootURL" , Jenkins . getInstance ( ) . getRootUrl ( ) ) ; String flavor = req . getParameter ( "flavor" ) ; if ( flavor == null ) flavor = "atom" ; flavor = flavor . replace ( '/' , '_' ) ; req . getView ( Jenkins . getInstance ( ) , "/hudson/" + flavor + ".jelly" ) . forward ( req , rsp ) ; }
Sends the RSS feed to the client .
16,764
public String getName ( ) { String name = getClass ( ) . getName ( ) ; name = name . substring ( name . lastIndexOf ( '.' ) + 1 ) ; name = name . substring ( name . lastIndexOf ( '$' ) + 1 ) ; if ( name . endsWith ( "Command" ) ) name = name . substring ( 0 , name . length ( ) - 7 ) ; return name . replaceAll ( "([a-z0-9])([A-Z])" , "$1-$2" ) . toLowerCase ( Locale . ENGLISH ) ; }
Gets the command name .
16,765
public Authentication getTransportAuthentication ( ) { Authentication a = transportAuth ; if ( a == null ) a = Jenkins . ANONYMOUS ; return a ; }
Returns the identity of the client as determined at the CLI transport level .
16,766
@ Restricted ( NoExternalUse . class ) public final String getSingleLineSummary ( ) { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; getCmdLineParser ( ) . printSingleLineUsage ( out ) ; return out . toString ( ) ; }
Get single line summary as a string .
16,767
@ Restricted ( NoExternalUse . class ) public final String getUsage ( ) { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; getCmdLineParser ( ) . printUsage ( out ) ; return out . toString ( ) ; }
Get usage as a string .
16,768
@ Restricted ( NoExternalUse . class ) public final String getLongDescription ( ) { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; PrintStream ps = new PrintStream ( out ) ; printUsageSummary ( ps ) ; ps . close ( ) ; return out . toString ( ) ; }
Get long description as a string .
16,769
protected final FilePath preferredLocation ( ToolInstallation tool , Node node ) { if ( node == null ) { throw new IllegalArgumentException ( "must pass non-null node" ) ; } String home = Util . fixEmptyAndTrim ( tool . getHome ( ) ) ; if ( home == null ) { home = sanitize ( tool . getDescriptor ( ) . getId ( ) ) + File . separatorChar + sanitize ( tool . getName ( ) ) ; } FilePath root = node . getRootPath ( ) ; if ( root == null ) { throw new IllegalArgumentException ( "Node " + node . getDisplayName ( ) + " seems to be offline" ) ; } return root . child ( "tools" ) . child ( home ) ; }
Convenience method to find a location to install a tool .
16,770
private String getFileName ( String possiblyPathName ) { possiblyPathName = possiblyPathName . substring ( possiblyPathName . lastIndexOf ( '/' ) + 1 ) ; possiblyPathName = possiblyPathName . substring ( possiblyPathName . lastIndexOf ( '\\' ) + 1 ) ; return possiblyPathName ; }
Strip off the path portion if the given path contains it .
16,771
@ SuppressFBWarnings ( value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE" , justification = "Null checks in readResolve are valid since we deserialize and upgrade objects" ) protected Object readResolve ( ) { if ( allowEmptyArchive == null ) { this . allowEmptyArchive = SystemProperties . getBoolean ( ArtifactArchiver . class . getName ( ) + ".warnOnEmpty" ) ; } if ( defaultExcludes == null ) { defaultExcludes = true ; } if ( caseSensitive == null ) { caseSensitive = true ; } return this ; }
Backwards compatibility for older builds
16,772
private void applyForcedChanges ( ) { ApiTokenPropertyConfiguration apiTokenPropertyConfiguration = ApiTokenPropertyConfiguration . get ( ) ; if ( ! apiTokenPropertyConfiguration . hasExistingConfigFile ( ) ) { LOGGER . log ( Level . INFO , "New API token system configured with insecure options to keep legacy behavior" ) ; apiTokenPropertyConfiguration . setCreationOfLegacyTokenEnabled ( false ) ; apiTokenPropertyConfiguration . setTokenGenerationOnCreationEnabled ( false ) ; } }
Put here the different changes that are enforced after an update .
16,773
public boolean isDue ( ) { if ( isUpToDate ) return false ; if ( ! Jenkins . getInstance ( ) . hasPermission ( Jenkins . ADMINISTER ) ) return false ; WebApp wa = WebApp . getCurrent ( ) ; if ( wa == null || ! ( wa . getApp ( ) instanceof Jenkins ) ) return false ; return System . currentTimeMillis ( ) > SetupWizard . getUpdateStateFile ( ) . lastModified ( ) ; }
Do we need to show the upgrade wizard prompt?
16,774
public boolean isShowUpgradeWizard ( ) { HttpSession session = Stapler . getCurrentRequest ( ) . getSession ( false ) ; if ( session != null ) { return Boolean . TRUE . equals ( session . getAttribute ( SHOW_UPGRADE_WIZARD_FLAG ) ) ; } return false ; }
Whether to show the upgrade wizard
16,775
public HttpResponse doShowUpgradeWizard ( ) throws Exception { Jenkins . getInstance ( ) . checkPermission ( Jenkins . ADMINISTER ) ; HttpSession session = Stapler . getCurrentRequest ( ) . getSession ( true ) ; session . setAttribute ( SHOW_UPGRADE_WIZARD_FLAG , true ) ; return HttpResponses . redirectToContextRoot ( ) ; }
Call this to show the upgrade wizard
16,776
public HttpResponse doHideUpgradeWizard ( ) { Jenkins . getInstance ( ) . checkPermission ( Jenkins . ADMINISTER ) ; HttpSession session = Stapler . getCurrentRequest ( ) . getSession ( false ) ; if ( session != null ) { session . removeAttribute ( SHOW_UPGRADE_WIZARD_FLAG ) ; } return HttpResponses . redirectToContextRoot ( ) ; }
Call this to hide the upgrade wizard
16,777
public HttpResponse doSnooze ( ) throws IOException { Jenkins . getInstance ( ) . checkPermission ( Jenkins . ADMINISTER ) ; File f = SetupWizard . getUpdateStateFile ( ) ; FileUtils . touch ( f ) ; f . setLastModified ( System . currentTimeMillis ( ) + TimeUnit . DAYS . toMillis ( 1 ) ) ; LOGGER . log ( FINE , "Snoozed the upgrade wizard notice" ) ; return HttpResponses . redirectToContextRoot ( ) ; }
Snooze the upgrade wizard notice .
16,778
private void deleteIfEmpty ( File dir ) { String [ ] r = dir . list ( ) ; if ( r == null ) return ; if ( r . length == 0 ) dir . delete ( ) ; }
Deletes a directory if it s empty .
16,779
private boolean check ( File fingerprintFile , TaskListener listener ) { try { Fingerprint fp = loadFingerprint ( fingerprintFile ) ; if ( fp == null || ! fp . isAlive ( ) ) { listener . getLogger ( ) . println ( "deleting obsolete " + fingerprintFile ) ; fingerprintFile . delete ( ) ; return true ; } else { fp = getFingerprint ( fp ) ; return fp . trim ( ) ; } } catch ( IOException e ) { Functions . printStackTrace ( e , listener . error ( "Failed to process " + fingerprintFile ) ) ; return false ; } }
Examines the file and returns true if a file was deleted .
16,780
private boolean isWhitelisted ( RoleSensitive subject , Collection < Role > expected ) { for ( CallableWhitelist w : CallableWhitelist . all ( ) ) { if ( w . isWhitelisted ( subject , expected , context ) ) return true ; } return false ; }
Is this subject class name whitelisted?
16,781
public T get ( String key ) throws IOException { return get ( key , false , null ) ; }
Finds the data object that matches the given key if available or null if not found .
16,782
public String getPerformanceStats ( ) { int total = totalQuery . get ( ) ; int hit = cacheHit . get ( ) ; int weakRef = weakRefLost . get ( ) ; int failure = loadFailure . get ( ) ; int miss = total - hit - weakRef ; return MessageFormat . format ( "total={0} hit={1}% lostRef={2}% failure={3}% miss={4}%" , total , hit , weakRef , failure , miss ) ; }
Gets the short summary of performance statistics .
16,783
private static boolean hasSomeUser ( ) { for ( User u : User . getAll ( ) ) if ( u . getProperty ( Details . class ) != null ) return true ; return false ; }
Computes if this Hudson has some user accounts configured .
16,784
public HttpResponse commenceSignup ( final FederatedIdentity identity ) { Stapler . getCurrentRequest ( ) . getSession ( ) . setAttribute ( FEDERATED_IDENTITY_SESSION_KEY , identity ) ; return new ForwardToView ( this , "signupWithFederatedIdentity.jelly" ) { public void generateResponse ( StaplerRequest req , StaplerResponse rsp , Object node ) throws IOException , ServletException { SignupInfo si = new SignupInfo ( identity ) ; si . errorMessage = Messages . HudsonPrivateSecurityRealm_WouldYouLikeToSignUp ( identity . getPronoun ( ) , identity . getIdentifier ( ) ) ; req . setAttribute ( "data" , si ) ; super . generateResponse ( req , rsp , node ) ; } } ; }
Show the sign up page with the data from the identity .
16,785
public User doCreateAccount ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { return _doCreateAccount ( req , rsp , "signup.jelly" ) ; }
Creates an user account . Used for self - registration .
16,786
@ SuppressWarnings ( "ACL.impersonate" ) private void loginAndTakeBack ( StaplerRequest req , StaplerResponse rsp , User u ) throws ServletException , IOException { HttpSession session = req . getSession ( false ) ; if ( session != null ) { session . invalidate ( ) ; } req . getSession ( true ) ; Authentication a = new UsernamePasswordAuthenticationToken ( u . getId ( ) , req . getParameter ( "password1" ) ) ; a = this . getSecurityComponents ( ) . manager . authenticate ( a ) ; SecurityContextHolder . getContext ( ) . setAuthentication ( a ) ; SecurityListener . fireLoggedIn ( u . getId ( ) ) ; req . getView ( this , "success.jelly" ) . forward ( req , rsp ) ; }
Lets the current user silently login as the given user and report back accordingly .
16,787
public void doCreateAccountByAdmin ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { createAccountByAdmin ( req , rsp , "addUser.jelly" , "." ) ; }
Creates a user account . Used by admins .
16,788
public void doCreateFirstAccount ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { if ( hasSomeUser ( ) ) { rsp . sendError ( SC_UNAUTHORIZED , "First user was already created" ) ; return ; } User u = createAccount ( req , rsp , false , "firstUser.jelly" ) ; if ( u != null ) { tryToMakeAdmin ( u ) ; loginAndTakeBack ( req , rsp , u ) ; } }
Creates a first admin user account .
16,789
private void tryToMakeAdmin ( User u ) { AuthorizationStrategy as = Jenkins . getInstance ( ) . getAuthorizationStrategy ( ) ; for ( PermissionAdder adder : ExtensionList . lookup ( PermissionAdder . class ) ) { if ( adder . add ( as , u , Jenkins . ADMINISTER ) ) { return ; } } }
Try to make this user a super - user
16,790
public User createAccount ( String userName , String password ) throws IOException { User user = User . getById ( userName , true ) ; user . addProperty ( Details . fromPlainPassword ( password ) ) ; SecurityListener . fireUserCreated ( user . getId ( ) ) ; return user ; }
Creates a new user account by registering a password to the user .
16,791
public User createAccountWithHashedPassword ( String userName , String hashedPassword ) throws IOException { if ( ! PASSWORD_ENCODER . isPasswordHashed ( hashedPassword ) ) { throw new IllegalArgumentException ( "this method should only be called with a pre-hashed password" ) ; } User user = User . getById ( userName , true ) ; user . addProperty ( Details . fromHashedPassword ( hashedPassword ) ) ; SecurityListener . fireUserCreated ( user . getId ( ) ) ; return user ; }
Creates a new user account by registering a JBCrypt Hashed password with the user .
16,792
public List < User > getAllUsers ( ) { List < User > r = new ArrayList < User > ( ) ; for ( User u : User . getAll ( ) ) { if ( u . getProperty ( Details . class ) != null ) r . add ( u ) ; } Collections . sort ( r ) ; return r ; }
All users who can login to the system .
16,793
@ Restricted ( NoExternalUse . class ) public User getUser ( String id ) { return User . getById ( id , User . ALLOW_USER_CREATION_VIA_URL && hasPermission ( Jenkins . ADMINISTER ) ) ; }
This is to map users under the security realm URL . This in turn helps us set up the right navigation breadcrumb .
16,794
public HttpResponse render ( ) { return new HttpResponse ( ) { public void generateResponse ( StaplerRequest req , StaplerResponse rsp , Object node ) throws IOException , ServletException { try { new DefaultScriptInvoker ( ) { protected JellyContext createContext ( StaplerRequest req , StaplerResponse rsp , Script script , Object it ) { JellyContext context = super . createContext ( req , rsp , script , it ) ; for ( int i = bodyStack . length - 1 ; i > 0 ; i -- ) { context = new JellyContext ( context ) ; context . setVariable ( "org.apache.commons.jelly.body" , bodyStack [ i ] ) ; } try { AdjunctsInPage . get ( ) . assumeIncluded ( adjuncts ) ; } catch ( IOException | SAXException e ) { LOGGER . log ( Level . WARNING , "Failed to resurrect adjunct context" , e ) ; } return context ; } protected void exportVariables ( StaplerRequest req , StaplerResponse rsp , Script script , Object it , JellyContext context ) { super . exportVariables ( req , rsp , script , it , context ) ; context . setVariables ( variables ) ; req . setAttribute ( "currentDescriptorByNameUrl" , currentDescriptorByNameUrl ) ; } } . invokeScript ( req , rsp , bodyStack [ 0 ] , null ) ; } catch ( JellyTagException e ) { LOGGER . log ( Level . WARNING , "Failed to evaluate the template closure" , e ) ; throw new IOException ( "Failed to evaluate the template closure" , e ) ; } } } ; }
Renders the captured fragment .
16,795
public synchronized void abort ( Throwable cause ) { if ( cause == null ) throw new IllegalArgumentException ( ) ; if ( aborted != null ) return ; aborted = cause ; startLatch . abort ( cause ) ; endLatch . abort ( cause ) ; Thread c = Thread . currentThread ( ) ; for ( WorkUnit wu : workUnits ) { Executor e = wu . getExecutor ( ) ; if ( e != null && e != c ) e . interrupt ( ) ; } }
When one of the work unit is aborted call this method to abort all the other work units .
16,796
public TreeString intern ( final String s ) { if ( s == null ) return null ; return root . intern ( s ) . node ; }
Interns a string .
16,797
public static Channel forProcess ( String name , ExecutorService execService , InputStream in , OutputStream out , OutputStream header , final Proc proc ) throws IOException { ChannelBuilder cb = new ChannelBuilder ( name , execService ) { public Channel build ( CommandTransport transport ) throws IOException { return new Channel ( this , transport ) { public synchronized void terminate ( IOException e ) { super . terminate ( e ) ; try { proc . kill ( ) ; } catch ( IOException x ) { LOGGER . log ( Level . INFO , "Failed to terminate the severed connection" , x ) ; } catch ( InterruptedException x ) { Thread . currentThread ( ) . interrupt ( ) ; } } public synchronized void join ( ) throws InterruptedException { super . join ( ) ; try { proc . join ( ) ; } catch ( IOException e ) { throw new IOError ( e ) ; } } } ; } } ; cb . withHeaderStream ( header ) ; for ( ChannelConfigurator cc : ChannelConfigurator . all ( ) ) { cc . onChannelBuilding ( cb , null ) ; } return cb . build ( in , out ) ; }
Creates a channel that wraps a remote process so that when we shut down the connection we kill the process .
16,798
public void doProgressText ( StaplerRequest req , StaplerResponse rsp ) throws IOException { rsp . setContentType ( "text/plain" ) ; rsp . setStatus ( HttpServletResponse . SC_OK ) ; if ( ! source . exists ( ) ) { rsp . addHeader ( "X-Text-Size" , "0" ) ; rsp . addHeader ( "X-More-Data" , "true" ) ; return ; } long start = 0 ; String s = req . getParameter ( "start" ) ; if ( s != null ) start = Long . parseLong ( s ) ; if ( source . length ( ) < start ) start = 0 ; CharSpool spool = new CharSpool ( ) ; long r = writeLogTo ( start , spool ) ; rsp . addHeader ( "X-Text-Size" , String . valueOf ( r ) ) ; if ( ! completed ) rsp . addHeader ( "X-More-Data" , "true" ) ; Writer w ; if ( r - start > 4096 ) w = rsp . getCompressedWriter ( req ) ; else w = rsp . getWriter ( ) ; spool . writeTo ( new LineEndNormalizingWriter ( w ) ) ; w . close ( ) ; }
Implements the progressive text handling . This method is used as a web method with progressiveText . jelly .
16,799
public void restart ( ) throws IOException , InterruptedException { Jenkins jenkins = Jenkins . getInstanceOrNull ( ) ; try { if ( jenkins != null ) { jenkins . cleanUp ( ) ; } } catch ( Exception e ) { LOGGER . log ( Level . SEVERE , "Failed to clean up. Restart will continue." , e ) ; } System . exit ( 0 ) ; }
In SMF managed environment just commit a suicide and the service will be restarted by SMF .