idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
31,200 | private List < String > wrapLines ( String line , final int maxLength ) { List < String > rv = new ArrayList < String > ( ) ; for ( String restOfLine : line . split ( "\\n" ) ) { while ( restOfLine . length ( ) > maxLength ) { int lineLength ; String candidate = restOfLine . substring ( 0 , maxLength ) ; int sp = candidate . lastIndexOf ( ' ' ) ; if ( sp > maxLength * 3 / 5 ) lineLength = sp ; else lineLength = maxLength ; rv . add ( restOfLine . substring ( 0 , lineLength ) ) ; restOfLine = restOfLine . substring ( lineLength ) . trim ( ) ; } rv . add ( restOfLine ) ; } return rv ; } | Wraps a line so that the resulting parts are not longer than a given maximum length . |
31,201 | public void parseArgument ( final String ... args ) throws CmdLineException { checkNonNull ( args , "args" ) ; String expandedArgs [ ] = args ; if ( parserProperties . getAtSyntax ( ) ) { expandedArgs = expandAtFiles ( args ) ; } CmdLineImpl cmdLine = new CmdLineImpl ( expandedArgs ) ; Set < OptionHandler > present = new HashSet < OptionHandler > ( ) ; int argIndex = 0 ; while ( cmdLine . hasMore ( ) ) { String arg = cmdLine . getCurrentToken ( ) ; if ( isOption ( arg ) ) { boolean isKeyValuePair = arg . contains ( parserProperties . getOptionValueDelimiter ( ) ) || arg . indexOf ( '=' ) != - 1 ; currentOptionHandler = isKeyValuePair ? findOptionHandler ( arg ) : findOptionByName ( arg ) ; if ( currentOptionHandler == null ) { throw new CmdLineException ( this , Messages . UNDEFINED_OPTION , arg ) ; } if ( isKeyValuePair ) { cmdLine . splitToken ( ) ; } else { cmdLine . proceed ( 1 ) ; } } else { if ( argIndex >= arguments . size ( ) ) { Messages msg = arguments . size ( ) == 0 ? Messages . NO_ARGUMENT_ALLOWED : Messages . TOO_MANY_ARGUMENTS ; throw new CmdLineException ( this , msg , arg ) ; } currentOptionHandler = arguments . get ( argIndex ) ; if ( currentOptionHandler == null ) throw new IllegalStateException ( "@Argument with index=" + argIndex + " is undefined" ) ; if ( ! currentOptionHandler . option . isMultiValued ( ) ) argIndex ++ ; } int diff = currentOptionHandler . parseArguments ( cmdLine ) ; cmdLine . proceed ( diff ) ; present . add ( currentOptionHandler ) ; } boolean helpSet = false ; for ( OptionHandler handler : options ) { if ( handler . option . help ( ) && present . contains ( handler ) ) { helpSet = true ; } } if ( ! helpSet ) { checkRequiredOptionsAndArguments ( present ) ; } } | Parses the command line arguments and set them to the option bean given in the constructor . |
31,202 | private String [ ] expandAtFiles ( String args [ ] ) throws CmdLineException { List < String > result = new ArrayList < String > ( ) ; for ( String arg : args ) { if ( arg . startsWith ( "@" ) ) { File file = new File ( arg . substring ( 1 ) ) ; if ( ! file . exists ( ) ) throw new CmdLineException ( this , Messages . NO_SUCH_FILE , file . getPath ( ) ) ; try { result . addAll ( readAllLines ( file ) ) ; } catch ( IOException ex ) { throw new CmdLineException ( this , "Failed to parse " + file , ex ) ; } } else { result . add ( arg ) ; } } return result . toArray ( new String [ result . size ( ) ] ) ; } | Expands every entry prefixed with the AT sign by reading the file . The AT sign is used to reference another file that contains command line options separated by line breaks . |
31,203 | private static List < String > readAllLines ( File f ) throws IOException { BufferedReader r = new BufferedReader ( new FileReader ( f ) ) ; try { List < String > result = new ArrayList < String > ( ) ; String line ; while ( ( line = r . readLine ( ) ) != null ) { result . add ( line ) ; } return result ; } finally { r . close ( ) ; } } | Reads all lines of a file with the platform encoding . |
31,204 | public static Config parse ( InputSource xml ) throws IOException , SAXException { Config rv = new Config ( ) ; XMLReader reader = XMLReaderFactory . createXMLReader ( ) ; ConfigHandler handler = rv . new ConfigHandler ( rv ) ; reader . setContentHandler ( handler ) ; reader . parse ( xml ) ; return rv ; } | Parses a XML file and returns a Config object holding the information . |
31,205 | public MultimediaInfo getInfo ( ) throws InputFormatException , EncoderException { if ( inputFile . canRead ( ) ) { FFMPEGExecutor ffmpeg = locator . createExecutor ( ) ; ffmpeg . addArgument ( "-i" ) ; ffmpeg . addArgument ( inputFile . getAbsolutePath ( ) ) ; try { ffmpeg . execute ( ) ; } catch ( IOException e ) { throw new EncoderException ( e ) ; } try { RBufferedReader reader = new RBufferedReader ( new InputStreamReader ( ffmpeg . getErrorStream ( ) ) ) ; return parseMultimediaInfo ( inputFile , reader ) ; } finally { ffmpeg . destroy ( ) ; } } else { throw new EncoderException ( "Input file not found <" + inputFile . getAbsolutePath ( ) + ">" ) ; } } | Returns a set informations about a multimedia file if its format is supported for decoding . |
31,206 | public void render ( MultimediaObject multimediaObject , int width , int height , int seconds , File outputDir , String fileNamePrefix , String extension , int quality ) throws InputFormatException , EncoderException { File inputFile = multimediaObject . getFile ( ) ; try { if ( ! outputDir . exists ( ) ) { if ( ! outputDir . mkdirs ( ) ) { LOG . debug ( "Failed to create destination folder" ) ; throw new SecurityException ( ) ; } } if ( ! inputFile . canRead ( ) ) { LOG . debug ( "Failed to open input file" ) ; throw new SecurityException ( ) ; } } catch ( SecurityException e ) { LOG . debug ( "Access denied checking destination folder" + e ) ; } MultimediaInfo multimediaInfo = multimediaObject . getInfo ( ) ; numberOfScreens = ( int ) Math . ceil ( ( multimediaInfo . getDuration ( ) * .001 ) / seconds + 1 ) ; FFMPEGExecutor ffmpeg = this . locator . createExecutor ( ) ; ffmpeg . addArgument ( "-i" ) ; ffmpeg . addArgument ( inputFile . getAbsolutePath ( ) ) ; ffmpeg . addArgument ( "-f" ) ; ffmpeg . addArgument ( "image2" ) ; ffmpeg . addArgument ( "-vf" ) ; ffmpeg . addArgument ( String . format ( "fps=fps=1/%s" , String . valueOf ( seconds ) ) ) ; ffmpeg . addArgument ( "-s" ) ; ffmpeg . addArgument ( String . format ( "%sx%s" , String . valueOf ( width ) , String . valueOf ( height ) ) ) ; ffmpeg . addArgument ( "-qscale" ) ; ffmpeg . addArgument ( String . valueOf ( quality ) ) ; ffmpeg . addArgument ( String . format ( "%s%s%s-%%04d.%s" , outputDir . getAbsolutePath ( ) , File . separator , fileNamePrefix , extension ) ) ; try { ffmpeg . execute ( ) ; } catch ( IOException e ) { throw new EncoderException ( e ) ; } try { RBufferedReader reader = new RBufferedReader ( new InputStreamReader ( ffmpeg . getErrorStream ( ) ) ) ; int step = 0 ; int lineNR = 0 ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { lineNR ++ ; LOG . debug ( "Input Line (" + lineNR + "): " + line ) ; } } catch ( IOException e ) { throw new EncoderException ( e ) ; } finally { ffmpeg . destroy ( ) ; } } | Generates screenshots from source video . |
31,207 | public void render ( MultimediaObject multimediaObject , int width , int height , int seconds , File target , int quality ) throws EncoderException { File inputFile = multimediaObject . getFile ( ) ; target = target . getAbsoluteFile ( ) ; target . getParentFile ( ) . mkdirs ( ) ; try { if ( ! inputFile . canRead ( ) ) { LOG . debug ( "Failed to open input file" ) ; throw new SecurityException ( ) ; } } catch ( SecurityException e ) { LOG . debug ( "Access denied checking destination folder" + e ) ; } MultimediaInfo multimediaInfo = multimediaObject . getInfo ( ) ; int duration = ( int ) ( multimediaInfo . getDuration ( ) * .001 ) ; numberOfScreens = seconds <= duration ? 1 : 0 ; FFMPEGExecutor ffmpeg = this . locator . createExecutor ( ) ; ffmpeg . addArgument ( "-i" ) ; ffmpeg . addArgument ( inputFile . getAbsolutePath ( ) ) ; ffmpeg . addArgument ( "-f" ) ; ffmpeg . addArgument ( "image2" ) ; ffmpeg . addArgument ( "-vframes" ) ; ffmpeg . addArgument ( "1" ) ; ffmpeg . addArgument ( "-ss" ) ; ffmpeg . addArgument ( String . valueOf ( seconds ) ) ; ffmpeg . addArgument ( "-s" ) ; ffmpeg . addArgument ( String . format ( "%sx%s" , String . valueOf ( width ) , String . valueOf ( height ) ) ) ; ffmpeg . addArgument ( "-qscale" ) ; ffmpeg . addArgument ( String . valueOf ( quality ) ) ; ffmpeg . addArgument ( target . getAbsolutePath ( ) ) ; try { ffmpeg . execute ( ) ; } catch ( IOException e ) { throw new EncoderException ( e ) ; } try { RBufferedReader reader = new RBufferedReader ( new InputStreamReader ( ffmpeg . getErrorStream ( ) ) ) ; int step = 0 ; int lineNR = 0 ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { lineNR ++ ; LOG . debug ( "Input Line (" + lineNR + "): " + line ) ; } } catch ( IOException e ) { throw new EncoderException ( e ) ; } finally { ffmpeg . destroy ( ) ; } } | Generate a single screenshot from source video . |
31,208 | protected String [ ] getCoders ( boolean encoder , boolean audio ) throws EncoderException { ArrayList < String > res = new ArrayList < > ( ) ; FFMPEGExecutor localFFMPEG = locator . createExecutor ( ) ; localFFMPEG . addArgument ( encoder ? "-encoders" : "-decoders" ) ; try { localFFMPEG . execute ( ) ; RBufferedReader reader = new RBufferedReader ( new InputStreamReader ( localFFMPEG . getInputStream ( ) ) ) ; String line ; String format = audio ? "A" : "V" ; boolean headerFound = false ; boolean evaluateLine = false ; while ( ( line = reader . readLine ( ) ) != null ) { if ( line . trim ( ) . length ( ) == 0 ) { continue ; } if ( headerFound ) { if ( evaluateLine ) { Matcher matcher = ENCODER_DECODER_PATTERN . matcher ( line ) ; if ( matcher . matches ( ) ) { String audioVideoFlag = matcher . group ( 1 ) ; if ( format . equals ( audioVideoFlag ) ) { String name = matcher . group ( 2 ) ; res . add ( name ) ; } } else { break ; } } else { evaluateLine = line . trim ( ) . equals ( "------" ) ; } } else if ( line . trim ( ) . equals ( encoder ? "Encoders:" : "Decoders:" ) ) { headerFound = true ; } } } catch ( IOException e ) { throw new EncoderException ( e ) ; } finally { localFFMPEG . destroy ( ) ; } int size = res . size ( ) ; String [ ] ret = new String [ size ] ; for ( int i = 0 ; i < size ; i ++ ) { ret [ i ] = res . get ( i ) ; } return ret ; } | Returns a list with the names of all the coders bundled with the ffmpeg distribution in use . |
31,209 | public void execute ( ) throws IOException { int argsSize = args . size ( ) ; String [ ] cmd = new String [ argsSize + 2 ] ; cmd [ 0 ] = ffmpegExecutablePath ; for ( int i = 0 ; i < argsSize ; i ++ ) { cmd [ i + 1 ] = args . get ( i ) ; } cmd [ argsSize + 1 ] = "-hide_banner" ; if ( LOG . isDebugEnabled ( ) ) { StringBuilder sb = new StringBuilder ( ) ; for ( String c : cmd ) { sb . append ( c ) ; sb . append ( ' ' ) ; } LOG . debug ( "About to execute " + sb . toString ( ) ) ; } Runtime runtime = Runtime . getRuntime ( ) ; ffmpeg = runtime . exec ( cmd ) ; ffmpegKiller = new ProcessKiller ( ffmpeg ) ; runtime . addShutdownHook ( ffmpegKiller ) ; inputStream = ffmpeg . getInputStream ( ) ; outputStream = ffmpeg . getOutputStream ( ) ; errorStream = ffmpeg . getErrorStream ( ) ; } | Executes the ffmpeg process with the previous given arguments . |
31,210 | public void destroy ( ) { if ( inputStream != null ) { try { inputStream . close ( ) ; } catch ( Throwable t ) { LOG . warn ( "Error closing input stream" , t ) ; } inputStream = null ; } if ( outputStream != null ) { try { outputStream . close ( ) ; } catch ( Throwable t ) { LOG . warn ( "Error closing output stream" , t ) ; } outputStream = null ; } if ( errorStream != null ) { try { errorStream . close ( ) ; } catch ( Throwable t ) { LOG . warn ( "Error closing error stream" , t ) ; } errorStream = null ; } if ( ffmpeg != null ) { ffmpeg . destroy ( ) ; ffmpeg = null ; } if ( ffmpegKiller != null ) { Runtime runtime = Runtime . getRuntime ( ) ; runtime . removeShutdownHook ( ffmpegKiller ) ; ffmpegKiller = null ; } } | If there s a ffmpeg execution in progress it kills it . |
31,211 | public int getProcessExitCode ( ) { try { ffmpeg . waitFor ( ) ; } catch ( InterruptedException ex ) { LOG . warn ( "Interrupted during waiting on process, forced shutdown?" , ex ) ; } return ffmpeg . exitValue ( ) ; } | Return the exit code of the ffmpeg process If the process is not yet terminated it waits for the termination of the process |
31,212 | private void copyFile ( String path , File dest ) { String resourceName = "native/" + path ; try { LOG . debug ( "Copy from resource <" + resourceName + "> to target <" + dest . getAbsolutePath ( ) + ">" ) ; if ( copy ( getClass ( ) . getResourceAsStream ( resourceName ) , dest . getAbsolutePath ( ) ) ) { if ( dest . exists ( ) ) { LOG . debug ( "Target <" + dest . getAbsolutePath ( ) + "> exists" ) ; } else { LOG . fatal ( "Target <" + dest . getAbsolutePath ( ) + "> does not exist" ) ; } } else { LOG . fatal ( "Copy resource to target <" + dest . getAbsolutePath ( ) + "> failed" ) ; } } catch ( NullPointerException ex ) { LOG . error ( "Could not find ffmpeg executable for " + resourceName + " is the correct platform jar included?" ) ; throw ex ; } } | Copies a file bundled in the package to the supplied destination . |
31,213 | private boolean copy ( InputStream source , String destination ) { boolean success = true ; try { Files . copy ( source , Paths . get ( destination ) , StandardCopyOption . REPLACE_EXISTING ) ; } catch ( IOException ex ) { LOG . fatal ( "Cannot write file " + destination , ex ) ; success = false ; } return success ; } | Copy a file from source to destination . |
31,214 | protected void debug ( String message ) { final Log log = getLog ( ) ; if ( log != null ) log . debug ( message ) ; } | Log given message at debug level |
31,215 | protected void debug ( String message , Throwable throwable ) { final Log log = getLog ( ) ; if ( log != null ) log . debug ( message , throwable ) ; } | Log given message and throwable at debug level |
31,216 | protected void info ( String message ) { final Log log = getLog ( ) ; if ( log != null ) log . info ( message ) ; } | Log given message at info level |
31,217 | protected boolean configureOAuth2Token ( final GitHubClient client , final String oauth2Token ) { if ( StringUtils . isEmpty ( oauth2Token ) ) return false ; if ( isDebug ( ) ) debug ( "Using OAuth2 access token authentication" ) ; client . setOAuth2Token ( oauth2Token ) ; return true ; } | Configure credentials from configured OAuth2 token |
31,218 | protected boolean configureServerCredentials ( final GitHubClient client , final String serverId , final Settings settings , final MavenSession session ) throws MojoExecutionException { if ( StringUtils . isEmpty ( serverId ) ) return false ; String serverUsername = null ; String serverPassword = null ; Server server = getServer ( settings , serverId ) ; if ( server == null ) throw new MojoExecutionException ( MessageFormat . format ( "Server ''{0}'' not found in settings" , serverId ) ) ; if ( isDebug ( ) ) debug ( MessageFormat . format ( "Using ''{0}'' server credentials" , serverId ) ) ; { try { SettingsDecrypter settingsDecrypter = container . lookup ( SettingsDecrypter . class ) ; SettingsDecryptionResult result = settingsDecrypter . decrypt ( new DefaultSettingsDecryptionRequest ( server ) ) ; server = result . getServer ( ) ; } catch ( ComponentLookupException cle ) { throw new MojoExecutionException ( "Unable to lookup SettingsDecrypter: " + cle . getMessage ( ) , cle ) ; } } serverUsername = server . getUsername ( ) ; serverPassword = server . getPassword ( ) ; if ( ! StringUtils . isEmpty ( serverUsername , serverPassword ) ) { if ( isDebug ( ) ) debug ( "Using basic authentication with username: " + serverUsername ) ; client . setCredentials ( serverUsername , serverPassword ) ; return true ; } if ( ! StringUtils . isEmpty ( serverPassword ) ) { if ( isDebug ( ) ) debug ( "Using OAuth2 access token authentication" ) ; client . setOAuth2Token ( serverPassword ) ; return true ; } if ( isDebug ( ) ) debug ( MessageFormat . format ( "Server ''{0}'' is missing username/password credentials" , serverId ) ) ; return false ; } | Configure client with credentials from given server id |
31,219 | protected Server getServer ( final Settings settings , final String serverId ) { if ( settings == null ) return null ; List < Server > servers = settings . getServers ( ) ; if ( servers == null || servers . isEmpty ( ) ) return null ; for ( Server server : servers ) if ( serverId . equals ( server . getId ( ) ) ) return server ; return null ; } | Get server with given id |
31,220 | protected boolean matchNonProxy ( final Proxy proxy , final String hostname ) { String host = hostname ; if ( null == hostname ) host = IGitHubConstants . HOST_DEFAULT ; final String nonProxyHosts = proxy . getNonProxyHosts ( ) ; if ( null != nonProxyHosts ) { final String [ ] nonProxies = nonProxyHosts . split ( "(,)|(;)|(\\|)" ) ; if ( null != nonProxies ) { for ( final String nonProxyHost : nonProxies ) { if ( null != nonProxyHost && nonProxyHost . contains ( "*" ) ) { final int pos = nonProxyHost . indexOf ( '*' ) ; String nonProxyHostPrefix = nonProxyHost . substring ( 0 , pos ) ; String nonProxyHostSuffix = nonProxyHost . substring ( pos + 1 ) ; if ( ! StringUtils . isEmpty ( nonProxyHostPrefix ) && host . startsWith ( nonProxyHostPrefix ) && StringUtils . isEmpty ( nonProxyHostSuffix ) ) { return true ; } if ( StringUtils . isEmpty ( nonProxyHostPrefix ) && ! StringUtils . isEmpty ( nonProxyHostSuffix ) && host . endsWith ( nonProxyHostSuffix ) ) { return true ; } if ( ! StringUtils . isEmpty ( nonProxyHostPrefix ) && host . startsWith ( nonProxyHostPrefix ) && ! StringUtils . isEmpty ( nonProxyHostSuffix ) && host . endsWith ( nonProxyHostSuffix ) ) { return true ; } } else if ( host . equals ( nonProxyHost ) ) { return true ; } } } } return false ; } | Check hostname that matched nonProxy setting |
31,221 | protected Proxy getProxy ( final Settings settings , final String serverId , final String host ) { if ( settings == null ) return null ; List < Proxy > proxies = settings . getProxies ( ) ; if ( proxies == null || proxies . isEmpty ( ) ) return null ; if ( serverId != null && ! serverId . isEmpty ( ) ) { for ( Proxy proxy : proxies ) { if ( proxy . isActive ( ) ) { final String proxyId = proxy . getId ( ) ; if ( proxyId != null && ! proxyId . isEmpty ( ) ) { if ( proxyId . equalsIgnoreCase ( serverId ) ) { if ( ( "http" . equalsIgnoreCase ( proxy . getProtocol ( ) ) || "https" . equalsIgnoreCase ( proxy . getProtocol ( ) ) ) ) { if ( matchNonProxy ( proxy , host ) ) return null ; else return proxy ; } } } } } } for ( Proxy proxy : proxies ) if ( proxy . isActive ( ) && ( "http" . equalsIgnoreCase ( proxy . getProtocol ( ) ) || "https" . equalsIgnoreCase ( proxy . getProtocol ( ) ) ) ) { if ( matchNonProxy ( proxy , host ) ) return null ; else return proxy ; } return null ; } | Get proxy from settings |
31,222 | public static RepositoryId extractRepositoryFromScmUrl ( String url ) { if ( StringUtils . isEmpty ( url ) ) return null ; int ghIndex = url . indexOf ( HOST_DEFAULT ) ; if ( ghIndex == - 1 || ghIndex + 1 >= url . length ( ) ) return null ; if ( ! url . endsWith ( SUFFIX_GIT ) ) return null ; url = url . substring ( ghIndex + HOST_DEFAULT . length ( ) + 1 , url . length ( ) - SUFFIX_GIT . length ( ) ) ; return RepositoryId . createFromId ( url ) ; } | Extra repository id from given SCM URL |
31,223 | public static boolean isEmpty ( final String ... values ) { if ( values == null || values . length == 0 ) return true ; for ( String value : values ) if ( value == null || value . length ( ) == 0 ) return true ; return false ; } | Are any given values null or empty? |
31,224 | protected void updateValuesFromHSVFields ( ) { int [ ] hsv = ColorUtils . RGBtoHSV ( color ) ; int h = hsv [ 0 ] ; int s = hsv [ 1 ] ; int v = hsv [ 2 ] ; if ( hBar . isInputValid ( ) ) h = hBar . getValue ( ) ; if ( sBar . isInputValid ( ) ) s = sBar . getValue ( ) ; if ( vBar . isInputValid ( ) ) v = vBar . getValue ( ) ; color = ColorUtils . HSVtoRGB ( h , s , v , color . a ) ; int cr = MathUtils . round ( color . r * 255.0f ) ; int cg = MathUtils . round ( color . g * 255.0f ) ; int cb = MathUtils . round ( color . b * 255.0f ) ; rBar . setValue ( cr ) ; gBar . setValue ( cg ) ; bBar . setValue ( cb ) ; } | Updates picker from H S and V bars |
31,225 | private void updateValuesFromRGBFields ( ) { int r = MathUtils . round ( color . r * 255.0f ) ; int g = MathUtils . round ( color . g * 255.0f ) ; int b = MathUtils . round ( color . b * 255.0f ) ; if ( rBar . isInputValid ( ) ) r = rBar . getValue ( ) ; if ( gBar . isInputValid ( ) ) g = gBar . getValue ( ) ; if ( bBar . isInputValid ( ) ) b = bBar . getValue ( ) ; color . set ( r / 255.0f , g / 255.0f , b / 255.0f , color . a ) ; int [ ] hsv = ColorUtils . RGBtoHSV ( color ) ; int ch = hsv [ 0 ] ; int cs = hsv [ 1 ] ; int cv = hsv [ 2 ] ; hBar . setValue ( ch ) ; sBar . setValue ( cs ) ; vBar . setValue ( cv ) ; verticalBar . setValue ( hBar . getValue ( ) ) ; palette . setValue ( sBar . getValue ( ) , vBar . getValue ( ) ) ; } | Updates picker from R G and B bars |
31,226 | public void processHighlighter ( ) { if ( highlights == null ) return ; highlights . clear ( ) ; if ( highlighter != null ) highlighter . process ( this , highlights ) ; chunkUpdateScheduled = true ; } | Processes highlighter rules collects created highlights and schedules text area displayed text update . This should be called after highlighter rules has changed to update highlights . |
31,227 | public FormInputValidator notEmpty ( VisValidatableTextField field , String errorMsg ) { EmptyInputValidator validator = new EmptyInputValidator ( errorMsg ) ; field . addValidator ( validator ) ; add ( field ) ; return validator ; } | Validates if file is not empty |
31,228 | public FormInputValidator integerNumber ( VisValidatableTextField field , String errorMsg ) { ValidatorWrapper wrapper = new ValidatorWrapper ( errorMsg , Validators . INTEGERS ) ; field . addValidator ( wrapper ) ; add ( field ) ; return wrapper ; } | Validates if entered text is integer number |
31,229 | public FormInputValidator floatNumber ( VisValidatableTextField field , String errorMsg ) { ValidatorWrapper wrapper = new ValidatorWrapper ( errorMsg , Validators . FLOATS ) ; field . addValidator ( wrapper ) ; add ( field ) ; return wrapper ; } | Validates if entered text is float number |
31,230 | public FormInputValidator custom ( VisValidatableTextField field , FormInputValidator customValidator ) { field . addValidator ( customValidator ) ; add ( field ) ; return customValidator ; } | Allows to add custom validator to field |
31,231 | public void validate ( ) { formInvalid = false ; errorMsgText = null ; for ( CheckedButtonWrapper wrapper : buttons ) { if ( wrapper . button . isChecked ( ) != wrapper . mustBeChecked ) { wrapper . setButtonStateInvalid ( true ) ; } else { wrapper . setButtonStateInvalid ( false ) ; } } for ( CheckedButtonWrapper wrapper : buttons ) { if ( treatDisabledFieldsAsValid && wrapper . button . isDisabled ( ) ) { continue ; } if ( wrapper . button . isChecked ( ) != wrapper . mustBeChecked ) { errorMsgText = wrapper . errorMsg ; formInvalid = true ; break ; } } for ( VisValidatableTextField field : fields ) { field . validateInput ( ) ; } for ( VisValidatableTextField field : fields ) { if ( treatDisabledFieldsAsValid && field . isDisabled ( ) ) { continue ; } if ( field . isInputValid ( ) == false ) { Array < InputValidator > validators = field . getValidators ( ) ; for ( InputValidator v : validators ) { if ( v instanceof FormInputValidator == false ) { throw new IllegalStateException ( "Fields validated by FormValidator cannot have validators not added using FormValidator methods. " + "Are you adding validators to field manually?" ) ; } FormInputValidator validator = ( FormInputValidator ) v ; if ( validator . getLastResult ( ) == false ) { if ( ! ( validator . isHideErrorOnEmptyInput ( ) && field . getText ( ) . equals ( "" ) ) ) { errorMsgText = validator . getErrorMsg ( ) ; } formInvalid = true ; break ; } } break ; } } updateWidgets ( ) ; } | Performs full check of this form typically there is no need to call this method manually since form will be automatically validated upon field content change . However calling this might be required when change made to field state does not cause change event to be fired . For example disabling or enabling field . |
31,232 | protected void sizeChanged ( ) { lastText = null ; BitmapFont font = style . font ; Drawable background = style . background ; float availableHeight = getHeight ( ) - ( background == null ? 0 : background . getBottomHeight ( ) + background . getTopHeight ( ) ) ; linesShowing = ( int ) Math . floor ( availableHeight / font . getLineHeight ( ) ) ; } | OVERRIDE from TextField |
31,233 | public FormInputValidator fileExists ( VisValidatableTextField field , String errorMsg ) { FileExistsValidator validator = new FileExistsValidator ( errorMsg ) ; field . addValidator ( validator ) ; add ( field ) ; return validator ; } | Validates if absolute path entered in text field points to an existing file . |
31,234 | public FormInputValidator fileExists ( VisValidatableTextField field , FileHandle relativeTo , String errorMsg ) { FileExistsValidator validator = new FileExistsValidator ( relativeTo . file ( ) , errorMsg ) ; field . addValidator ( validator ) ; add ( field ) ; return validator ; } | Validates if relative path entered in text field points to an existing file . |
31,235 | public FormInputValidator directory ( VisValidatableTextField field , String errorMsg ) { DirectoryValidator validator = new DirectoryValidator ( errorMsg ) ; field . addValidator ( validator ) ; add ( field ) ; return validator ; } | Validates if relative path entered in text field points to an existing directory . |
31,236 | public FormInputValidator directoryEmpty ( VisValidatableTextField field , String errorMsg ) { DirectoryContentValidator validator = new DirectoryContentValidator ( errorMsg , true ) ; field . addValidator ( validator ) ; add ( field ) ; return validator ; } | Validates if relative path entered in text field points to an existing and empty directory . |
31,237 | public FormInputValidator directoryNotEmpty ( VisValidatableTextField field , String errorMsg ) { DirectoryContentValidator validator = new DirectoryContentValidator ( errorMsg , false ) ; field . addValidator ( validator ) ; add ( field ) ; return validator ; } | Validates if relative path entered in text field points to an existing and non empty directory . |
31,238 | public boolean remove ( final Tab tab , boolean ignoreTabDirty ) { checkIfTabsBelongsToThisPane ( tab ) ; if ( ignoreTabDirty ) { return removeTab ( tab ) ; } if ( tab . isDirty ( ) && mainTable . getStage ( ) != null ) { Dialogs . showOptionDialog ( mainTable . getStage ( ) , Text . UNSAVED_DIALOG_TITLE . get ( ) , Text . UNSAVED_DIALOG_TEXT . get ( ) , OptionDialogType . YES_NO_CANCEL , new OptionDialogAdapter ( ) { public void yes ( ) { tab . save ( ) ; removeTab ( tab ) ; } public void no ( ) { removeTab ( tab ) ; } } ) ; } else { return removeTab ( tab ) ; } return false ; } | Removes tab from pane if tab is dirty and ignoreTabDirty == false this will cause to display Unsaved changes dialog! |
31,239 | public void removeAll ( ) { for ( Tab tab : tabs ) { tab . setPane ( null ) ; tab . onHide ( ) ; tab . dispose ( ) ; } tabs . clear ( ) ; tabsButtonMap . clear ( ) ; tabsPane . clear ( ) ; notifyListenersRemovedAll ( ) ; } | Removes all tabs ignores if tab is dirty |
31,240 | void setMenuBar ( MenuBar menuBar ) { if ( this . menuBar != null && menuBar != null ) throw new IllegalStateException ( "Menu was already added to MenuBar" ) ; this . menuBar = menuBar ; } | Called by MenuBar when this menu is added to it |
31,241 | public boolean centerWindow ( ) { Group parent = getParent ( ) ; if ( parent == null ) { centerOnAdd = true ; return false ; } else { moveToCenter ( ) ; return true ; } } | Centers this window if it has parent it will be done instantly if it does not have parent it will be centered when it will be added to stage |
31,242 | public void fadeOut ( float time ) { if ( fadeOutActionRunning ) return ; fadeOutActionRunning = true ; final Touchable previousTouchable = getTouchable ( ) ; setTouchable ( Touchable . disabled ) ; Stage stage = getStage ( ) ; if ( stage != null && stage . getKeyboardFocus ( ) != null && stage . getKeyboardFocus ( ) . isDescendantOf ( this ) ) { FocusManager . resetFocus ( stage ) ; } addAction ( Actions . sequence ( Actions . fadeOut ( time , Interpolation . fade ) , new Action ( ) { public boolean act ( float delta ) { setTouchable ( previousTouchable ) ; remove ( ) ; getColor ( ) . a = 1f ; fadeOutActionRunning = false ; return true ; } } ) ) ; } | Fade outs this window when fade out animation is completed window is removed from Stage . Calling this for the second time won t have any effect if previous animation is still running . |
31,243 | public static VisDialog showOKDialog ( Stage stage , String title , String text ) { final VisDialog dialog = new VisDialog ( title ) ; dialog . closeOnEscape ( ) ; dialog . text ( text ) ; dialog . button ( ButtonType . OK . getText ( ) ) . padBottom ( 3 ) ; dialog . pack ( ) ; dialog . centerWindow ( ) ; dialog . addListener ( new InputListener ( ) { public boolean keyDown ( InputEvent event , int keycode ) { if ( keycode == Keys . ENTER ) { dialog . fadeOut ( ) ; return true ; } return false ; } } ) ; stage . addActor ( dialog . fadeIn ( ) ) ; return dialog ; } | Dialog with given text and single OK button . |
31,244 | public static OptionDialog showOptionDialog ( Stage stage , String title , String text , OptionDialogType type , OptionDialogListener listener ) { OptionDialog dialog = new OptionDialog ( title , text , type , listener ) ; stage . addActor ( dialog . fadeIn ( ) ) ; return dialog ; } | Dialog with text and buttons like Yes No Cancel . |
31,245 | public static InputDialog showInputDialog ( Stage stage , String title , String fieldTitle , InputDialogListener listener ) { InputDialog dialog = new InputDialog ( title , fieldTitle , true , null , listener ) ; stage . addActor ( dialog . fadeIn ( ) ) ; return dialog ; } | Dialog with text and text field for user input . Cannot be canceled . |
31,246 | public static DetailsDialog showErrorDialog ( Stage stage , String text ) { return showErrorDialog ( stage , text , ( String ) null ) ; } | Dialog with title Error and provided text . |
31,247 | public static DetailsDialog showErrorDialog ( Stage stage , String text , Throwable exception ) { if ( exception == null ) return showErrorDialog ( stage , text , ( String ) null ) ; else return showErrorDialog ( stage , text , getStackTrace ( exception ) ) ; } | Dialog with title Error provided text and exception stacktrace available after pressing Details button . |
31,248 | public static DetailsDialog showErrorDialog ( Stage stage , String text , String details ) { DetailsDialog dialog = new DetailsDialog ( text , Text . ERROR . get ( ) , details ) ; stage . addActor ( dialog . fadeIn ( ) ) ; return dialog ; } | Dialog with title Error provided text and provided details available after pressing Details button . |
31,249 | public void addLinkLabel ( String text , LinkLabel . LinkLabelListener labelListener ) { LinkLabel label = new LinkLabel ( text ) ; label . setListener ( labelListener ) ; linkLabelTable . add ( label ) . spaceRight ( 12 ) ; } | Adds new link label below toast message . |
31,250 | public void setMin ( BigDecimal min ) { if ( min . compareTo ( max ) > 0 ) throw new IllegalArgumentException ( "min can't be > max" ) ; this . min = min ; if ( min . compareTo ( BigDecimal . ZERO ) >= 0 ) { textFieldFilter . setAcceptNegativeValues ( false ) ; } else { textFieldFilter . setAcceptNegativeValues ( true ) ; } if ( current . compareTo ( min ) < 0 ) { current = min . setScale ( scale , BigDecimal . ROUND_HALF_UP ) ; spinner . notifyValueChanged ( spinner . isProgrammaticChangeEvents ( ) ) ; } } | Sets min value . If current is lesser than min the current value is set to min value |
31,251 | public static Color HSVtoRGB ( float h , float s , float v , float alpha ) { Color c = HSVtoRGB ( h , s , v ) ; c . a = alpha ; return c ; } | Converts HSV to RGB |
31,252 | public static int [ ] RGBtoHSV ( float r , float g , float b ) { float h , s , v ; float min , max , delta ; min = Math . min ( Math . min ( r , g ) , b ) ; max = Math . max ( Math . max ( r , g ) , b ) ; v = max ; delta = max - min ; if ( max != 0 ) s = delta / max ; else { s = 0 ; h = 0 ; return new int [ ] { MathUtils . round ( h ) , MathUtils . round ( s ) , MathUtils . round ( v ) } ; } if ( delta == 0 ) h = 0 ; else { if ( r == max ) h = ( g - b ) / delta ; else if ( g == max ) h = 2 + ( b - r ) / delta ; else h = 4 + ( r - g ) / delta ; } h *= 60 ; if ( h < 0 ) h += 360 ; s *= 100 ; v *= 100 ; return new int [ ] { MathUtils . round ( h ) , MathUtils . round ( s ) , MathUtils . round ( v ) } ; } | Converts RGB to HSV color system |
31,253 | public void word ( Color color , String ... words ) { for ( String word : words ) { addRule ( new WordHighlightRule ( color , word ) ) ; } } | Adds word based highlighter rule . Utility method allowing to add many words at once . |
31,254 | public void process ( HighlightTextArea textArea , Array < Highlight > highlights ) { for ( HighlightRule rule : rules ) { rule . process ( textArea , highlights ) ; } } | Process all rules in this highlighter . |
31,255 | protected void updateValuesFromCurrentColor ( ) { int [ ] hsv = ColorUtils . RGBtoHSV ( color ) ; int ch = hsv [ 0 ] ; int cs = hsv [ 1 ] ; int cv = hsv [ 2 ] ; verticalBar . setValue ( ch ) ; palette . setValue ( cs , cv ) ; } | Updates picker ui from current color |
31,256 | public void setColor ( Color newColor ) { if ( allowAlphaEdit == false ) newColor . a = 1 ; setColor ( newColor , true ) ; } | Sets current selected color in picker . |
31,257 | public static void removeTooltip ( Actor target ) { Array < EventListener > listeners = target . getListeners ( ) ; for ( EventListener listener : listeners ) { if ( listener instanceof TooltipInputListener ) target . removeListener ( listener ) ; } } | Remove any attached tooltip from target actor |
31,258 | public void setText ( String text ) { if ( content instanceof VisLabel ) { ( ( VisLabel ) content ) . setText ( text ) ; } else { setContent ( new VisLabel ( text ) ) ; } pack ( ) ; } | Changes text tooltip to specified text . If tooltip content is not instance of VisLabel then previous tooltip content will be replaced by VisLabel instance . |
31,259 | public void setWidgets ( Iterable < Actor > actors ) { clearChildren ( ) ; widgetBounds . clear ( ) ; scissors . clear ( ) ; handleBounds . clear ( ) ; splits . clear ( ) ; for ( Actor actor : actors ) { super . addActor ( actor ) ; widgetBounds . add ( new Rectangle ( ) ) ; scissors . add ( new Rectangle ( ) ) ; } float currentSplit = 0 ; float splitAdvance = 1f / getChildren ( ) . size ; for ( int i = 0 ; i < getChildren ( ) . size - 1 ; i ++ ) { handleBounds . add ( new Rectangle ( ) ) ; currentSplit += splitAdvance ; splits . add ( currentSplit ) ; } invalidate ( ) ; } | Changes widgets of this split pane . You can pass any number of actors even 1 or 0 . Actors can t be null . |
31,260 | public void show ( String text , float timeSec ) { VisTable table = new VisTable ( ) ; table . add ( text ) . grow ( ) ; show ( table , timeSec ) ; } | Displays basic toast with provided text as message . Toast will be displayed for given amount of seconds . |
31,261 | public void show ( final Toast toast , float timeSec ) { Table toastMainTable = toast . getMainTable ( ) ; if ( toastMainTable . getStage ( ) != null ) { remove ( toast ) ; } toasts . add ( toast ) ; toast . setToastManager ( this ) ; toast . fadeIn ( ) ; toastMainTable . pack ( ) ; root . addActor ( toastMainTable ) ; updateToastsPositions ( ) ; if ( timeSec > 0 ) { Timer . Task fadeOutTask = new Timer . Task ( ) { public void run ( ) { toast . fadeOut ( ) ; timersTasks . remove ( toast ) ; } } ; timersTasks . put ( toast , fadeOutTask ) ; Timer . schedule ( fadeOutTask , timeSec ) ; } } | Displays toast . Toast will be displayed for given amount of seconds . |
31,262 | public boolean remove ( Toast toast ) { boolean removed = toasts . removeValue ( toast , true ) ; if ( removed ) { toast . getMainTable ( ) . remove ( ) ; Timer . Task timerTask = timersTasks . remove ( toast ) ; if ( timerTask != null ) timerTask . cancel ( ) ; updateToastsPositions ( ) ; } return removed ; } | Removes toast from screen . |
31,263 | public static void restoreDefaultCursor ( ) { if ( systemCursorAsDefault ) { Gdx . graphics . setSystemCursor ( defaultSystemCursor ) ; } else { Gdx . graphics . setCursor ( defaultCursor ) ; } } | Restores currently used cursor to default one . |
31,264 | public VisDialog text ( String text ) { if ( skin == null ) throw new IllegalStateException ( "This method may only be used if the dialog was constructed with a Skin." ) ; return text ( text , skin . get ( LabelStyle . class ) ) ; } | Adds a label to the content table . The dialog must have been constructed with a skin to use this method . |
31,265 | public VisDialog text ( String text , LabelStyle labelStyle ) { return text ( new Label ( text , labelStyle ) ) ; } | Adds a label to the content table . |
31,266 | public VisDialog button ( String text , Object object ) { if ( skin == null ) throw new IllegalStateException ( "This method may only be used if the dialog was constructed with a Skin." ) ; return button ( text , object , skin . get ( VisTextButtonStyle . class ) ) ; } | Adds a text button to the button table . The dialog must have been constructed with a skin to use this method . |
31,267 | public VisDialog button ( String text , Object object , VisTextButtonStyle buttonStyle ) { return button ( new VisTextButton ( text , buttonStyle ) , object ) ; } | Adds a text button to the button table . |
31,268 | public VisDialog button ( Button button , Object object ) { buttonTable . add ( button ) ; setObject ( button , object ) ; return this ; } | Adds the given button to the button table . |
31,269 | public void hide ( Action action ) { Stage stage = getStage ( ) ; if ( stage != null ) { removeListener ( focusListener ) ; if ( previousKeyboardFocus != null && previousKeyboardFocus . getStage ( ) == null ) previousKeyboardFocus = null ; Actor actor = stage . getKeyboardFocus ( ) ; if ( actor == null || actor . isDescendantOf ( this ) ) stage . setKeyboardFocus ( previousKeyboardFocus ) ; if ( previousScrollFocus != null && previousScrollFocus . getStage ( ) == null ) previousScrollFocus = null ; actor = stage . getScrollFocus ( ) ; if ( actor == null || actor . isDescendantOf ( this ) ) stage . setScrollFocus ( previousScrollFocus ) ; } if ( action != null ) { addCaptureListener ( ignoreTouchDown ) ; addAction ( sequence ( action , Actions . removeListener ( ignoreTouchDown , true ) , Actions . removeActor ( ) ) ) ; } else remove ( ) ; } | Hides the dialog with the given action and then removes it from the stage . |
31,270 | public void hide ( ) { hide ( sequence ( Actions . fadeOut ( FADE_TIME , Interpolation . fade ) , Actions . removeListener ( ignoreTouchDown , true ) , Actions . removeActor ( ) ) ) ; } | Hides the dialog . Called automatically when a button is clicked . The default implementation fades out the dialog over 400 milliseconds and then removes it from the stage . |
31,271 | protected void executeOnGdx ( final Runnable runnable ) { final CountDownLatch latch = new CountDownLatch ( 1 ) ; final AtomicReference < Exception > exceptionAt = new AtomicReference < Exception > ( ) ; Gdx . app . postRunnable ( new Runnable ( ) { public void run ( ) { try { runnable . run ( ) ; } catch ( Exception e ) { exceptionAt . set ( e ) ; } finally { latch . countDown ( ) ; } } } ) ; try { latch . await ( ) ; final Exception e = exceptionAt . get ( ) ; if ( e != null ) { failed ( e ) ; } } catch ( InterruptedException e ) { failed ( e ) ; } } | Executes runnable on main GDX thread . This methods blocks until runnable has finished executing . Note that this runnable will also block main render thread . |
31,272 | public void setMin ( float min ) { if ( min > max ) throw new IllegalArgumentException ( "min can't be > max" ) ; this . min = min ; if ( min >= 0 ) { textFieldFilter . setAcceptNegativeValues ( false ) ; } else { textFieldFilter . setAcceptNegativeValues ( true ) ; } if ( current < min ) { current = min ; spinner . notifyValueChanged ( spinner . isProgrammaticChangeEvents ( ) ) ; } } | Sets min value if current is lesser than min the current value is set to min value |
31,273 | public void invalidateDataSet ( ) { updateCurrentItem ( MathUtils . clamp ( currentIndex , 0 , items . size - 1 ) ) ; spinner . notifyValueChanged ( true ) ; } | Notifies model that items has changed and view must be refreshed . This will trigger a change event . |
31,274 | public void setItems ( Array < T > newItems ) { items . clear ( ) ; items . addAll ( newItems ) ; currentIndex = 0 ; invalidateDataSet ( ) ; } | Changes items of this model . Current index is not preserved . This will trigger a change event . |
31,275 | public static boolean isValidFileName ( String name ) { try { if ( OsUtils . isWindows ( ) ) { if ( name . contains ( ">" ) || name . contains ( "<" ) ) return false ; name = name . toLowerCase ( ) ; } return new File ( name ) . getCanonicalFile ( ) . getName ( ) . equals ( name ) ; } catch ( Exception e ) { return false ; } } | Checks whether given name is valid for current user OS . |
31,276 | @ SuppressWarnings ( "unchecked" ) public static void showDirInExplorer ( FileHandle dir ) throws IOException { File dirToShow ; if ( dir . isDirectory ( ) ) { dirToShow = dir . file ( ) ; } else { dirToShow = dir . parent ( ) . file ( ) ; } if ( OsUtils . isMac ( ) ) { FileManager . revealInFinder ( dirToShow ) ; } else { try { Class desktopClass = Class . forName ( "java.awt.Desktop" ) ; Object desktop = desktopClass . getMethod ( "getDesktop" ) . invoke ( null ) ; desktopClass . getMethod ( "open" , File . class ) . invoke ( desktop , dirToShow ) ; } catch ( Exception e ) { Gdx . app . log ( "VisUI" , "Can't open file " + dirToShow . getPath ( ) , e ) ; } } } | Shows given directory in system explorer window . |
31,277 | public InputListener getDefaultInputListener ( final int mouseButton ) { if ( defaultInputListener == null ) { defaultInputListener = new InputListener ( ) { public boolean touchDown ( InputEvent event , float x , float y , int pointer , int button ) { return true ; } public void touchUp ( InputEvent event , float x , float y , int pointer , int button ) { if ( event . getButton ( ) == mouseButton ) showMenu ( event . getStage ( ) , event . getStageX ( ) , event . getStageY ( ) ) ; } } ; } return defaultInputListener ; } | Returns input listener that can be added to scene2d actor . When mouse button is pressed on that actor menu will be displayed |
31,278 | public void showMenu ( Stage stage , float x , float y ) { setPosition ( x , y - getHeight ( ) ) ; if ( stage . getHeight ( ) - getY ( ) > stage . getHeight ( ) ) setY ( getY ( ) + getHeight ( ) ) ; ActorUtils . keepWithinStage ( stage , this ) ; stage . addActor ( this ) ; } | Shows menu as given stage coordinates |
31,279 | void setActiveSubMenu ( PopupMenu newSubMenu ) { if ( activeSubMenu == newSubMenu ) return ; if ( activeSubMenu != null ) activeSubMenu . remove ( ) ; activeSubMenu = newSubMenu ; if ( newSubMenu != null ) { newSubMenu . setParentMenu ( this ) ; } } | Called by framework when PopupMenu is added to MenuItem as submenu |
31,280 | public ScrollPane createCompatibleScrollPane ( ) { VisScrollPane scrollPane = new VisScrollPane ( this ) ; scrollPane . setOverscroll ( false , false ) ; scrollPane . setFlickScroll ( false ) ; scrollPane . setFadeScrollBars ( false ) ; scrollPane . setScrollbarsOnTop ( true ) ; scrollPane . setScrollingDisabled ( true , false ) ; return scrollPane ; } | Creates scroll pane for this scrolling text area with best possible default settings . Note that text area can belong to only one scroll pane calling this multiple times will break previously created scroll pane . The scroll pane should be embedded in container with fixed size or optionally grow property . |
31,281 | public void setRestoreLastValid ( boolean restoreLastValid ) { if ( hasSelection ) throw new IllegalStateException ( "Last valid text restore can't be changed while filed has selection" ) ; this . restoreLastValid = restoreLastValid ; if ( restoreLastValid ) { if ( restoreFocusListener == null ) restoreFocusListener = new LastValidFocusListener ( ) ; addListener ( restoreFocusListener ) ; } else { removeListener ( restoreFocusListener ) ; } } | If true this field will automatically restore last valid text if it loses keyboard focus during text edition . This can t be called while field is selected doing so will result in IllegalStateException . Default is false . |
31,282 | public static String getName ( String name , int level ) { level ++ ; String fullName ; if ( name == null ) fullName = getCallerClassName ( level ) ; else if ( name . contains ( "." ) ) fullName = name ; else fullName = getCallerClassName ( level ) + "." + name ; return fullName ; } | Returns full name for the caller class logger . |
31,283 | public void removeAll ( Class < ? extends ProcessListener > type ) { for ( Iterator < ProcessListener > it = children . iterator ( ) ; it . hasNext ( ) ; ) { if ( type . isInstance ( it . next ( ) ) ) it . remove ( ) ; } } | Remove existing listeners of given type or its sub - types . |
31,284 | public void write ( final int cc ) throws IOException { final byte c = ( byte ) cc ; if ( ( c == '\n' ) || ( c == '\r' ) ) { if ( c == '\r' || ( c == '\n' && ( lastReceivedByte != '\r' && lastReceivedByte != '\n' ) ) ) { processBuffer ( ) ; } } else { buffer . write ( cc ) ; } lastReceivedByte = c ; } | Write the data to the buffer and flush the buffer if a line separator is detected . |
31,285 | public void write ( final byte [ ] b , final int off , final int len ) throws IOException { int offset = off ; int blockStartOffset = offset ; int remaining = len ; while ( remaining > 0 ) { while ( remaining > 0 && b [ offset ] != LF && b [ offset ] != CR ) { offset ++ ; remaining -- ; } int blockLength = offset - blockStartOffset ; if ( blockLength > 0 ) { buffer . write ( b , blockStartOffset , blockLength ) ; lastReceivedByte = 0 ; } while ( remaining > 0 && ( b [ offset ] == LF || b [ offset ] == CR ) ) { write ( b [ offset ] ) ; offset ++ ; remaining -- ; } blockStartOffset = offset ; } } | Write a block of characters to the output stream |
31,286 | public static void addSuppressed ( Throwable t , Throwable suppressed ) { if ( METHOD_ADD_SUPPRESSED != null ) { try { METHOD_ADD_SUPPRESSED . invoke ( t , suppressed ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Could not add suppressed exception:" , e ) ; } } } | If supported . appends the specified exception to the exceptions that were suppressed in order to deliver this exception . |
31,287 | private void closeStreams ( final Process process ) throws IOException { IOException caught = null ; try { process . getOutputStream ( ) . close ( ) ; } catch ( IOException e ) { if ( e . getMessage ( ) . equals ( "Stream closed" ) ) { log . trace ( "Failed to close process output stream:" , e ) ; } else { log . error ( "Failed to close process output stream:" , e ) ; caught = add ( caught , e ) ; } } try { process . getInputStream ( ) . close ( ) ; } catch ( IOException e ) { log . error ( "Failed to close process input stream:" , e ) ; caught = add ( caught , e ) ; } try { process . getErrorStream ( ) . close ( ) ; } catch ( IOException e ) { log . error ( "Failed to close process error stream:" , e ) ; caught = add ( caught , e ) ; } if ( caught != null ) { throw caught ; } } | Close the streams belonging to the given Process . |
31,288 | public ProcessExecutor environment ( String name , String value ) { environment . put ( name , value ) ; return this ; } | Adds a single additional environment variable for the process being executed . |
31,289 | public ProcessExecutor exitValue ( Integer exitValue ) { return exitValues ( exitValue == null ? null : new Integer [ ] { exitValue } ) ; } | Sets the allowed exit value for the process being executed . |
31,290 | public ProcessExecutor redirectInput ( InputStream input ) { PumpStreamHandler pumps = pumps ( ) ; return streams ( new PumpStreamHandler ( pumps == null ? null : pumps . getOut ( ) , pumps == null ? null : pumps . getErr ( ) , input ) ) ; } | Sets the input stream to redirect to the process input stream . If this method is invoked multiple times each call overwrites the previous . |
31,291 | private static PumpStreamHandler redirectOutputAlsoTo ( PumpStreamHandler pumps , OutputStream output ) { if ( output == null ) throw new IllegalArgumentException ( "OutputStream must be provided." ) ; OutputStream current = pumps . getOut ( ) ; if ( current != null && ! ( current instanceof NullOutputStream ) ) { output = new TeeOutputStream ( current , output ) ; } return new PumpStreamHandler ( output , pumps . getErr ( ) , pumps . getInput ( ) ) ; } | Redirects the process output stream also to a given output stream . |
31,292 | protected final WaitForProcess startInternal ( ) throws IOException { listeners . beforeStart ( this ) ; if ( builder . command ( ) . isEmpty ( ) ) { throw new IllegalStateException ( "Command has not been set." ) ; } validateStreams ( streams , readOutput ) ; applyEnvironment ( ) ; messageLogger . message ( log , getExecutingLogMessage ( ) ) ; Process process = invokeStart ( ) ; messageLogger . message ( log , "Started {}" , process ) ; ProcessAttributes attributes = getAttributes ( ) ; ExecuteStreamHandler newStreams = streams ; ByteArrayOutputStream out = null ; if ( readOutput ) { PumpStreamHandler pumps = ( PumpStreamHandler ) streams ; out = new ByteArrayOutputStream ( ) ; newStreams = redirectOutputAlsoTo ( pumps , out ) ; } return startInternal ( process , attributes , newStreams , out ) ; } | Start the process and its stream handlers . |
31,293 | private ProcessAttributes getAttributes ( ) { return new ProcessAttributes ( getCommand ( ) , getDirectory ( ) , new LinkedHashMap < String , String > ( environment ) , allowedExitValues == null ? null : new HashSet < Integer > ( allowedExitValues ) ) ; } | Capture a snapshot of this process executor s main state . |
31,294 | private ProcessResult waitFor ( WaitForProcess task ) throws IOException , InterruptedException , TimeoutException { ProcessResult result ; if ( timeout == null ) { result = task . call ( ) ; } else { ExecutorService service = newExecutor ( task ) ; long _timeout = timeout ; TimeUnit unit = timeoutUnit ; try { result = invokeSubmit ( service , task ) . get ( _timeout , unit ) ; } catch ( ExecutionException e ) { Throwable c = e . getCause ( ) ; if ( c instanceof IOException ) { throw ( IOException ) c ; } if ( c instanceof InterruptedException ) { throw ( InterruptedException ) c ; } if ( c instanceof InvalidExitValueException ) { InvalidExitValueException i = ( InvalidExitValueException ) c ; throw new InvalidExitValueException ( i . getMessage ( ) , i . getResult ( ) ) ; } if ( c instanceof InvalidOutputException ) { InvalidOutputException i = ( InvalidOutputException ) c ; throw new InvalidOutputException ( i . getMessage ( ) , i . getResult ( ) ) ; } if ( c . getClass ( ) . equals ( InvalidResultException . class ) ) { InvalidResultException p = ( InvalidResultException ) c ; throw new InvalidResultException ( p . getMessage ( ) , p . getResult ( ) ) ; } throw new IllegalStateException ( "Error occured while waiting for process to finish:" , c ) ; } catch ( TimeoutException e ) { messageLogger . message ( log , "{} is running too long" , task ) ; throw newTimeoutException ( _timeout , unit , task ) ; } finally { service . shutdownNow ( ) ; } } return result ; } | Wait until the process stops a timeout occurs and the caller thread gets interrupted . In the latter cases the process gets destroyed as well . |
31,295 | protected < T > Future < T > invokeSubmit ( ExecutorService executor , Callable < T > task ) { return executor . submit ( wrapTask ( task ) ) ; } | Override this to customize how the waiting task is started in the background . |
31,296 | public void run ( ) { if ( shutDownHookExecuted ) { return ; } synchronized ( processes ) { running = true ; Enumeration e = processes . elements ( ) ; while ( e . hasMoreElements ( ) ) { destroy ( ( Process ) e . nextElement ( ) ) ; } processes . clear ( ) ; shutDownHookExecuted = true ; } } | Invoked by the VM when it is exiting . |
31,297 | public static void checkExit ( ProcessAttributes attributes , ProcessResult result ) { Set < Integer > allowedExitValues = attributes . getAllowedExitValues ( ) ; if ( allowedExitValues != null && ! allowedExitValues . contains ( result . getExitValue ( ) ) ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Unexpected exit value: " ) . append ( result . getExitValue ( ) ) ; sb . append ( ", allowed exit values: " ) . append ( allowedExitValues ) ; addExceptionMessageSuffix ( attributes , sb , result . hasOutput ( ) ? result . getOutput ( ) : null ) ; throw new InvalidExitValueException ( sb . toString ( ) , result ) ; } } | Check the process exit value . |
31,298 | protected BindingTemplate loadBindingTemplate ( String type ) { try ( final InputStream is = AddMojo . class . getResourceAsStream ( "/bindings.json" ) ) { final String bindingsJsonStr = IOUtil . toString ( is ) ; final BindingsTemplate bindingsTemplate = new ObjectMapper ( ) . readValue ( bindingsJsonStr , BindingsTemplate . class ) ; return bindingsTemplate . getBindingTemplateByName ( type ) ; } catch ( IOException e ) { warning ( LOAD_BINDING_TEMPLATES_FAIL ) ; return null ; } } | region Load templates |
31,299 | protected FunctionTemplate getFunctionTemplate ( final List < FunctionTemplate > templates ) throws Exception { info ( "" ) ; info ( FIND_TEMPLATE ) ; if ( settings != null && ! settings . isInteractiveMode ( ) ) { assureInputInBatchMode ( getFunctionTemplate ( ) , str -> getTemplateNames ( templates ) . stream ( ) . filter ( Objects :: nonNull ) . anyMatch ( o -> o . equalsIgnoreCase ( str ) ) , this :: setFunctionTemplate , true ) ; } else { assureInputFromUser ( "template for new function" , getFunctionTemplate ( ) , getTemplateNames ( templates ) , this :: setFunctionTemplate ) ; } return findTemplateByName ( templates , getFunctionTemplate ( ) ) ; } | region Get function template |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.