idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
16,800
public boolean isApplicable ( Class < ? extends T > targetType ) { Class < ? extends T > applicable = Functions . getTypeParameter ( clazz , getP ( ) , 0 ) ; return applicable . isAssignableFrom ( targetType ) ; }
Returns true if this property type is applicable to the given target type .
16,801
protected File getLogDir ( ) { File dir = new File ( Jenkins . getInstance ( ) . getRootDir ( ) , "logs/slaves/" + nodeName ) ; if ( ! dir . exists ( ) && ! dir . mkdirs ( ) ) { LOGGER . severe ( "Failed to create agent log directory " + dir . getAbsolutePath ( ) ) ; } return dir ; }
Directory where rotated agent logs are stored .
16,802
@ Restricted ( NoExternalUse . class ) public List < DisplayExecutor > getDisplayExecutors ( ) { List < DisplayExecutor > result = new ArrayList < > ( executors . size ( ) + oneOffExecutors . size ( ) ) ; int index = 0 ; for ( Executor e : executors ) { if ( e . isDisplayCell ( ) ) { result . add ( new DisplayExecutor ( Integer . toString ( index + 1 ) , String . format ( "executors/%d" , index ) , e ) ) ; } index ++ ; } index = 0 ; for ( OneOffExecutor e : oneOffExecutors ) { if ( e . isDisplayCell ( ) ) { result . add ( new DisplayExecutor ( "" , String . format ( "oneOffExecutors/%d" , index ) , e ) ) ; } index ++ ; } return result ; }
Used to render the list of executors .
16,803
public final boolean isIdle ( ) { if ( ! oneOffExecutors . isEmpty ( ) ) return false ; for ( Executor e : executors ) if ( ! e . isIdle ( ) ) return false ; return true ; }
Returns true if all the executors of this computer are idle .
16,804
public final long getIdleStartMilliseconds ( ) { long firstIdle = Long . MIN_VALUE ; for ( Executor e : oneOffExecutors ) { firstIdle = Math . max ( firstIdle , e . getIdleStartMilliseconds ( ) ) ; } for ( Executor e : executors ) { firstIdle = Math . max ( firstIdle , e . getIdleStartMilliseconds ( ) ) ; } return firstIdle ; }
Returns the time when this computer last became idle .
16,805
public final long getDemandStartMilliseconds ( ) { long firstDemand = Long . MAX_VALUE ; for ( Queue . BuildableItem item : Jenkins . getInstance ( ) . getQueue ( ) . getBuildableItems ( this ) ) { firstDemand = Math . min ( item . buildableStartMilliseconds , firstDemand ) ; } return firstDemand ; }
Returns the time when this computer first became in demand .
16,806
@ Exported ( inline = true ) public Map < String , Object > getMonitorData ( ) { Map < String , Object > r = new HashMap < > ( ) ; if ( hasPermission ( CONNECT ) ) { for ( NodeMonitor monitor : NodeMonitor . getAll ( ) ) r . put ( monitor . getClass ( ) . getName ( ) , monitor . data ( this ) ) ; } return r ; }
Expose monitoring data for the remote API .
16,807
public String getHostName ( ) throws IOException , InterruptedException { if ( hostNameCached ) return cachedHostName ; VirtualChannel channel = getChannel ( ) ; if ( channel == null ) return null ; for ( String address : channel . call ( new ListPossibleNames ( ) ) ) { try { InetAddress ia = InetAddress . getByName ( address ) ; if ( ! ( ia instanceof Inet4Address ) ) { LOGGER . log ( Level . FINE , "{0} is not an IPv4 address" , address ) ; continue ; } if ( ! ComputerPinger . checkIsReachable ( ia , 3 ) ) { LOGGER . log ( Level . FINE , "{0} didn't respond to ping" , address ) ; continue ; } cachedHostName = ia . getCanonicalHostName ( ) ; hostNameCached = true ; return cachedHostName ; } catch ( IOException e ) { LogRecord lr = new LogRecord ( Level . FINE , "Failed to parse {0}" ) ; lr . setThrown ( e ) ; lr . setParameters ( new Object [ ] { address } ) ; LOGGER . log ( lr ) ; } } cachedHostName = channel . call ( new GetFallbackName ( ) ) ; hostNameCached = true ; return cachedHostName ; }
This method tries to compute the name of the host that s reachable by all the other nodes .
16,808
public void doDumpExportTable ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException , InterruptedException { checkPermission ( Jenkins . ADMINISTER ) ; rsp . setContentType ( "text/plain" ) ; try ( PrintWriter w = new PrintWriter ( rsp . getCompressedWriter ( req ) ) ) { VirtualChannel vc = getChannel ( ) ; if ( vc instanceof Channel ) { w . println ( "Master to slave" ) ; ( ( Channel ) vc ) . dumpExportTable ( w ) ; w . flush ( ) ; w . println ( "\n\n\nSlave to master" ) ; w . print ( vc . call ( new DumpExportTableTask ( ) ) ) ; } else { w . println ( Messages . Computer_BadChannel ( ) ) ; } } }
Dumps the contents of the export table .
16,809
public void doScript ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { _doScript ( req , rsp , "_script.jelly" ) ; }
For system diagnostics . Run arbitrary Groovy script .
16,810
public void updateByXml ( final InputStream source ) throws IOException , ServletException { checkPermission ( CONFIGURE ) ; Node result = ( Node ) Jenkins . XSTREAM2 . fromXML ( source ) ; Jenkins . getInstance ( ) . getNodesObject ( ) . replaceNode ( this . getNode ( ) , result ) ; }
Updates Job by its XML definition .
16,811
public HttpResponse doDoDelete ( ) throws IOException { checkPermission ( DELETE ) ; Node node = getNode ( ) ; if ( node != null ) { Jenkins . getInstance ( ) . removeNode ( node ) ; } else { AbstractCIBase app = Jenkins . getInstance ( ) ; app . removeComputer ( this ) ; } return new HttpRedirect ( ".." ) ; }
Really deletes the agent .
16,812
public void doProgressiveLog ( StaplerRequest req , StaplerResponse rsp ) throws IOException { getLogText ( ) . doProgressText ( req , rsp ) ; }
Handles incremental log .
16,813
public Permalink findNearest ( String id ) { List < String > ids = new ArrayList < > ( ) ; for ( Permalink p : this ) ids . add ( p . getId ( ) ) ; String nearest = EditDistance . findNearest ( id , ids ) ; if ( nearest == null ) return null ; return get ( nearest ) ; }
Finds the closest name match by its ID .
16,814
public static boolean isRelativePath ( String path ) { if ( path . startsWith ( "/" ) ) return false ; if ( path . startsWith ( "\\\\" ) && path . length ( ) > 3 && path . indexOf ( '\\' , 3 ) != - 1 ) return false ; if ( path . length ( ) >= 3 && ':' == path . charAt ( 1 ) ) { char p = path . charAt ( 0 ) ; if ( ( 'A' <= p && p <= 'Z' ) || ( 'a' <= p && p <= 'z' ) ) { return path . charAt ( 2 ) != '\\' && path . charAt ( 2 ) != '/' ; } } return true ; }
A mostly accurate check of whether a path is a relative path or not . This is designed to take a path against an unknown operating system so may give invalid results .
16,815
public static boolean isDescendant ( File forParent , File potentialChild ) throws IOException { Path child = fileToPath ( potentialChild . getAbsoluteFile ( ) ) . normalize ( ) ; Path parent = fileToPath ( forParent . getAbsoluteFile ( ) ) . normalize ( ) ; return child . startsWith ( parent ) ; }
A check if a file path is a descendant of a parent path
16,816
public static File createTempDir ( ) throws IOException { final Path tempPath ; final String tempDirNamePrefix = "jenkins" ; if ( FileSystems . getDefault ( ) . supportedFileAttributeViews ( ) . contains ( "posix" ) ) { tempPath = Files . createTempDirectory ( tempDirNamePrefix , PosixFilePermissions . asFileAttribute ( EnumSet . allOf ( PosixFilePermission . class ) ) ) ; } else { tempPath = Files . createTempDirectory ( tempDirNamePrefix ) ; } return tempPath . toFile ( ) ; }
Creates a new temporary directory .
16,817
public static String getWin32ErrorMessage ( int n ) { try { ResourceBundle rb = ResourceBundle . getBundle ( "/hudson/win32errors" ) ; return rb . getString ( "error" + n ) ; } catch ( MissingResourceException e ) { LOGGER . log ( Level . WARNING , "Failed to find resource bundle" , e ) ; return null ; } }
Gets a human readable message for the given Win32 error code .
16,818
public static String encodeRFC2396 ( String url ) { try { return new URI ( null , url , null ) . toASCIIString ( ) ; } catch ( URISyntaxException e ) { LOGGER . log ( Level . WARNING , "Failed to encode {0}" , url ) ; return url ; } }
Encodes the URL by RFC 2396 .
16,819
public List < SCC < N > > getStronglyConnectedComponents ( ) { final Map < N , Node > nodes = new HashMap < > ( ) ; for ( N n : nodes ( ) ) { nodes . put ( n , new Node ( n ) ) ; } final List < SCC < N > > sccs = new ArrayList < > ( ) ; class Tarjan { int index = 0 ; int sccIndex = 0 ; Stack < Node > pending = new Stack < > ( ) ; void traverse ( ) { for ( Node n : nodes . values ( ) ) { if ( n . index == - 1 ) visit ( n ) ; } } void visit ( Node v ) { v . index = v . lowlink = index ++ ; pending . push ( v ) ; for ( N q : v . edges ( ) ) { Node w = nodes . get ( q ) ; if ( w . index == - 1 ) { visit ( w ) ; v . lowlink = Math . min ( v . lowlink , w . lowlink ) ; } else if ( pending . contains ( w ) ) { v . lowlink = Math . min ( v . lowlink , w . index ) ; } } if ( v . lowlink == v . index ) { SCC < N > scc = new SCC < > ( sccIndex ++ ) ; sccs . add ( scc ) ; Node w ; do { w = pending . pop ( ) ; w . scc = scc ; scc . members . add ( w . n ) ; } while ( w != v ) ; } } } new Tarjan ( ) . traverse ( ) ; Collections . reverse ( sccs ) ; return sccs ; }
Performs the Tarjan s algorithm and computes strongly - connected components from the sink to source order .
16,820
public void setNodes ( final Collection < ? extends Node > nodes ) throws IOException { Queue . withLock ( new Runnable ( ) { public void run ( ) { Set < String > toRemove = new HashSet < > ( Nodes . this . nodes . keySet ( ) ) ; for ( Node n : nodes ) { final String name = n . getNodeName ( ) ; toRemove . remove ( name ) ; Nodes . this . nodes . put ( name , n ) ; } Nodes . this . nodes . keySet ( ) . removeAll ( toRemove ) ; jenkins . updateComputerList ( ) ; jenkins . trimLabels ( ) ; } } ) ; save ( ) ; }
Sets the list of nodes .
16,821
public void addNode ( final Node node ) throws IOException { Node oldNode = nodes . get ( node . getNodeName ( ) ) ; if ( node != oldNode ) { Queue . withLock ( new Runnable ( ) { public void run ( ) { nodes . put ( node . getNodeName ( ) , node ) ; jenkins . updateComputerList ( ) ; jenkins . trimLabels ( ) ; } } ) ; try { persistNode ( node ) ; } catch ( IOException | RuntimeException e ) { Queue . withLock ( new Runnable ( ) { public void run ( ) { nodes . compute ( node . getNodeName ( ) , ( ignoredNodeName , ignoredNode ) -> oldNode ) ; jenkins . updateComputerList ( ) ; jenkins . trimLabels ( ) ; } } ) ; throw e ; } NodeListener . fireOnCreated ( node ) ; } }
Adds a node . If a node of the same name already exists then that node will be replaced .
16,822
private void persistNode ( final Node node ) throws IOException { if ( node instanceof EphemeralNode ) { Util . deleteRecursive ( new File ( getNodesDir ( ) , node . getNodeName ( ) ) ) ; } else { XmlFile xmlFile = new XmlFile ( Jenkins . XSTREAM , new File ( new File ( getNodesDir ( ) , node . getNodeName ( ) ) , "config.xml" ) ) ; xmlFile . write ( node ) ; SaveableListener . fireOnChange ( this , xmlFile ) ; } jenkins . getQueue ( ) . scheduleMaintenance ( ) ; }
Actually persists a node on disk .
16,823
public boolean replaceNode ( final Node oldOne , final Node newOne ) throws IOException { if ( oldOne == nodes . get ( oldOne . getNodeName ( ) ) ) { Queue . withLock ( new Runnable ( ) { public void run ( ) { Nodes . this . nodes . remove ( oldOne . getNodeName ( ) ) ; Nodes . this . nodes . put ( newOne . getNodeName ( ) , newOne ) ; jenkins . updateComputerList ( ) ; jenkins . trimLabels ( ) ; } } ) ; updateNode ( newOne ) ; if ( ! newOne . getNodeName ( ) . equals ( oldOne . getNodeName ( ) ) ) { Util . deleteRecursive ( new File ( getNodesDir ( ) , oldOne . getNodeName ( ) ) ) ; } NodeListener . fireOnUpdated ( oldOne , newOne ) ; return true ; } else { return false ; } }
Replace node of given name .
16,824
public Node getNode ( String name ) { return name == null ? null : nodes . get ( name ) ; }
Returns the named node .
16,825
public void load ( ) throws IOException { final File nodesDir = getNodesDir ( ) ; final File [ ] subdirs = nodesDir . listFiles ( new FileFilter ( ) { public boolean accept ( File child ) { return child . isDirectory ( ) ; } } ) ; final Map < String , Node > newNodes = new TreeMap < > ( ) ; if ( subdirs != null ) { for ( File subdir : subdirs ) { try { XmlFile xmlFile = new XmlFile ( Jenkins . XSTREAM , new File ( subdir , "config.xml" ) ) ; if ( xmlFile . exists ( ) ) { Node node = ( Node ) xmlFile . read ( ) ; newNodes . put ( node . getNodeName ( ) , node ) ; } } catch ( IOException e ) { Logger . getLogger ( Nodes . class . getName ( ) ) . log ( Level . WARNING , "could not load " + subdir , e ) ; } } } Queue . withLock ( new Runnable ( ) { public void run ( ) { nodes . entrySet ( ) . removeIf ( stringNodeEntry -> ! ( stringNodeEntry . getValue ( ) instanceof EphemeralNode ) ) ; nodes . putAll ( newNodes ) ; jenkins . updateComputerList ( ) ; jenkins . trimLabels ( ) ; } } ) ; }
Loads the nodes from disk .
16,826
private File getNodesDir ( ) throws IOException { final File nodesDir = new File ( jenkins . getRootDir ( ) , "nodes" ) ; if ( ! nodesDir . isDirectory ( ) && ! nodesDir . mkdirs ( ) ) { throw new IOException ( String . format ( "Could not mkdirs %s" , nodesDir ) ) ; } return nodesDir ; }
Returns the directory that the nodes are stored in .
16,827
public String getFormattedDescription ( ) { try { return Jenkins . getInstance ( ) . getMarkupFormatter ( ) . translate ( description ) ; } catch ( IOException e ) { LOGGER . warning ( "failed to translate description using configured markup formatter" ) ; return "" ; } }
return parameter description applying the configured MarkupFormatter for jenkins instance .
16,828
public ParameterValue createValue ( CLICommand command , String value ) throws IOException , InterruptedException { throw new AbortException ( "CLI parameter submission is not supported for the " + getClass ( ) + " type. Please file a bug report for this" ) ; }
Create a parameter value from the string given in the CLI .
16,829
public static String toNameList ( Collection < ? extends Item > items ) { StringBuilder buf = new StringBuilder ( ) ; for ( Item item : items ) { if ( buf . length ( ) > 0 ) buf . append ( ", " ) ; buf . append ( item . getFullName ( ) ) ; } return buf . toString ( ) ; }
Converts a list of items into a comma - separated list of full names .
16,830
public static Method getPublicMethodNamed ( Class c , String methodName ) { for ( Method m : c . getMethods ( ) ) if ( m . getName ( ) . equals ( methodName ) ) return m ; return null ; }
Finds a public method of the given name regardless of its parameter definitions
16,831
public static boolean isDefaultJDKValid ( Node n ) { try { TaskListener listener = new StreamTaskListener ( new NullStream ( ) ) ; Launcher launcher = n . createLauncher ( listener ) ; return launcher . launch ( ) . cmds ( "java" , "-fullversion" ) . stdout ( listener ) . join ( ) == 0 ; } catch ( IOException | InterruptedException e ) { return false ; } }
Checks if java is in PATH on the given node .
16,832
public MarkupText . SubText findToken ( Pattern pattern ) { String text = getText ( ) ; Matcher m = pattern . matcher ( text ) ; if ( m . find ( ) ) return createSubText ( m ) ; return null ; }
Find the first occurrence of the given pattern in this text or null .
16,833
public List < MarkupText . SubText > findTokens ( Pattern pattern ) { String text = getText ( ) ; Matcher m = pattern . matcher ( text ) ; List < SubText > r = new ArrayList < > ( ) ; while ( m . find ( ) ) { int idx = m . start ( ) ; if ( idx > 0 ) { char ch = text . charAt ( idx - 1 ) ; if ( Character . isLetter ( ch ) || Character . isDigit ( ch ) ) continue ; } idx = m . end ( ) ; if ( idx < text . length ( ) ) { char ch = text . charAt ( idx ) ; if ( Character . isLetter ( ch ) || Character . isDigit ( ch ) ) continue ; } r . add ( createSubText ( m ) ) ; } return r ; }
Find all tokens that match the given pattern in this text .
16,834
public static int waitForExitProcess ( Pointer hProcess ) throws InterruptedException { while ( true ) { if ( Thread . interrupted ( ) ) throw new InterruptedException ( ) ; Kernel32 . INSTANCE . WaitForSingleObject ( hProcess , 1000 ) ; IntByReference exitCode = new IntByReference ( ) ; exitCode . setValue ( - 1 ) ; Kernel32 . INSTANCE . GetExitCodeProcess ( hProcess , exitCode ) ; int v = exitCode . getValue ( ) ; if ( v != Kernel32 . STILL_ACTIVE ) { return v ; } } }
Given the process handle waits for its completion and returns the exit code .
16,835
@ Restricted ( NoExternalUse . class ) public HttpResponse doCreateAdminUser ( StaplerRequest req , StaplerResponse rsp ) throws IOException { Jenkins j = Jenkins . getInstance ( ) ; j . checkPermission ( Jenkins . ADMINISTER ) ; HudsonPrivateSecurityRealm securityRealm = ( HudsonPrivateSecurityRealm ) j . getSecurityRealm ( ) ; User admin = securityRealm . getUser ( SetupWizard . initialSetupAdminUserName ) ; try { if ( admin != null ) { admin . delete ( ) ; } User newUser = securityRealm . createAccountFromSetupWizard ( req ) ; if ( admin != null ) { admin = null ; } try { getInitialAdminPasswordFile ( ) . delete ( ) ; } catch ( InterruptedException e ) { throw new IOException ( e ) ; } InstallUtil . proceedToNextStateFrom ( InstallState . CREATE_ADMIN_USER ) ; Authentication auth = new UsernamePasswordAuthenticationToken ( newUser . getId ( ) , req . getParameter ( "password1" ) ) ; auth = securityRealm . getSecurityComponents ( ) . manager . authenticate ( auth ) ; SecurityContextHolder . getContext ( ) . setAuthentication ( auth ) ; HttpSession session = req . getSession ( false ) ; if ( session != null ) { session . invalidate ( ) ; } HttpSession newSession = req . getSession ( true ) ; UserSeedProperty userSeed = newUser . getProperty ( UserSeedProperty . class ) ; String sessionSeed = userSeed . getSeed ( ) ; newSession . setAttribute ( UserSeedProperty . USER_SESSION_SEED , sessionSeed ) ; CrumbIssuer crumbIssuer = Jenkins . getInstance ( ) . getCrumbIssuer ( ) ; JSONObject data = new JSONObject ( ) ; if ( crumbIssuer != null ) { data . accumulate ( "crumbRequestField" , crumbIssuer . getCrumbRequestField ( ) ) . accumulate ( "crumb" , crumbIssuer . getCrumb ( req ) ) ; } return HttpResponses . okJSON ( data ) ; } catch ( AccountCreationFailedException e ) { rsp . setStatus ( 422 ) ; return HttpResponses . forwardToView ( securityRealm , "/jenkins/install/SetupWizard/setupWizardFirstUser.jelly" ) ; } finally { if ( admin != null ) { admin . save ( ) ; } } }
Called during the initial setup to create an admin user
16,836
@ Restricted ( DoNotUse . class ) public HttpResponse doPlatformPluginList ( ) throws IOException { SetupWizard setupWizard = Jenkins . get ( ) . getSetupWizard ( ) ; if ( setupWizard != null ) { if ( InstallState . UPGRADE . equals ( Jenkins . get ( ) . getInstallState ( ) ) ) { JSONArray initialPluginData = getPlatformPluginUpdates ( ) ; if ( initialPluginData != null ) { return HttpResponses . okJSON ( initialPluginData ) ; } } else { JSONArray initialPluginData = getPlatformPluginList ( ) ; if ( initialPluginData != null ) { return HttpResponses . okJSON ( initialPluginData ) ; } } } return HttpResponses . okJSON ( ) ; }
Returns the initial plugin list in JSON format
16,837
public JSONArray getPlatformPluginUpdates ( ) { final VersionNumber version = getCurrentLevel ( ) ; if ( version == null ) { return null ; } return getPlatformPluginsForUpdate ( version , Jenkins . getVersion ( ) ) ; }
Provides the list of platform plugin updates from the last time the upgrade was run .
16,838
public InstallState getInstallState ( String name ) { if ( name == null ) { return null ; } return InstallState . valueOf ( name ) ; }
Returns an installState by name
16,839
private ReactorListener buildReactorListener ( ) throws IOException { List < ReactorListener > r = Lists . newArrayList ( ServiceLoader . load ( InitReactorListener . class , Thread . currentThread ( ) . getContextClassLoader ( ) ) ) ; r . add ( new ReactorListener ( ) { final Level level = Level . parse ( Configuration . getStringConfigParameter ( "initLogLevel" , "FINE" ) ) ; public void onTaskStarted ( Task t ) { LOGGER . log ( level , "Started {0}" , getDisplayName ( t ) ) ; } public void onTaskCompleted ( Task t ) { LOGGER . log ( level , "Completed {0}" , getDisplayName ( t ) ) ; } public void onTaskFailed ( Task t , Throwable err , boolean fatal ) { LOGGER . log ( SEVERE , "Failed " + getDisplayName ( t ) , err ) ; } public void onAttained ( Milestone milestone ) { Level lv = level ; String s = "Attained " + milestone . toString ( ) ; if ( milestone instanceof InitMilestone ) { lv = Level . INFO ; onInitMilestoneAttained ( ( InitMilestone ) milestone ) ; s = milestone . toString ( ) ; } LOGGER . log ( lv , s ) ; } } ) ; return new ReactorListener . Aggregator ( r ) ; }
Aggregates all the listeners into one and returns it .
16,840
public static String unprotect ( String data ) { if ( data == null ) return null ; try { Cipher cipher = Secret . getCipher ( ALGORITHM ) ; cipher . init ( Cipher . DECRYPT_MODE , DES_KEY ) ; String plainText = new String ( cipher . doFinal ( Base64 . getDecoder ( ) . decode ( data . getBytes ( StandardCharsets . UTF_8 ) ) ) , StandardCharsets . UTF_8 ) ; if ( plainText . endsWith ( MAGIC ) ) return plainText . substring ( 0 , plainText . length ( ) - 3 ) ; return null ; } catch ( GeneralSecurityException | IllegalArgumentException e ) { return null ; } }
Returns null if fails to decrypt properly .
16,841
static synchronized void clearTLDOverrides ( ) { inUse = false ; countryCodeTLDsPlus = MemoryReductionUtil . EMPTY_STRING_ARRAY ; countryCodeTLDsMinus = MemoryReductionUtil . EMPTY_STRING_ARRAY ; genericTLDsPlus = MemoryReductionUtil . EMPTY_STRING_ARRAY ; genericTLDsMinus = MemoryReductionUtil . EMPTY_STRING_ARRAY ; }
For use by unit test code only
16,842
public static String [ ] getTLDEntries ( DomainValidator . ArrayType table ) { final String [ ] array ; switch ( table ) { case COUNTRY_CODE_MINUS : array = countryCodeTLDsMinus ; break ; case COUNTRY_CODE_PLUS : array = countryCodeTLDsPlus ; break ; case GENERIC_MINUS : array = genericTLDsMinus ; break ; case GENERIC_PLUS : array = genericTLDsPlus ; break ; case GENERIC_RO : array = GENERIC_TLDS ; break ; case COUNTRY_CODE_RO : array = COUNTRY_CODE_TLDS ; break ; case INFRASTRUCTURE_RO : array = INFRASTRUCTURE_TLDS ; break ; case LOCAL_RO : array = LOCAL_TLDS ; break ; default : throw new IllegalArgumentException ( "Unexpected enum value: " + table ) ; } return Arrays . copyOf ( array , array . length ) ; }
Get a copy of the internal array .
16,843
public AnnotatedLargeText obtainLog ( ) { WeakReference < AnnotatedLargeText > l = log ; if ( l == null ) return null ; return l . get ( ) ; }
Obtains the log file .
16,844
public void doProgressiveLog ( StaplerRequest req , StaplerResponse rsp ) throws IOException { AnnotatedLargeText text = obtainLog ( ) ; if ( text != null ) { text . doProgressText ( req , rsp ) ; return ; } rsp . setStatus ( HttpServletResponse . SC_OK ) ; }
Handles incremental log output .
16,845
public synchronized void doClearError ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { getACL ( ) . checkPermission ( getPermission ( ) ) ; if ( workerThread != null && ! workerThread . isRunning ( ) ) workerThread = null ; rsp . sendRedirect ( "." ) ; }
Clears the error status .
16,846
public Class < ? > type ( ) { Type type = Types . getBaseClass ( getClass ( ) , ConsoleAnnotatorFactory . class ) ; if ( type instanceof ParameterizedType ) return Types . erasure ( Types . getTypeArgument ( type , 0 ) ) ; else return Object . class ; }
For which context type does this annotator work?
16,847
public static ExtensionComponentSet union ( final Collection < ? extends ExtensionComponentSet > base ) { return new ExtensionComponentSet ( ) { public < T > Collection < ExtensionComponent < T > > find ( Class < T > type ) { List < ExtensionComponent < T > > r = Lists . newArrayList ( ) ; for ( ExtensionComponentSet d : base ) r . addAll ( d . find ( type ) ) ; return r ; } } ; }
Computes the union of all the given delta .
16,848
public Iterator < R > iterator ( ) { return new Iterator < R > ( ) { R last = null ; R next = newestBuild ( ) ; public boolean hasNext ( ) { return next != null ; } public R next ( ) { last = next ; if ( last != null ) next = last . getPreviousBuild ( ) ; else throw new NoSuchElementException ( ) ; return last ; } public void remove ( ) { if ( last == null ) throw new UnsupportedOperationException ( ) ; removeValue ( last ) ; } } ; }
Walks through builds newer ones first .
16,849
protected boolean isValidQuery ( String query ) { if ( query == null ) { return true ; } return QUERY_PATTERN . matcher ( query ) . matches ( ) ; }
Returns true if the query is null or it s a properly formatted query string .
16,850
public static < V , T extends Throwable > V execute ( TaskListener listener , String rootUsername , String rootPassword , final Callable < V , T > closure ) throws T , IOException , InterruptedException { VirtualChannel ch = start ( listener , rootUsername , rootPassword ) ; try { return ch . call ( closure ) ; } finally { ch . close ( ) ; ch . join ( 3000 ) ; } }
Starts a new privilege - escalated environment execute a closure and shut it down .
16,851
public synchronized void download ( StaplerRequest req , StaplerResponse rsp ) throws InterruptedException , IOException { rsp . setStatus ( HttpServletResponse . SC_OK ) ; rsp . addHeader ( "Transfer-Encoding" , "chunked" ) ; OutputStream out = rsp . getOutputStream ( ) ; if ( DIY_CHUNKING ) { out = new ChunkedOutputStream ( out ) ; } out . write ( 0 ) ; out . flush ( ) ; { long end = System . currentTimeMillis ( ) + CONNECTION_TIMEOUT ; while ( upload == null && System . currentTimeMillis ( ) < end ) { LOGGER . log ( Level . FINE , "Waiting for upload stream for {0}: {1}" , new Object [ ] { uuid , this } ) ; wait ( 1000 ) ; } if ( upload == null ) { throw new IOException ( "HTTP full-duplex channel timeout: " + uuid ) ; } LOGGER . log ( Level . FINE , "Received upload stream {0} for {1}: {2}" , new Object [ ] { upload , uuid , this } ) ; } try { run ( upload , out ) ; } finally { completed = true ; notify ( ) ; } }
This is where we send the data to the client .
16,852
public synchronized void upload ( StaplerRequest req , StaplerResponse rsp ) throws InterruptedException , IOException { rsp . setStatus ( HttpServletResponse . SC_OK ) ; InputStream in = req . getInputStream ( ) ; if ( DIY_CHUNKING ) { in = new ChunkedInputStream ( in ) ; } upload = in ; LOGGER . log ( Level . FINE , "Recording upload stream {0} for {1}: {2}" , new Object [ ] { upload , uuid , this } ) ; notify ( ) ; while ( ! completed ) { wait ( ) ; } }
This is where we receive inputs from the client .
16,853
public static void register ( ) { if ( Main . isUnitTest && JENKINS_LOC == null ) { mockOff ( ) ; return ; } ClassFilter . setDefault ( new ClassFilterImpl ( ) ) ; if ( SUPPRESS_ALL ) { LOGGER . warning ( "All class filtering suppressed. Your Jenkins installation is at risk from known attacks. See https://jenkins.io/redirect/class-filter/" ) ; } else if ( SUPPRESS_WHITELIST ) { LOGGER . warning ( "JEP-200 class filtering by whitelist suppressed. Your Jenkins installation may be at risk. See https://jenkins.io/redirect/class-filter/" ) ; } }
Register this implementation as the default in the system .
16,854
public boolean isValidInet4Address ( String inet4Address ) { String [ ] groups = ipv4Validator . match ( inet4Address ) ; if ( groups == null ) { return false ; } for ( String ipSegment : groups ) { if ( ipSegment == null || ipSegment . length ( ) == 0 ) { return false ; } int iIpSegment = 0 ; try { iIpSegment = Integer . parseInt ( ipSegment ) ; } catch ( NumberFormatException e ) { return false ; } if ( iIpSegment > IPV4_MAX_OCTET_VALUE ) { return false ; } if ( ipSegment . length ( ) > 1 && ipSegment . startsWith ( "0" ) ) { return false ; } } return true ; }
Validates an IPv4 address . Returns true if valid .
16,855
public static void report ( Saveable obj , String version ) { OldDataMonitor odm = get ( Jenkins . getInstance ( ) ) ; try { SaveableReference ref = referTo ( obj ) ; while ( true ) { VersionRange vr = odm . data . get ( ref ) ; if ( vr != null && odm . data . replace ( ref , vr , new VersionRange ( vr , version , null ) ) ) { break ; } else if ( odm . data . putIfAbsent ( ref , new VersionRange ( null , version , null ) ) == null ) { break ; } } } catch ( IllegalArgumentException ex ) { LOGGER . log ( Level . WARNING , "Bad parameter given to OldDataMonitor" , ex ) ; } }
Inform monitor that some data in a deprecated format has been loaded and converted in - memory to a new structure .
16,856
public static void report ( UnmarshallingContext context , String version ) { RobustReflectionConverter . addErrorInContext ( context , new ReportException ( version ) ) ; }
Inform monitor that some data in a deprecated format has been loaded during XStream unmarshalling when the Saveable containing this object is not available .
16,857
public static void report ( Saveable obj , Collection < Throwable > errors ) { StringBuilder buf = new StringBuilder ( ) ; int i = 0 ; for ( Throwable e : errors ) { if ( e instanceof ReportException ) { report ( obj , ( ( ReportException ) e ) . version ) ; } else { if ( ++ i > 1 ) buf . append ( ", " ) ; buf . append ( e . getClass ( ) . getSimpleName ( ) ) . append ( ": " ) . append ( e . getMessage ( ) ) ; } } if ( buf . length ( ) == 0 ) return ; Jenkins j = Jenkins . getInstanceOrNull ( ) ; if ( j == null ) { for ( Throwable t : errors ) { LOGGER . log ( Level . WARNING , "could not read " + obj + " (and Jenkins did not start up)" , t ) ; } return ; } OldDataMonitor odm = get ( j ) ; SaveableReference ref = referTo ( obj ) ; while ( true ) { VersionRange vr = odm . data . get ( ref ) ; if ( vr != null && odm . data . replace ( ref , vr , new VersionRange ( vr , null , buf . toString ( ) ) ) ) { break ; } else if ( odm . data . putIfAbsent ( ref , new VersionRange ( null , null , buf . toString ( ) ) ) == null ) { break ; } } }
Inform monitor that some unreadable data was found while loading .
16,858
@ Restricted ( NoExternalUse . class ) public Iterator < VersionNumber > getVersionList ( ) { TreeSet < VersionNumber > set = new TreeSet < VersionNumber > ( ) ; for ( VersionRange vr : data . values ( ) ) { if ( vr . max != null ) { set . add ( vr . max ) ; } } return set . iterator ( ) ; }
Sorted list of unique max - versions in the data set . For select list in jelly .
16,859
public HttpResponse doUpgrade ( StaplerRequest req , StaplerResponse rsp ) { final String thruVerParam = req . getParameter ( "thruVer" ) ; final VersionNumber thruVer = thruVerParam . equals ( "all" ) ? null : new VersionNumber ( thruVerParam ) ; saveAndRemoveEntries ( new Predicate < Map . Entry < SaveableReference , VersionRange > > ( ) { public boolean apply ( Map . Entry < SaveableReference , VersionRange > entry ) { VersionNumber version = entry . getValue ( ) . max ; return version != null && ( thruVer == null || ! version . isNewerThan ( thruVer ) ) ; } } ) ; return HttpResponses . forwardToPreviousPage ( ) ; }
Save all or some of the files to persist data in the new forms . Remove those items from the data map .
16,860
public void doLogout ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { HttpSession session = req . getSession ( false ) ; if ( session != null ) session . invalidate ( ) ; Authentication auth = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; SecurityContextHolder . clearContext ( ) ; Cookie cookie = new Cookie ( ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY , "" ) ; cookie . setMaxAge ( 0 ) ; cookie . setSecure ( req . isSecure ( ) ) ; cookie . setHttpOnly ( true ) ; cookie . setPath ( req . getContextPath ( ) . length ( ) > 0 ? req . getContextPath ( ) : "/" ) ; rsp . addCookie ( cookie ) ; rsp . sendRedirect2 ( getPostLogOutUrl ( req , auth ) ) ; }
Handles the logout processing .
16,861
public final void doCaptcha ( StaplerRequest req , StaplerResponse rsp ) throws IOException { if ( captchaSupport != null ) { String id = req . getSession ( ) . getId ( ) ; rsp . setContentType ( "image/png" ) ; rsp . setHeader ( "Cache-Control" , "no-cache, no-store, must-revalidate" ) ; rsp . setHeader ( "Pragma" , "no-cache" ) ; rsp . setHeader ( "Expires" , "0" ) ; captchaSupport . generateImage ( id , rsp . getOutputStream ( ) ) ; } }
Generates a captcha image .
16,862
protected final boolean validateCaptcha ( String text ) { if ( captchaSupport != null ) { String id = Stapler . getCurrentRequest ( ) . getSession ( ) . getId ( ) ; return captchaSupport . validateCaptcha ( id , text ) ; } return true ; }
Validates the captcha .
16,863
@ Restricted ( DoNotUse . class ) public static String getFrom ( ) { String from = null , returnValue = null ; final StaplerRequest request = Stapler . getCurrentRequest ( ) ; if ( request != null && request . getSession ( false ) != null ) { from = ( String ) request . getSession ( ) . getAttribute ( "from" ) ; } else if ( request != null ) { from = request . getParameter ( "from" ) ; } if ( from == null && request != null && request . getRequestURI ( ) != null && ! request . getRequestURI ( ) . equals ( "/loginError" ) && ! request . getRequestURI ( ) . equals ( "/login" ) ) { from = request . getRequestURI ( ) ; } from = StringUtils . defaultIfBlank ( from , "/" ) . trim ( ) ; try { returnValue = java . net . URLEncoder . encode ( from , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { } return StringUtils . isBlank ( returnValue ) ? "/" : returnValue ; }
Perform a calculation where we should go back after successful login
16,864
public static HttpResponseException success ( final String destination ) { return new HttpResponseException ( ) { public void generateResponse ( StaplerRequest req , StaplerResponse rsp , Object node ) throws IOException , ServletException { if ( isApply ( req ) ) { applyResponse ( "notificationBar.show('" + Messages . HttpResponses_Saved ( ) + "',notificationBar.OK)" ) . generateResponse ( req , rsp , node ) ; } else { rsp . sendRedirect ( destination ) ; } } } ; }
Generates the response for the form submission in such a way that it handles the apply button correctly .
16,865
public boolean isContainedBy ( PermissionScope s ) { if ( this == s ) return true ; for ( PermissionScope c : containers ) { if ( c . isContainedBy ( s ) ) return true ; } return false ; }
Returns true if this scope is directly or indirectly contained by the given scope .
16,866
public int available ( ) throws IOException { if ( this . entrySize - this . entryOffset > Integer . MAX_VALUE ) { return Integer . MAX_VALUE ; } return ( int ) ( this . entrySize - this . entryOffset ) ; }
Get the available data that can be read from the current entry in the archive . This does not indicate how much data is left in the entire archive only in the current entry . This value is determined from the entry s size header field and the amount of data already read from the current entry . Integer . MAX_VALUE is returned in case more than Integer . MAX_VALUE bytes are left in the current entry in the archive .
16,867
public int read ( byte [ ] buf , int offset , int numToRead ) throws IOException { int totalRead = 0 ; if ( this . entryOffset >= this . entrySize ) { return - 1 ; } if ( ( numToRead + this . entryOffset ) > this . entrySize ) { numToRead = ( int ) ( this . entrySize - this . entryOffset ) ; } if ( this . readBuf != null ) { int sz = ( numToRead > this . readBuf . length ) ? this . readBuf . length : numToRead ; System . arraycopy ( this . readBuf , 0 , buf , offset , sz ) ; if ( sz >= this . readBuf . length ) { this . readBuf = null ; } else { int newLen = this . readBuf . length - sz ; byte [ ] newBuf = new byte [ newLen ] ; System . arraycopy ( this . readBuf , sz , newBuf , 0 , newLen ) ; this . readBuf = newBuf ; } totalRead += sz ; numToRead -= sz ; offset += sz ; } while ( numToRead > 0 ) { byte [ ] rec = this . buffer . readRecord ( ) ; if ( rec == null ) { throw new IOException ( "unexpected EOF with " + numToRead + " bytes unread" ) ; } int sz = numToRead ; int recLen = rec . length ; if ( recLen > sz ) { System . arraycopy ( rec , 0 , buf , offset , sz ) ; this . readBuf = new byte [ recLen - sz ] ; System . arraycopy ( rec , sz , this . readBuf , 0 , recLen - sz ) ; } else { sz = recLen ; System . arraycopy ( rec , 0 , buf , offset , recLen ) ; } totalRead += sz ; numToRead -= sz ; offset += sz ; } this . entryOffset += totalRead ; return totalRead ; }
Reads bytes from the current tar archive entry .
16,868
public void copyEntryContents ( OutputStream out ) throws IOException { byte [ ] buf = new byte [ 32 * 1024 ] ; while ( true ) { int numRead = this . read ( buf , 0 , buf . length ) ; if ( numRead == - 1 ) { break ; } out . write ( buf , 0 , numRead ) ; } }
Copies the contents of the current tar archive entry directly into an output stream .
16,869
public String getId ( ) { Jenkins h = Jenkins . getInstance ( ) ; String contextPath = "" ; try { Method m = ServletContext . class . getMethod ( "getContextPath" ) ; contextPath = " contextPath=\"" + m . invoke ( h . servletContext ) + "\"" ; } catch ( Exception e ) { } return h . hashCode ( ) + contextPath + " at " + ManagementFactory . getRuntimeMXBean ( ) . getName ( ) ; }
Figures out a string that identifies this instance of Hudson .
16,870
public void schedule ( ) { long MINUTE = 1000 * 60 ; Timer . get ( ) . schedule ( new SafeTimerTask ( ) { protected void doRun ( ) { execute ( ) ; } } , ( random . nextInt ( 30 ) + 60 ) * MINUTE , TimeUnit . MILLISECONDS ) ; }
Schedules the next execution .
16,871
public void doDynamic ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { rsp . setStatus ( SC_INTERNAL_SERVER_ERROR ) ; req . getView ( this , "index.jelly" ) . forward ( req , rsp ) ; }
Serve all URLs with the index view .
16,872
public void doIgnore ( StaplerRequest req , StaplerResponse rsp ) throws IOException { ignore = true ; Jenkins . getInstance ( ) . servletContext . setAttribute ( "app" , Jenkins . getInstance ( ) ) ; rsp . sendRedirect2 ( req . getContextPath ( ) + '/' ) ; }
Ignore the problem and go back to using Hudson .
16,873
public String getIconUrl ( String size ) { if ( iconUrl == null ) { return Jenkins . RESOURCE_PATH + "/images/" + size + "/" + HEALTH_UNKNOWN_IMG ; } if ( iconUrl . startsWith ( "/" ) ) { return iconUrl . replace ( "/32x32/" , "/" + size + "/" ) ; } return Jenkins . RESOURCE_PATH + "/images/" + size + "/" + iconUrl ; }
Get s the iconUrl relative to the hudson root url for the correct size .
16,874
public static HealthReport min ( HealthReport a , HealthReport b ) { if ( a == null && b == null ) return null ; if ( a == null ) return b ; if ( b == null ) return a ; if ( a . compareTo ( b ) <= 0 ) return a ; return b ; }
Utility method to find the report with the lowest health .
16,875
public static HealthReport max ( HealthReport a , HealthReport b ) { if ( a == null && b == null ) return null ; if ( a == null ) return b ; if ( b == null ) return a ; if ( a . compareTo ( b ) >= 0 ) return a ; return b ; }
Utility method to find the report with the highest health .
16,876
public void load ( ) throws IOException { logRecorders . clear ( ) ; File dir = configDir ( ) ; File [ ] files = dir . listFiles ( ( FileFilter ) new WildcardFileFilter ( "*.xml" ) ) ; if ( files == null ) return ; for ( File child : files ) { String name = child . getName ( ) ; name = name . substring ( 0 , name . length ( ) - 4 ) ; LogRecorder lr = new LogRecorder ( name ) ; lr . load ( ) ; logRecorders . put ( name , lr ) ; } }
Loads the configuration from disk .
16,877
public < T > void putComputationalData ( Class < T > key , T value ) { this . computationalData . put ( key , value ) ; }
Adds data which is useful for the time when the dependency graph is built up . All this data will be cleaned once the dependency graph creation has finished .
16,878
public < T > T getComputationalData ( Class < T > key ) { @ SuppressWarnings ( "unchecked" ) T result = ( T ) this . computationalData . get ( key ) ; return result ; }
Gets temporary data which is needed for building up the dependency graph .
16,879
public Iterable < HistoryPageEntry < T > > getRenderList ( ) { if ( trimmed ) { List < HistoryPageEntry < T > > pageEntries = toPageEntries ( baseList ) ; if ( pageEntries . size ( ) > THRESHOLD ) { return updateFirstTransientBuildKey ( pageEntries . subList ( 0 , THRESHOLD ) ) ; } else { trimmed = false ; return updateFirstTransientBuildKey ( pageEntries ) ; } } else { return updateFirstTransientBuildKey ( toPageEntries ( baseList ) ) ; } }
The records to be rendered this time .
16,880
public void doAjax ( StaplerRequest req , StaplerResponse rsp , @ Header ( "n" ) String n ) throws IOException , ServletException { rsp . setContentType ( "text/html;charset=UTF-8" ) ; List < T > items = new ArrayList < > ( ) ; if ( n != null ) { String nn = null ; for ( T t : baseList ) { if ( adapter . compare ( t , n ) >= 0 ) { items . add ( t ) ; if ( adapter . isBuilding ( t ) ) nn = adapter . getKey ( t ) ; } else break ; } if ( nn == null ) { if ( items . isEmpty ( ) ) { nn = n ; } else { nn = adapter . getNextKey ( adapter . getKey ( items . get ( 0 ) ) ) ; } } baseList = items ; rsp . setHeader ( "n" , nn ) ; firstTransientBuildKey = nn ; } HistoryPageFilter page = getHistoryPageFilter ( ) ; req . getView ( page , "ajaxBuildHistory.jelly" ) . forward ( req , rsp ) ; }
Handles AJAX requests from browsers to update build history .
16,881
private void recordBootAttempt ( File home ) { try ( OutputStream o = Files . newOutputStream ( BootFailure . getBootFailureFile ( home ) . toPath ( ) , StandardOpenOption . CREATE , StandardOpenOption . APPEND ) ) { o . write ( ( new Date ( ) . toString ( ) + System . getProperty ( "line.separator" , "\n" ) ) . toString ( ) . getBytes ( ) ) ; } catch ( IOException | InvalidPathException e ) { LOGGER . log ( WARNING , "Failed to record boot attempts" , e ) ; } }
To assist boot failure script record the number of boot attempts . This file gets deleted in case of successful boot .
16,882
@ edu . umd . cs . findbugs . annotations . SuppressFBWarnings ( "LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE" ) private void installLogger ( ) { Jenkins . logRecords = handler . getView ( ) ; Logger . getLogger ( "" ) . addHandler ( handler ) ; }
Installs log handler to monitor all Hudson logs .
16,883
public FileAndDescription getHomeDir ( ServletContextEvent event ) { for ( String name : HOME_NAMES ) { try { InitialContext iniCtxt = new InitialContext ( ) ; Context env = ( Context ) iniCtxt . lookup ( "java:comp/env" ) ; String value = ( String ) env . lookup ( name ) ; if ( value != null && value . trim ( ) . length ( ) > 0 ) return new FileAndDescription ( new File ( value . trim ( ) ) , "JNDI/java:comp/env/" + name ) ; value = ( String ) iniCtxt . lookup ( name ) ; if ( value != null && value . trim ( ) . length ( ) > 0 ) return new FileAndDescription ( new File ( value . trim ( ) ) , "JNDI/" + name ) ; } catch ( NamingException e ) { } } for ( String name : HOME_NAMES ) { String sysProp = SystemProperties . getString ( name ) ; if ( sysProp != null ) return new FileAndDescription ( new File ( sysProp . trim ( ) ) , "SystemProperties.getProperty(\"" + name + "\")" ) ; } for ( String name : HOME_NAMES ) { String env = EnvVars . masterEnvVars . get ( name ) ; if ( env != null ) return new FileAndDescription ( new File ( env . trim ( ) ) . getAbsoluteFile ( ) , "EnvVars.masterEnvVars.get(\"" + name + "\")" ) ; } String root = event . getServletContext ( ) . getRealPath ( "/WEB-INF/workspace" ) ; if ( root != null ) { File ws = new File ( root . trim ( ) ) ; if ( ws . exists ( ) ) return new FileAndDescription ( ws , "getServletContext().getRealPath(\"/WEB-INF/workspace\")" ) ; } File legacyHome = new File ( new File ( System . getProperty ( "user.home" ) ) , ".hudson" ) ; if ( legacyHome . exists ( ) ) { return new FileAndDescription ( legacyHome , "$user.home/.hudson" ) ; } File newHome = new File ( new File ( System . getProperty ( "user.home" ) ) , ".jenkins" ) ; return new FileAndDescription ( newHome , "$user.home/.jenkins" ) ; }
Determines the home directory for Jenkins .
16,884
public String substitute ( AbstractBuild < ? , ? > build , String text ) { return Util . replaceMacro ( text , createVariableResolver ( build ) ) ; }
Performs a variable substitution to the given text and return it .
16,885
public boolean shouldSchedule ( List < Action > actions ) { List < ParametersAction > others = Util . filter ( actions , ParametersAction . class ) ; if ( others . isEmpty ( ) ) { return ! parameters . isEmpty ( ) ; } else { Set < ParameterValue > params = new HashSet < > ( ) ; for ( ParametersAction other : others ) { params . addAll ( other . parameters ) ; } return ! params . equals ( new HashSet < > ( this . parameters ) ) ; } }
Allow an other build of the same project to be scheduled if it has other parameters .
16,886
boolean isUnix ( ) { if ( ! isRemote ( ) ) return File . pathSeparatorChar != ';' ; if ( remote . length ( ) > 3 && remote . charAt ( 1 ) == ':' && remote . charAt ( 2 ) == '\\' ) return false ; return ! remote . contains ( "\\" ) ; }
Checks if the remote path is Unix .
16,887
public void zip ( OutputStream os , FileFilter filter ) throws IOException , InterruptedException { archive ( ArchiverFactory . ZIP , os , filter ) ; }
Creates a zip file from this directory by using the specified filter and sends the result to the given output stream .
16,888
public int zip ( OutputStream out , DirScanner scanner ) throws IOException , InterruptedException { return archive ( ArchiverFactory . ZIP , out , scanner ) ; }
Uses the given scanner on this directory to list up files and then archive it to a zip stream .
16,889
public void unzipFrom ( InputStream _in ) throws IOException , InterruptedException { final InputStream in = new RemoteInputStream ( _in , Flag . GREEDY ) ; act ( new UnzipFrom ( in ) ) ; }
Reads the given InputStream as a zip file and extracts it into this directory .
16,890
public void symlinkTo ( final String target , final TaskListener listener ) throws IOException , InterruptedException { act ( new SymlinkTo ( target , listener ) ) ; }
Creates a symlink to the specified target .
16,891
public void untarFrom ( InputStream _in , final TarCompression compression ) throws IOException , InterruptedException { try { final InputStream in = new RemoteInputStream ( _in , Flag . GREEDY ) ; act ( new UntarFrom ( compression , in ) ) ; } finally { _in . close ( ) ; } }
Reads the given InputStream as a tar file and extracts it into this directory .
16,892
public String getBaseName ( ) { String n = getName ( ) ; int idx = n . lastIndexOf ( '.' ) ; if ( idx < 0 ) return n ; return n . substring ( 0 , idx ) ; }
Gets the file name portion except the extension .
16,893
public String getName ( ) { String r = remote ; if ( r . endsWith ( "\\" ) || r . endsWith ( "/" ) ) r = r . substring ( 0 , r . length ( ) - 1 ) ; int len = r . length ( ) - 1 ; while ( len >= 0 ) { char ch = r . charAt ( len ) ; if ( ch == '\\' || ch == '/' ) break ; len -- ; } return r . substring ( len + 1 ) ; }
Gets just the file name portion without directories .
16,894
public FilePath getParent ( ) { int i = remote . length ( ) - 2 ; for ( ; i >= 0 ; i -- ) { char ch = remote . charAt ( i ) ; if ( ch == '\\' || ch == '/' ) break ; } return i >= 0 ? new FilePath ( channel , remote . substring ( 0 , i + 1 ) ) : null ; }
Gets the parent file .
16,895
public FilePath createTempDir ( final String prefix , final String suffix ) throws IOException , InterruptedException { try { String [ ] s ; if ( StringUtils . isBlank ( suffix ) ) { s = new String [ ] { prefix , "tmp" } ; } else { s = new String [ ] { prefix , suffix } ; } String name = StringUtils . join ( s , "." ) ; return new FilePath ( this , act ( new CreateTempDir ( name ) ) ) ; } catch ( IOException e ) { throw new IOException ( "Failed to create a temp directory on " + remote , e ) ; } }
Creates a temporary directory inside the directory represented by this
16,896
private static void _chmod ( File f , int mask ) throws IOException { if ( File . pathSeparatorChar == ';' ) return ; if ( Util . NATIVE_CHMOD_MODE ) { PosixAPI . jnr ( ) . chmod ( f . getAbsolutePath ( ) , mask ) ; } else { Files . setPosixFilePermissions ( fileToPath ( f ) , Util . modeToPermissions ( mask ) ) ; } }
Change permissions via NIO .
16,897
public synchronized void updateNextBuildNumber ( int next ) throws IOException { RunT lb = getLastBuild ( ) ; if ( lb != null ? next > lb . getNumber ( ) : next > 0 ) { this . nextBuildNumber = next ; saveNextBuildNumber ( ) ; } }
Programatically updates the next build number .
16,898
public void logRotate ( ) throws IOException , InterruptedException { BuildDiscarder bd = getBuildDiscarder ( ) ; if ( bd != null ) bd . perform ( this ) ; }
Perform log rotation .
16,899
public < T extends JobProperty > T removeProperty ( Class < T > clazz ) throws IOException { for ( JobProperty < ? super JobT > p : properties ) { if ( clazz . isInstance ( p ) ) { removeProperty ( p ) ; return clazz . cast ( p ) ; } } return null ; }
Removes the property of the given type .