idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
37,100
public String processSearchRequest ( final SearchRequest request ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "Search for " ) ; if ( request . getDatabaseCode ( ) != null ) { builder . append ( "code " ) ; builder . append ( request . getDatabaseCode ( ) ) ; } if ( request . getQuery ( ) != null ) { builder . append ( " with query " ) ; builder . append ( request . getQuery ( ) ) ; } if ( request . getPageNumber ( ) != null ) { builder . append ( " page " ) ; builder . append ( request . getPageNumber ( ) ) ; } if ( request . getMaxPerPage ( ) != null ) { builder . append ( " limited to " ) ; builder . append ( request . getMaxPerPage ( ) ) ; builder . append ( " per page" ) ; } return builder . toString ( ) ; }
Process a search request into a descriptive title string .
37,101
public static String toPrettyPrintedString ( final JSONObject jsonObject ) { ArgumentChecker . notNull ( jsonObject , "jsonObject" ) ; try { return jsonObject . toString ( JSON_INDENT ) + LINE_SEPARATOR ; } catch ( JSONException ex ) { s_logger . error ( "Problem converting JSONObject to String" , ex ) ; throw new QuandlRuntimeException ( "Problem converting JSONObject to String" , ex ) ; } }
Pretty print a JSONObject as an indented piece of JSON code . Throws a QuandlRuntimeException if it can t render the JSONObject to a String .
37,102
public static String toPrettyPrintedString ( final TabularResult result ) { ArgumentChecker . notNull ( result , "result" ) ; StringBuilder sb = new StringBuilder ( ) ; int [ ] maxWidths = maximumWidths ( result ) ; separator ( sb , maxWidths ) ; header ( sb , maxWidths , result . getHeaderDefinition ( ) ) ; separator ( sb , maxWidths ) ; for ( final Row row : result ) { row ( sb , maxWidths , row ) ; } separator ( sb , maxWidths ) ; return sb . toString ( ) ; }
Pretty print a TabularResult in a text - based table format .
37,103
protected void readFile ( ) throws IOException { String line ; try ( BufferedReader reader = new BufferedReader ( new InputStreamReader ( stream ) ) ) { while ( ( line = reader . readLine ( ) ) != null ) { if ( line . contains ( BEGIN_MARKER ) ) { beginMarker = line . trim ( ) ; String endMarker = beginMarker . replace ( "BEGIN" , "END" ) ; derBytes = readBytes ( reader , endMarker ) ; return ; } } throw new IOException ( "Invalid PEM file: no begin marker" ) ; } }
Read the PEM file and save the DER encoded octet stream and begin marker .
37,104
private static byte [ ] readBytes ( BufferedReader reader , String endMarker ) throws IOException { String line = null ; StringBuilder buf = new StringBuilder ( ) ; while ( ( line = reader . readLine ( ) ) != null ) { if ( line . contains ( endMarker ) ) { return Base64 . getDecoder ( ) . decode ( buf . toString ( ) ) ; } buf . append ( line . trim ( ) ) ; } throw new IOException ( "Invalid PEM file: No end marker" ) ; }
Read the lines between BEGIN and END marker and convert the Base64 encoded content into binary byte array .
37,105
private int getLength ( ) throws IOException { int i = in . read ( ) ; if ( i == - 1 ) throw new IOException ( "Invalid DER: length missing" ) ; if ( ( i & ~ 0x7F ) == 0 ) return i ; int num = i & 0x7F ; if ( i >= 0xFF || num > 4 ) throw new IOException ( "Invalid DER: length field too big (" + i + ")" ) ; byte [ ] bytes = new byte [ num ] ; int n = in . read ( bytes ) ; if ( n < num ) throw new IOException ( "Invalid DER: length too short" ) ; return new BigInteger ( 1 , bytes ) . intValue ( ) ; }
Decode the length of the field . Can only support length encoding up to 4 octets .
37,106
protected boolean podRunning ( Json podStatus ) { if ( podStatus == null ) { return false ; } log . trace ( "Determining pod status" ) ; String phase = Optional . ofNullable ( podStatus . at ( "phase" ) ) . map ( Json :: asString ) . orElse ( "not running" ) ; log . trace ( " status.phase=%s" , phase ) ; if ( ! phase . equalsIgnoreCase ( "Running" ) ) { return false ; } String statusMessage = Optional . ofNullable ( podStatus . at ( "message" ) ) . map ( Json :: asString ) . orElse ( null ) ; String statusReason = Optional . ofNullable ( podStatus . at ( "reason" ) ) . map ( Json :: asString ) . orElse ( null ) ; log . trace ( " status.message=%s and status.reason=%s" , statusMessage , statusReason ) ; if ( statusMessage != null || statusReason != null ) { return false ; } List < Json > containerStatuses = Optional . ofNullable ( podStatus . at ( "containerStatuses" ) ) . map ( Json :: asJsonList ) . orElse ( Collections . emptyList ( ) ) ; boolean ready = true ; for ( Json containerStatus : containerStatuses ) { ready = ready && containerStatus . at ( "ready" ) . asBoolean ( ) ; } log . trace ( " containerStatuses[].status of all container is %s" , Boolean . toString ( ready ) ) ; if ( ! ready ) { return false ; } Boolean readyCondition = Boolean . FALSE ; List < Json > conditions = podStatus . at ( "conditions" ) . asJsonList ( ) ; for ( Json condition : conditions ) { String type = condition . at ( "type" ) . asString ( ) ; if ( type . equalsIgnoreCase ( "Ready" ) ) { readyCondition = new Boolean ( condition . at ( "status" ) . asString ( ) ) ; } } log . trace ( "conditions with type==\"Ready\" has status property value = %s" , readyCondition . toString ( ) ) ; if ( ! readyCondition . booleanValue ( ) ) { return false ; } return true ; }
Helper method to determine if a pod is considered running or not .
37,107
public String getString ( ) throws IOException { String encoding ; switch ( type ) { case DerParser . NUMERIC_STRING : case DerParser . PRINTABLE_STRING : case DerParser . VIDEOTEX_STRING : case DerParser . IA5_STRING : case DerParser . GRAPHIC_STRING : case DerParser . ISO646_STRING : case DerParser . GENERAL_STRING : encoding = "ISO-8859-1" ; break ; case DerParser . BMP_STRING : encoding = "UTF-16BE" ; break ; case DerParser . UTF8_STRING : encoding = "UTF-8" ; break ; case DerParser . UNIVERSAL_STRING : throw new IOException ( "Invalid DER: can't handle UCS-4 string" ) ; default : throw new IOException ( "Invalid DER: object is not a string" ) ; } return new String ( value , encoding ) ; }
Get value as string . Most strings are treated as Latin - 1 .
37,108
public byte [ ] forecastJsonBytes ( ForecastRequest request ) throws ForecastException { notNull ( "The ForecastRequest cannot be null." , request ) ; logger . log ( Level . FINE , "Executing Forecat request: {0}" , request ) ; try ( InputStream is = executeForecastRequest ( request ) ) { return IOUtil . readFully ( is ) ; } catch ( IOException e ) { throw new ForecastException ( "Forecast cannot be fetched." , e ) ; } }
Returns the forecast response as bytes .
37,109
public String getValue ( String keyMsgType ) throws IOException { if ( keyToValue . containsKey ( keyMsgType ) ) { return keyToValue . get ( keyMsgType ) ; } else { throw new IOException ( "Key " + keyMsgType + " doesn't exist in " + keyToValue ) ; } }
Gets the value associated with the key from the message . This version throws an exception if the key is not available and should be used for mandatory fields
37,110
public String getValueWithDefault ( String keyMsgType , String defaultVal ) { return keyToValue . getOrDefault ( keyMsgType , defaultVal ) ; }
Gets the value associated with the key from the message if it exists in the underlying map . This version returns the default value if it does not exist .
37,111
public int getValueAsIntWithDefault ( String keyIdField , int defaultVal ) throws IOException { if ( keyToValue . containsKey ( keyIdField ) ) { return Integer . parseInt ( getValue ( keyIdField ) ) ; } else return defaultVal ; }
Calls the getValue method first and the converts to an integer .
37,112
public void onCopyToClipboard ( ActionEvent actionEvent ) { Clipboard systemClipboard = Clipboard . getSystemClipboard ( ) ; ClipboardContent content = new ClipboardContent ( ) ; content . putString ( loggingArea . getText ( ) ) ; systemClipboard . setContent ( content ) ; }
A shortcut button to get the contents of the logger window into the clipboard .
37,113
public MenuState < String > newMenuState ( String value , boolean changed , boolean active ) { return new StringMenuState ( changed , active , value ) ; }
Returns a new String current value that can be used as the current value in the Menutree
37,114
public static int getVersionFromProperties ( ) { String ver = version . get ( ) ; if ( ver == null ) { try { InputStream resourceAsStream = ProtocolUtil . class . getResourceAsStream ( "/japi-version.properties" ) ; Properties props = new Properties ( ) ; props . load ( resourceAsStream ) ; ver = props . getProperty ( "build.version" ) ; Matcher verMatch = versionPattern . matcher ( ver ) ; if ( verMatch . matches ( ) && verMatch . groupCount ( ) == 2 ) { int major = Integer . parseInt ( verMatch . group ( 1 ) ) ; int minor = Integer . parseInt ( verMatch . group ( 2 ) ) ; return ( major * 100 ) + minor ; } } catch ( Exception e ) { System . getLogger ( "ProtocolUtil" ) . log ( ERROR , "Did not successfully obtain version" , e ) ; } } return 0 ; }
gets and caches the current version from the version properties file
37,115
public static ApiPlatform fromKeyToApiPlatform ( int key ) { if ( keyToPlatform . get ( ) == null ) { Map < Integer , ApiPlatform > map = new HashMap < > ( ) ; for ( ApiPlatform apiPlatform : ApiPlatform . values ( ) ) { map . put ( apiPlatform . getKey ( ) , apiPlatform ) ; } keyToPlatform . set ( Collections . unmodifiableMap ( map ) ) ; } return keyToPlatform . get ( ) . get ( key ) ; }
get the api platform given it s integer key value .
37,116
protected void processMessagesOnConnection ( ) { try { logger . log ( INFO , "Connected to " + getConnectionName ( ) ) ; state . set ( StreamState . CONNECTED ) ; notifyConnection ( ) ; inputBuffer . flip ( ) ; while ( ! Thread . currentThread ( ) . isInterrupted ( ) && isConnected ( ) ) { try { byte byStart = 0 ; while ( byStart != START_OF_MSG && ! Thread . currentThread ( ) . isInterrupted ( ) && isConnected ( ) ) { byStart = nextByte ( inputBuffer ) ; } readCompleteMessage ( inputBuffer ) ; if ( inputBuffer . get ( ) != protocol . getKeyIdentifier ( ) ) throw new TcProtocolException ( "Bad protocol" ) ; logByteBuffer ( "Line read from stream" , inputBuffer ) ; MenuCommand mc = protocol . fromChannel ( inputBuffer ) ; logger . log ( INFO , "Command received: " + mc ) ; notifyListeners ( mc ) ; } catch ( TcProtocolException ex ) { logger . log ( WARNING , "Probable Bad message reason='{0}' Remote={1} " , ex . getMessage ( ) , getConnectionName ( ) ) ; } } logger . log ( INFO , "Disconnected from " + getConnectionName ( ) ) ; } catch ( Exception e ) { logger . log ( ERROR , "Problem with connectivity on " + getConnectionName ( ) , e ) ; } finally { close ( ) ; } }
This is the loop that handles a connection by reading messages until there s an IOException or the transport or thread change to an end state .
37,117
public void sendMenuCommand ( MenuCommand msg ) throws IOException { if ( isConnected ( ) ) { synchronized ( outputBuffer ) { cmdBuffer . clear ( ) ; protocol . toChannel ( cmdBuffer , msg ) ; cmdBuffer . flip ( ) ; outputBuffer . clear ( ) ; outputBuffer . put ( START_OF_MSG ) ; outputBuffer . put ( protocol . getKeyIdentifier ( ) ) ; outputBuffer . put ( cmdBuffer ) ; outputBuffer . flip ( ) ; logByteBuffer ( "Sending message on " + getConnectionName ( ) , outputBuffer ) ; sendInternal ( outputBuffer ) ; outputBuffer . clear ( ) ; } } else { throw new IOException ( "Not connected to port" ) ; } }
Sends a command to the remote with the protocol and usual headers .
37,118
private byte nextByte ( ByteBuffer inputBuffer ) throws IOException { getAtLeastBytes ( inputBuffer , 1 , ReadMode . ONLY_WHEN_EMPTY ) ; return inputBuffer . get ( ) ; }
Reads the next available byte from the input buffer provided waiting if data is not available .
37,119
public void registerConnectionChangeListener ( ConnectionChangeListener listener ) { connectionListeners . add ( listener ) ; executor . execute ( ( ) -> listener . connectionChange ( this , isConnected ( ) ) ) ; }
Register for connection change events when there is a change in connectivity status on the underlying transport .
37,120
protected void logByteBuffer ( String msg , ByteBuffer inBuffer ) { if ( ! logger . isLoggable ( DEBUG ) ) return ; ByteBuffer bb = inBuffer . duplicate ( ) ; byte [ ] byData = new byte [ 512 ] ; int len = Math . min ( byData . length , bb . remaining ( ) ) ; byte dataByte = bb . get ( ) ; int pos = 0 ; while ( pos < len && dataByte != '~' ) { byData [ pos ] = dataByte ; pos ++ ; dataByte = bb . get ( ) ; } logger . log ( DEBUG , msg + ". Content: " + new String ( byData , 0 , pos ) ) ; }
Helper method that logs the entire message buffer when at debug logging level .
37,121
public CodeVariableBuilder paramFromPropertyWithDefault ( String property , String defVal ) { params . add ( new PropertyWithDefaultParameter ( property , defVal ) ) ; return this ; }
This parameter will be based on the value of a property if the property is empty or missing then the replacement default will be used .
37,122
protected void loadModules ( String sourceDir , Collection < String > moduleNames ) { ModuleFinder finder = ModuleFinder . of ( Paths . get ( sourceDir ) ) ; ClassLoader scl = ClassLoader . getSystemClassLoader ( ) ; ModuleLayer parent = ModuleLayer . boot ( ) ; Configuration cf = parent . configuration ( ) . resolve ( finder , ModuleFinder . of ( ) , moduleNames ) ; layer = parent . defineModulesWithOneLoader ( cf , scl ) ; }
Load all the modules that were configured into the main class loader we don t want any additional class loaders we just want to load the classes in .
37,123
private CodePluginConfig parsePluginConfig ( InputStream inputStream ) { Gson gson = new Gson ( ) ; CodePluginConfig config = gson . fromJson ( new InputStreamReader ( inputStream ) , CodePluginConfig . class ) ; logger . log ( Level . INFO , "Loaded configuration " + config ) ; return config ; }
Create a plugin config object from JSON format .
37,124
public void start ( ) { connector . registerConnectorListener ( this :: onCommandReceived ) ; connector . registerConnectionChangeListener ( this :: onConnectionChange ) ; connector . start ( ) ; executor . scheduleAtFixedRate ( this :: checkHeartbeat , 1000 , 1000 , TimeUnit . MILLISECONDS ) ; }
starts the remote connection such that it will attempt to establish connectivity
37,125
public void sendCommand ( MenuCommand command ) { lastTx . set ( clock . millis ( ) ) ; try { connector . sendMenuCommand ( command ) ; } catch ( IOException e ) { logger . log ( ERROR , "Error while writing out command" , e ) ; connector . close ( ) ; } }
send a command to the Arduino normally use the CommandFactory to generate the command
37,126
protected String safeStringFromProperty ( StringProperty stringProperty , String field , List < FieldError > errorsBuilder , int maxLen , StringFieldType fieldType ) { String s = stringProperty . get ( ) ; if ( fieldType == StringFieldType . OPTIONAL && s . length ( ) > maxLen ) { errorsBuilder . add ( new FieldError ( "field must be less than " + maxLen + " characters" , field ) ) ; } else if ( fieldType != StringFieldType . OPTIONAL && ( s . length ( ) > maxLen || s . isEmpty ( ) ) ) { errorsBuilder . add ( new FieldError ( "field must not be blank and less than " + maxLen + " characters" , field ) ) ; } if ( fieldType == StringFieldType . VARIABLE && ! s . matches ( "^[\\p{L}_$][\\p{L}\\p{N}_]*$" ) ) { errorsBuilder . add ( new FieldError ( "Function fields must use only letters, digits, and '_'" , field ) ) ; } else if ( ! s . matches ( "^[\\p{L}\\p{N}\\s\\-_*%()]*$" ) ) { errorsBuilder . add ( new FieldError ( "Text can only contain letters, numbers, spaces and '-_()*%'" , field ) ) ; } return s ; }
Gets the string value from a text field and validates it is correct in terms of length and content .
37,127
protected int safeIntFromProperty ( StringProperty strProp , String field , List < FieldError > errorsBuilder , int min , int max ) { String s = strProp . get ( ) ; if ( StringHelper . isStringEmptyOrNull ( s ) ) { return 0 ; } int val = 0 ; try { val = Integer . valueOf ( s ) ; if ( val < min || val > max ) { errorsBuilder . add ( new FieldError ( "Value must be between " + min + " and " + max , field ) ) ; } } catch ( NumberFormatException e ) { errorsBuilder . add ( new FieldError ( "Value must be a number" , field ) ) ; } return val ; }
Gets the integer value from a text field property and validates it again the conditions provided . It must be a number and within the ranges provided .
37,128
public MenuState < Integer > newMenuState ( Integer value , boolean changed , boolean active ) { return new IntegerMenuState ( changed , active , value ) ; }
returns a new state object that represents the current value for the menu . Current values are held separately to the items see MenuTree
37,129
public static boolean setAboutHandler ( Object target , Method aboutHandler ) { boolean enableAboutMenu = ( target != null && aboutHandler != null ) ; if ( enableAboutMenu ) { setHandler ( new OSXAdapter ( "handleAbout" , target , aboutHandler ) ) ; } try { Method enableAboutMethod = macOSXApplication . getClass ( ) . getDeclaredMethod ( "setEnabledAboutMenu" , new Class [ ] { boolean . class } ) ; enableAboutMethod . invoke ( macOSXApplication , new Object [ ] { Boolean . valueOf ( enableAboutMenu ) } ) ; return true ; } catch ( Exception ex ) { System . err . println ( "OSXAdapter could not access the About Menu" ) ; ex . printStackTrace ( ) ; return false ; } }
They will be called when the About menu item is selected from the application menu
37,130
public static void setPreferencesHandler ( Object target , Method prefsHandler ) { boolean enablePrefsMenu = ( target != null && prefsHandler != null ) ; if ( enablePrefsMenu ) { setHandler ( new OSXAdapter ( "handlePreferences" , target , prefsHandler ) ) ; } try { Method enablePrefsMethod = macOSXApplication . getClass ( ) . getDeclaredMethod ( "setEnabledPreferencesMenu" , new Class [ ] { boolean . class } ) ; enablePrefsMethod . invoke ( macOSXApplication , new Object [ ] { Boolean . valueOf ( enablePrefsMenu ) } ) ; } catch ( Exception ex ) { System . err . println ( "OSXAdapter could not access the About Menu" ) ; ex . printStackTrace ( ) ; } }
They will be called when the Preferences menu item is selected from the application menu
37,131
public static void setFileHandler ( Object target , Method fileHandler ) { setHandler ( new OSXAdapter ( "handleOpenFile" , target , fileHandler ) { public boolean callTarget ( Object appleEvent ) { if ( appleEvent != null ) { try { Method getFilenameMethod = appleEvent . getClass ( ) . getDeclaredMethod ( "getFilename" , ( Class [ ] ) null ) ; String filename = ( String ) getFilenameMethod . invoke ( appleEvent , ( Object [ ] ) null ) ; this . targetMethod . invoke ( this . targetObject , new Object [ ] { filename } ) ; } catch ( Exception ex ) { } } return true ; } } ) ; }
application bundle s Info . plist
37,132
public static void setHandler ( OSXAdapter adapter ) { try { Class < ? > applicationClass = Class . forName ( "com.apple.eawt.Application" ) ; if ( macOSXApplication == null ) { macOSXApplication = applicationClass . getConstructor ( ( Class [ ] ) null ) . newInstance ( ( Object [ ] ) null ) ; } Class < ? > applicationListenerClass = Class . forName ( "com.apple.eawt.ApplicationListener" ) ; Method addListenerMethod = applicationClass . getDeclaredMethod ( "addApplicationListener" , new Class [ ] { applicationListenerClass } ) ; Object osxAdapterProxy = Proxy . newProxyInstance ( OSXAdapter . class . getClassLoader ( ) , new Class [ ] { applicationListenerClass } , adapter ) ; addListenerMethod . invoke ( macOSXApplication , new Object [ ] { osxAdapterProxy } ) ; } catch ( ClassNotFoundException cnfe ) { System . err . println ( "This version of Mac OS X does not support the Apple EAWT. ApplicationEvent handling has been disabled (" + cnfe + ")" ) ; } catch ( Exception ex ) { System . err . println ( "Mac OS X Adapter could not talk to EAWT:" ) ; ex . printStackTrace ( ) ; } }
setHandler creates a Proxy object from the passed OSXAdapter and adds it as an ApplicationListener
37,133
public boolean callTarget ( Object appleEvent ) throws InvocationTargetException , IllegalAccessException { Object result = targetMethod . invoke ( targetObject , ( Object [ ] ) null ) ; if ( result == null ) { return true ; } return Boolean . valueOf ( result . toString ( ) ) . booleanValue ( ) ; }
See setFileHandler above for an example
37,134
public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { if ( isCorrectMethod ( method , args ) ) { boolean handled = callTarget ( args [ 0 ] ) ; setApplicationEventHandled ( args [ 0 ] , handled ) ; } return null ; }
This is the entry point for our proxy object ; it is called every time an ApplicationListener method is invoked
37,135
protected void setApplicationEventHandled ( Object event , boolean handled ) { if ( event != null ) { try { Method setHandledMethod = event . getClass ( ) . getDeclaredMethod ( "setHandled" , new Class [ ] { boolean . class } ) ; setHandledMethod . invoke ( event , new Object [ ] { Boolean . valueOf ( handled ) } ) ; } catch ( Exception ex ) { System . err . println ( "OSXAdapter was unable to handle an ApplicationEvent: " + event ) ; ex . printStackTrace ( ) ; } } }
This method checks for a boolean result from the proxy method and sets the event accordingly
37,136
public static < T > Optional < T > visitWithResult ( MenuItem item , AbstractMenuItemVisitor < T > visitor ) { item . accept ( visitor ) ; return visitor . getResult ( ) ; }
Visits a menu item calling the appropriate function for the type and collects the result that is set by calling your visitor s setResult method .
37,137
public static SubMenuItem asSubMenu ( MenuItem item ) { return visitWithResult ( item , new AbstractMenuItemVisitor < SubMenuItem > ( ) { public void visit ( SubMenuItem item ) { setResult ( item ) ; } public void anyItem ( MenuItem item ) { } } ) . orElse ( null ) ; }
Returns the menu item as a sub menu or null
37,138
public static MenuItem createFromExistingWithId ( MenuItem selected , int newId ) { return visitWithResult ( selected , new AbstractMenuItemVisitor < MenuItem > ( ) { public void visit ( AnalogMenuItem item ) { setResult ( AnalogMenuItemBuilder . anAnalogMenuItemBuilder ( ) . withExisting ( item ) . withId ( newId ) . menuItem ( ) ) ; } public void visit ( BooleanMenuItem item ) { setResult ( BooleanMenuItemBuilder . aBooleanMenuItemBuilder ( ) . withExisting ( item ) . withId ( newId ) . menuItem ( ) ) ; } public void visit ( EnumMenuItem item ) { setResult ( EnumMenuItemBuilder . anEnumMenuItemBuilder ( ) . withExisting ( item ) . withId ( newId ) . menuItem ( ) ) ; } public void visit ( SubMenuItem item ) { setResult ( SubMenuItemBuilder . aSubMenuItemBuilder ( ) . withExisting ( item ) . withId ( newId ) . menuItem ( ) ) ; } public void visit ( TextMenuItem item ) { setResult ( TextMenuItemBuilder . aTextMenuItemBuilder ( ) . withExisting ( item ) . withId ( newId ) . menuItem ( ) ) ; } public void visit ( RemoteMenuItem item ) { setResult ( RemoteMenuItemBuilder . aRemoteMenuItemBuilder ( ) . withExisting ( item ) . withId ( newId ) . menuItem ( ) ) ; } public void visit ( FloatMenuItem item ) { setResult ( FloatMenuItemBuilder . aFloatMenuItemBuilder ( ) . withExisting ( item ) . withId ( newId ) . menuItem ( ) ) ; } public void visit ( ActionMenuItem item ) { setResult ( ActionMenuItemBuilder . anActionMenuItemBuilder ( ) . withExisting ( item ) . withId ( newId ) . menuItem ( ) ) ; } } ) . orElse ( null ) ; }
creates a copy of the menu item chosen with the ID changed to newId
37,139
public static int eepromSizeForItem ( MenuItem item ) { return MenuItemHelper . visitWithResult ( item , new AbstractMenuItemVisitor < Integer > ( ) { public void visit ( AnalogMenuItem item ) { setResult ( 2 ) ; } public void visit ( BooleanMenuItem item ) { setResult ( 1 ) ; } public void visit ( EnumMenuItem item ) { setResult ( 2 ) ; } public void visit ( TextMenuItem item ) { setResult ( item . getTextLength ( ) ) ; } public void anyItem ( MenuItem item ) { setResult ( 0 ) ; } } ) . orElse ( 0 ) ; }
Gets the size of the eeprom storage for a given element type
37,140
public static PluginFileDependency fileInTcMenu ( String file ) { return new PluginFileDependency ( file , PackagingType . WITHIN_TCMENU , Map . of ( ) ) ; }
Creates an instance of the class that indicates the file is within tcMenu itself . Don t use for new plugins prefer to package arduino code in the plugin or a new library .
37,141
public void initialise ( String root ) { functionCalls . clear ( ) ; variables . clear ( ) ; initCreator ( root ) ; }
Do not override this use initCreator
37,142
protected void addExportVariableIfPresent ( String variable , String typeName ) { String expVar = findPropertyValue ( variable ) . getLatestValue ( ) ; if ( expVar != null && ! expVar . isEmpty ( ) ) { addVariable ( new CodeVariableBuilder ( ) . exportOnly ( ) . variableType ( typeName ) . variableName ( expVar ) ) ; } }
Adds a variable for export only when a property is present
37,143
protected void addLibraryFiles ( String ... files ) { libraryFiles . addAll ( Arrays . stream ( files ) . map ( PluginFileDependency :: fileInTcMenu ) . collect ( Collectors . toList ( ) ) ) ; }
adds requirements on one or more files that must be copied into the project this is only for files that already exist in tcMenu library prefer to use the other version that takes PluiginFileDependency
37,144
public CreatorProperty findPropertyValue ( String name ) { return properties ( ) . stream ( ) . filter ( p -> name . equals ( p . getName ( ) ) ) . findFirst ( ) . orElse ( EMPTY ) ; }
Gets a property by it s name
37,145
public int findPropertyValueAsIntWithDefault ( String name , int defVal ) { return properties ( ) . stream ( ) . filter ( p -> name . equals ( p . getName ( ) ) ) . map ( CreatorProperty :: getLatestValueAsInt ) . findFirst ( ) . orElse ( defVal ) ; }
Find the integer value of a property or a default if it is not set
37,146
private Optional < String > getArduinoPathWithDialog ( ) { String savedPath = Preferences . userNodeForPackage ( ArduinoLibraryInstaller . class ) . get ( ARDUINO_CUSTOM_PATH , homeDirectory ) ; Path libsPath = Paths . get ( savedPath , "libraries" ) ; if ( Files . exists ( libsPath ) ) return Optional . of ( savedPath ) ; TextInputDialog dialog = new TextInputDialog ( savedPath ) ; dialog . setTitle ( "Manually enter Arduino Path" ) ; dialog . setHeaderText ( "Please manually enter the full path to the Arduino folder" ) ; dialog . setContentText ( "Arduino Path" ) ; Optional < String > path = dialog . showAndWait ( ) ; path . ifPresent ( ( p ) -> Preferences . userNodeForPackage ( ArduinoLibraryInstaller . class ) . put ( ARDUINO_CUSTOM_PATH , p ) ) ; return path ; }
This method will be called internally by the above method when a non standard layout is detected .
37,147
public Optional < Path > findLibraryInstall ( String libraryName ) { return getArduinoDirectory ( ) . map ( path -> { Path libsDir = path . resolve ( "libraries" ) ; Path tcMenuDir = libsDir . resolve ( libraryName ) ; if ( Files . exists ( tcMenuDir ) ) { return tcMenuDir ; } return null ; } ) ; }
Find the library installation of a specific named library using standard conventions
37,148
public VersionInfo getVersionOfLibrary ( String name , boolean inEmbeddedDir ) throws IOException { Path startPath ; if ( inEmbeddedDir ) { startPath = Paths . get ( embeddedDirectory , name ) ; } else { Path ardDir = getArduinoDirectory ( ) . orElseThrow ( IOException :: new ) ; startPath = ardDir . resolve ( "libraries" ) . resolve ( name ) ; } Path libProps = startPath . resolve ( LIBRARY_PROPERTIES_NAME ) ; if ( ! Files . exists ( libProps ) ) { return new VersionInfo ( "0.0.0" ) ; } Properties propsSrc = new Properties ( ) ; try ( FileReader reader = new FileReader ( libProps . toFile ( ) ) ) { propsSrc . load ( reader ) ; } return new VersionInfo ( propsSrc . getProperty ( "version" , "0.0.0" ) ) ; }
Get the version of a library either from the packaged version or currently installed depending how it s called .
37,149
public boolean isLibraryUpToDate ( String name ) { Optional < Path > libInst = findLibraryInstall ( name ) ; if ( ! libInst . isPresent ( ) ) return false ; try { VersionInfo srcVer = getVersionOfLibrary ( name , true ) ; VersionInfo dstVer = getVersionOfLibrary ( name , false ) ; return dstVer . isSameOrNewerThan ( srcVer ) ; } catch ( IOException e ) { return false ; } }
Check if the named library is the same version or new than the packaged version
37,150
public void copyLibraryFromPackage ( String libraryName ) throws IOException { Path ardDir = getArduinoDirectory ( ) . orElseThrow ( IOException :: new ) ; Path source = Paths . get ( embeddedDirectory ) . resolve ( libraryName ) ; Path dest = ardDir . resolve ( "libraries/" + libraryName ) ; if ( ! Files . exists ( dest ) ) { Files . createDirectory ( dest ) ; } Path gitRepoDir = dest . resolve ( ".git" ) ; if ( Files . exists ( gitRepoDir ) ) { throw new IOException ( "Git repository inside " + libraryName + "! Not proceeding to update path : " + dest ) ; } copyLibraryRecursive ( source , dest ) ; }
Copies the library from the packaged version into the installation directory .
37,151
private void copyLibraryRecursive ( Path input , Path output ) throws IOException { for ( Path dirItem : Files . list ( input ) . collect ( Collectors . toList ( ) ) ) { Path outputName = output . resolve ( dirItem . getFileName ( ) ) ; if ( Files . isDirectory ( dirItem ) ) { if ( ! Files . exists ( outputName ) ) Files . createDirectory ( outputName ) ; copyLibraryRecursive ( dirItem , outputName ) ; } else { Files . copy ( dirItem , outputName , StandardCopyOption . REPLACE_EXISTING ) ; } } }
Recursive copier for the above copy method . It calls recursively for subdirectories to ensure a full copy
37,152
public void initialise ( MenuTree menuTree , RemoteMenuController remoteControl ) { this . menuTree = menuTree ; this . remoteControl = remoteControl ; executor . scheduleAtFixedRate ( this :: updatedFieldChecker , 1000 , 100 , TimeUnit . MILLISECONDS ) ; remoteControl . addListener ( new RemoteControllerListener ( ) { public void menuItemChanged ( MenuItem item , boolean valueOnly ) { Platform . runLater ( ( ) -> renderItemValue ( item ) ) ; } public void treeFullyPopulated ( ) { Platform . runLater ( ( ) -> { menuLoadLabel . setText ( "YES" ) ; itemGrid . getChildren ( ) . clear ( ) ; buildGrid ( MenuTree . ROOT , 10 , 0 ) ; } ) ; } public void connectionState ( RemoteInformation remoteInformation , boolean con ) { remoteInfo = Optional . ofNullable ( remoteInformation ) ; connected = con ; Platform . runLater ( MainWindowController . this :: updateConnectionDetails ) ; } } ) ; remoteControl . start ( ) ; }
initialise is called by the App to start the application up . In here we register a listener for communication events and start the comms .
37,153
private int buildGrid ( SubMenuItem subMenu , int inset , int gridPosition ) { for ( MenuItem item : menuTree . getMenuItems ( subMenu ) ) { if ( item . hasChildren ( ) ) { Label itemLbl = new Label ( "SubMenu " + item . getName ( ) ) ; itemLbl . setPadding ( new Insets ( 12 , 10 , 12 , inset ) ) ; itemLbl . setStyle ( "-fx-font-weight: bold; -fx-font-size: 120%;" ) ; itemGrid . add ( itemLbl , 0 , gridPosition ++ , 2 , 1 ) ; gridPosition = buildGrid ( MenuItemHelper . asSubMenu ( item ) , inset + 10 , gridPosition ) ; } else { Label itemLbl = new Label ( item . getName ( ) ) ; itemLbl . setPadding ( new Insets ( 3 , 10 , 3 , inset ) ) ; itemGrid . add ( itemLbl , 0 , gridPosition ) ; itemGrid . add ( createUiControlForItem ( item ) , 1 , gridPosition ) ; renderItemValue ( item ) ; gridPosition ++ ; } } return gridPosition ; }
Here we go through all the menu items and populate a GridPane with controls to display and edit each item . We start at ROOT and through every item in all submenus . This is a recursive function that is repeatedly called on sub menu s until we ve finished all items .
37,154
private void renderItemValue ( MenuItem item ) { Label lblForVal = itemIdToLabel . get ( item . getId ( ) ) ; if ( lblForVal == null ) return ; Optional < String > value = MenuItemHelper . visitWithResult ( item , new AbstractMenuItemVisitor < > ( ) { public void visit ( AnalogMenuItem item ) { MenuState < Integer > state = menuTree . getMenuState ( item ) ; if ( state != null ) { double val = ( double ) ( state . getValue ( ) + item . getOffset ( ) ) ; val = val / ( ( double ) item . getDivisor ( ) ) ; setResult ( String . format ( "%.2f%s" , val , item . getUnitName ( ) ) ) ; } } public void visit ( BooleanMenuItem item ) { MenuState < Boolean > state = menuTree . getMenuState ( item ) ; if ( state != null ) { switch ( item . getNaming ( ) ) { case ON_OFF : setResult ( state . getValue ( ) ? "ON" : "OFF" ) ; break ; case YES_NO : setResult ( state . getValue ( ) ? "YES" : "NO" ) ; break ; case TRUE_FALSE : default : setResult ( state . getValue ( ) ? "TRUE" : "FALSE" ) ; break ; } } } public void visit ( EnumMenuItem item ) { MenuState < Integer > state = menuTree . getMenuState ( item ) ; if ( state != null ) { setResult ( item . getEnumEntries ( ) . get ( state . getValue ( ) ) ) ; } } public void visit ( RemoteMenuItem item ) { MenuState < String > state = menuTree . getMenuState ( item ) ; if ( state != null ) { setResult ( state . getValue ( ) ) ; } } public void visit ( FloatMenuItem item ) { MenuState < Float > state = menuTree . getMenuState ( item ) ; if ( state != null ) { NumberFormat fmt = NumberFormat . getInstance ( ) ; fmt . setGroupingUsed ( false ) ; fmt . setMinimumFractionDigits ( item . getNumDecimalPlaces ( ) ) ; fmt . setMaximumFractionDigits ( item . getNumDecimalPlaces ( ) ) ; setResult ( fmt . format ( state . getValue ( ) ) ) ; } } public void visit ( TextMenuItem item ) { MenuState < String > state = menuTree . getMenuState ( item ) ; if ( state != null ) { setResult ( state . getValue ( ) ) ; } } public void anyItem ( MenuItem item ) { setResult ( "" ) ; } } ) ; lblForVal . setText ( value . orElse ( "Not Present" ) ) ; itemIdToChangeTicks . put ( item . getId ( ) , TICKS_HIGHLIGHT_ON_CHANGE ) ; }
When there s a change in value for an item this code takes care of rendering it .
37,155
private void updateConnectionDetails ( ) { Stage stage = ( Stage ) platformLabel . getScene ( ) . getWindow ( ) ; connectedLabel . setText ( connected ? "YES" : "NO" ) ; remoteInfo . ifPresent ( remote -> { remoteNameLabel . setText ( remote . getName ( ) ) ; versionLabel . setText ( remote . getMajorVersion ( ) + "." + remote . getMinorVersion ( ) ) ; platformLabel . setText ( remote . getPlatform ( ) . getDescription ( ) ) ; stage . setTitle ( "Connected to " + remote . getName ( ) ) ; } ) ; if ( ! connected ) { stage . setTitle ( "Disconnected [" + remoteControl . getConnector ( ) . getConnectionName ( ) + "]" ) ; menuLoadLabel . setText ( "NO" ) ; versionLabel . setText ( "" ) ; remoteNameLabel . setText ( "" ) ; } }
When the connectivity changes we update the fields on the FX thread we must not update any UI fields on the connection thread .
37,156
public void makeAdjustments ( Consumer < String > logger , String inoFile , String projectName , List < String > callbacks ) throws IOException { this . logger = logger ; changed = false ; Path source = Paths . get ( inoFile ) ; if ( ! Files . exists ( source ) ) { logger . accept ( "No existing infoFile, generating an empty one" ) ; Files . write ( source , ArduinoSketchFileAdjuster . EMPTY_SKETCH . getBytes ( ) ) ; } boolean needsInclude = true ; boolean needsTaskMgr = true ; boolean needsSetup = true ; List < String > callbacksDefined = new ArrayList < > ( ) ; for ( String line : Files . lines ( source ) . collect ( Collectors . toList ( ) ) ) { if ( line . contains ( "#include" ) && line . contains ( projectName + "_menu.h" ) ) { logger . accept ( "found include in INO" ) ; needsInclude = false ; } else if ( line . contains ( "taskManager.runLoop()" ) ) { logger . accept ( "found runLoop in INO" ) ; needsTaskMgr = false ; } else if ( line . contains ( "setupMenu(" ) ) { logger . accept ( "found setup in INO" ) ; needsSetup = false ; } else if ( line . contains ( "CALLBACK_FUNCTION" ) ) { Matcher fnMatch = FUNCTION_PATTERN . matcher ( line ) ; if ( fnMatch . matches ( ) ) { logger . accept ( "found callback for " + fnMatch . group ( 1 ) ) ; callbacksDefined . add ( fnMatch . group ( 1 ) ) ; } } } ArrayList < String > lines = new ArrayList < > ( Files . readAllLines ( source ) ) ; if ( needsInclude ) addIncludeToTopOfFile ( lines , projectName ) ; if ( needsSetup ) addSetupCode ( lines , SETUP_PATTERN , " setupMenu();" ) ; if ( needsTaskMgr ) addSetupCode ( lines , LOOP_PATTERN , " taskManager.runLoop();" ) ; List < String > callbacksToMake = new ArrayList < > ( callbacks ) ; callbacksToMake . removeAll ( callbacksDefined ) ; makeNewCallbacks ( lines , callbacksToMake ) ; if ( changed ) { logger . accept ( "INO Previously existed, backup existing file" ) ; Files . copy ( source , Paths . get ( source . toString ( ) + ".backup" ) , REPLACE_EXISTING ) ; logger . accept ( "Writing out changes to INO sketch file" ) ; Files . write ( Paths . get ( inoFile ) , lines ) ; } else { logger . accept ( "No changes to the INO file, not writing out" ) ; } }
Is able to update and round trip an ino file for the items that tcMenu needs .
37,157
public FunctionCallBuilder requiresHeader ( String headerName , boolean useQuotes ) { headers . add ( new HeaderDefinition ( headerName , useQuotes , HeaderDefinition . PRIORITY_NORMAL ) ) ; return this ; }
Add a requirement that a header file needs to be included for this to work
37,158
public void addMenuItem ( SubMenuItem parent , MenuItem item ) { SubMenuItem subMenu = ( parent != null ) ? parent : ROOT ; synchronized ( subMenuItems ) { ArrayList < MenuItem > subMenuChildren = subMenuItems . computeIfAbsent ( subMenu , sm -> new ArrayList < > ( ) ) ; subMenuChildren . add ( item ) ; if ( item . hasChildren ( ) ) { subMenuItems . put ( item , new ArrayList < > ( ) ) ; } } }
add a new menu item to a sub menu for the top level menu use ROOT .
37,159
public void addOrUpdateItem ( int parentId , MenuItem item ) { synchronized ( subMenuItems ) { getSubMenuById ( parentId ) . ifPresent ( subMenu -> { if ( getMenuItems ( subMenu ) . stream ( ) . anyMatch ( it -> it . getId ( ) == item . getId ( ) ) ) { replaceMenuById ( asSubMenu ( subMenu ) , item ) ; } else { addMenuItem ( asSubMenu ( subMenu ) , item ) ; } } ) ; } }
This will either add or update an existing item depending if the ID is already present .
37,160
public Optional < SubMenuItem > getSubMenuById ( int parentId ) { return getAllSubMenus ( ) . stream ( ) . filter ( subMenu -> subMenu . getId ( ) == parentId ) . map ( m -> ( SubMenuItem ) m ) . findFirst ( ) ; }
gets a submenu by it s ID . Returns an optional that will be empty when not present
37,161
public Optional < MenuItem > getMenuById ( SubMenuItem root , int id ) { return getMenuItems ( root ) . stream ( ) . filter ( item -> item . getId ( ) == id ) . findFirst ( ) ; }
Gets the menu item with the specified ID in a given submenu . If you don t know the sub menu call the findMenuItem to obtain the parent .
37,162
public void replaceMenuById ( SubMenuItem subMenu , MenuItem toReplace ) { synchronized ( subMenuItems ) { ArrayList < MenuItem > list = subMenuItems . get ( subMenu ) ; int idx = - 1 ; for ( int i = 0 ; i < list . size ( ) ; ++ i ) { if ( list . get ( i ) . getId ( ) == toReplace . getId ( ) ) { idx = i ; } } if ( idx != - 1 ) { MenuItem oldItem = list . set ( idx , toReplace ) ; if ( toReplace . hasChildren ( ) ) { ArrayList < MenuItem > items = subMenuItems . remove ( oldItem ) ; subMenuItems . put ( toReplace , items ) ; } } } }
Replace the menu item that has a given parent with the one provided
37,163
public void moveItem ( SubMenuItem parent , MenuItem newItem , MoveType moveType ) { synchronized ( subMenuItems ) { ArrayList < MenuItem > items = subMenuItems . get ( parent ) ; int idx = items . indexOf ( newItem ) ; if ( idx < 0 ) return ; items . remove ( idx ) ; idx = ( moveType == MoveType . MOVE_UP ) ? -- idx : ++ idx ; if ( idx < 0 ) idx = 0 ; if ( idx >= items . size ( ) ) { items . add ( newItem ) ; } else { items . add ( idx , newItem ) ; } } }
Moves the item either up or down in the list for that submenu
37,164
public SubMenuItem findParent ( MenuItem toFind ) { synchronized ( subMenuItems ) { SubMenuItem parent = MenuTree . ROOT ; for ( Map . Entry < MenuItem , ArrayList < MenuItem > > entry : subMenuItems . entrySet ( ) ) { for ( MenuItem item : entry . getValue ( ) ) { if ( item . getId ( ) == toFind . getId ( ) ) { parent = asSubMenu ( entry . getKey ( ) ) ; } } } return parent ; } }
Finds the submenu that the provided object belongs to .
37,165
public void removeMenuItem ( SubMenuItem parent , MenuItem item ) { SubMenuItem subMenu = ( parent != null ) ? parent : ROOT ; synchronized ( subMenuItems ) { ArrayList < MenuItem > subMenuChildren = subMenuItems . get ( subMenu ) ; if ( subMenuChildren == null ) { throw new UnsupportedOperationException ( "Menu element not found" ) ; } subMenuChildren . remove ( item ) ; if ( item . hasChildren ( ) ) { subMenuItems . remove ( item ) ; } } menuStates . remove ( item . getId ( ) ) ; }
Remove the menu item for the provided menu item in the provided sub menu .
37,166
public List < MenuItem > getMenuItems ( MenuItem item ) { synchronized ( subMenuItems ) { ArrayList < MenuItem > menuItems = subMenuItems . get ( item ) ; return menuItems == null ? null : Collections . unmodifiableList ( menuItems ) ; } }
Get a list of all menu items for a given submenu
37,167
public < T > void changeItem ( MenuItem < T > item , MenuState < T > menuState ) { menuStates . put ( item . getId ( ) , menuState ) ; }
Change the value that s associated with a menu item . if you are changing a value just send a command to the device it will automatically update the tree .
37,168
@ SuppressWarnings ( "unchecked" ) public < T > MenuState < T > getMenuState ( MenuItem < T > item ) { return ( MenuState < T > ) menuStates . get ( item . getId ( ) ) ; }
Gets the menu state that s associated with a given menu item . This is the current value for the menu item .
37,169
@ SuppressWarnings ( "unchecked" ) public static < T extends Number > T convertNumberToTargetClass ( Number number , Class < T > targetClass ) throws IllegalArgumentException { Assert . notNull ( number , "Number must not be null" ) ; Assert . notNull ( targetClass , "Target class must not be null" ) ; if ( targetClass . isInstance ( number ) ) { return ( T ) number ; } else if ( Byte . class == targetClass ) { long value = checkedLongValue ( number , targetClass ) ; if ( value < Byte . MIN_VALUE || value > Byte . MAX_VALUE ) { raiseOverflowException ( number , targetClass ) ; } return ( T ) Byte . valueOf ( number . byteValue ( ) ) ; } else if ( Short . class == targetClass ) { long value = checkedLongValue ( number , targetClass ) ; if ( value < Short . MIN_VALUE || value > Short . MAX_VALUE ) { raiseOverflowException ( number , targetClass ) ; } return ( T ) Short . valueOf ( number . shortValue ( ) ) ; } else if ( Integer . class == targetClass ) { long value = checkedLongValue ( number , targetClass ) ; if ( value < Integer . MIN_VALUE || value > Integer . MAX_VALUE ) { raiseOverflowException ( number , targetClass ) ; } return ( T ) Integer . valueOf ( number . intValue ( ) ) ; } else if ( Long . class == targetClass ) { long value = checkedLongValue ( number , targetClass ) ; return ( T ) Long . valueOf ( value ) ; } else if ( BigInteger . class == targetClass ) { if ( number instanceof BigDecimal ) { return ( T ) ( ( BigDecimal ) number ) . toBigInteger ( ) ; } else { return ( T ) BigInteger . valueOf ( number . longValue ( ) ) ; } } else if ( Float . class == targetClass ) { return ( T ) Float . valueOf ( number . floatValue ( ) ) ; } else if ( Double . class == targetClass ) { return ( T ) Double . valueOf ( number . doubleValue ( ) ) ; } else if ( BigDecimal . class == targetClass ) { return ( T ) new BigDecimal ( number . toString ( ) ) ; } else { throw new IllegalArgumentException ( "Could not convert number [" + number + "] of type [" + number . getClass ( ) . getName ( ) + "] to unsupported target class [" + targetClass . getName ( ) + "]" ) ; } }
Convert the given number into an instance of the given target class .
37,170
public void addFilterBefore ( IRuleFilter filter , Class < ? extends IRuleFilter > beforeFilter ) { int index = getIndexOfClass ( filters , beforeFilter ) ; if ( index == - 1 ) { throw new FilterAddException ( "filter " + beforeFilter . getSimpleName ( ) + " has not been added" ) ; } filters . add ( index , filter ) ; }
add filter before
37,171
public void addFilterAfter ( IRuleFilter filter , Class < ? extends IRuleFilter > afterFilter ) { int index = getIndexOfClass ( filters , afterFilter ) ; if ( index == - 1 ) { throw new FilterAddException ( "filter " + afterFilter . getSimpleName ( ) + " has not been added" ) ; } filters . add ( index + 1 , filter ) ; }
add filter after
37,172
public void addRuleParserBefore ( IRuleParser parser , Class < ? extends IRuleParser > beforeParser ) { int index = getIndexOfClass ( ruleParsers , beforeParser ) ; if ( index == - 1 ) { throw new ParserAddException ( "parser " + beforeParser . getSimpleName ( ) + " has not been added" ) ; } ruleParsers . add ( index , parser ) ; }
add parser before
37,173
public void addRuleParserAfter ( IRuleParser parser , Class < ? extends IRuleParser > afterParser ) { int index = getIndexOfClass ( ruleParsers , afterParser ) ; if ( index == - 1 ) { throw new ParserAddException ( "parser " + afterParser . getSimpleName ( ) + " has not been added" ) ; } ruleParsers . add ( index + 1 , parser ) ; }
add parser after
37,174
private int getIndexOfClass ( List list , Class cls ) { for ( int i = 0 ; i < list . size ( ) ; i ++ ) { if ( list . get ( i ) . getClass ( ) . equals ( cls ) ) { return i ; } } return - 1 ; }
get class index of list
37,175
static Annotation [ ] findAndSortAnnotations ( Annotation annotation ) { final Annotation [ ] metaAnnotations = annotation . annotationType ( ) . getAnnotations ( ) ; Arrays . sort ( metaAnnotations , new Comparator < Annotation > ( ) { public int compare ( Annotation o1 , Annotation o2 ) { if ( o1 instanceof ChameleonTarget ) { return - 1 ; } if ( o2 instanceof ChameleonTarget ) { return 1 ; } return 0 ; } } ) ; return metaAnnotations ; }
We need to sort annotations so the first one processed is ChameleonTarget so these properties has bigger preference that the inherit ones .
37,176
public ChameleonTargetConfiguration importConfiguration ( ChameleonTargetConfiguration other ) { if ( this . container == null || this . container . isEmpty ( ) ) { this . container = other . getContainer ( ) ; } if ( this . version == null || this . version . isEmpty ( ) ) { this . version = other . getVersion ( ) ; } if ( this . mode == null ) { this . mode = other . getMode ( ) ; } final Set < Map . Entry < String , String > > entries = other . getCustomProperties ( ) . entrySet ( ) ; for ( Map . Entry < String , String > entry : entries ) { if ( ! this . customProperties . containsKey ( entry . getKey ( ) ) ) { this . customProperties . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return this ; }
This methods copies attribute values that are not set in this object other object
37,177
private void createChameleonMarkerFile ( Path parent ) throws IOException { final Path chameleon = parent . resolve ( "chameleonrunner" ) ; Files . write ( chameleon , "Chameleon Runner was there" . getBytes ( ) ) ; }
representing different versions because then you have uncertainty on which configuration file is really used
37,178
public JsonObject prepare ( ) { if ( channel != null ) { slackMessage . addProperty ( CHANNEL , channel ) ; } if ( username != null ) { slackMessage . addProperty ( USERNAME , username ) ; } if ( icon != null ) { if ( icon . contains ( HTTP ) ) { slackMessage . addProperty ( ICON_URL , icon ) ; } else { slackMessage . addProperty ( ICON_EMOJI , icon ) ; } } slackMessage . addProperty ( UNFURL_MEDIA , unfurlMedia ) ; slackMessage . addProperty ( UNFURL_LINKS , unfurlLinks ) ; slackMessage . addProperty ( LINK_NAMES , linkNames ) ; if ( text == null ) { throw new IllegalArgumentException ( "Missing Text field @ SlackMessage" ) ; } else { slackMessage . addProperty ( TEXT , text ) ; } if ( ! attach . isEmpty ( ) ) { slackMessage . add ( ATTACHMENTS , this . prepareAttach ( ) ) ; } return slackMessage ; }
Convert SlackMessage to JSON
37,179
public static String dumpString ( byte [ ] b ) { StringBuilder d = new StringBuilder ( b . length * 2 ) ; for ( byte aB : b ) { char c = ( char ) aB ; if ( Character . isISOControl ( c ) ) { switch ( c ) { case '\r' : d . append ( "{CR}" ) ; break ; case '\n' : d . append ( "{LF}" ) ; break ; case '\000' : d . append ( "{NULL}" ) ; break ; default : char hi = Character . forDigit ( ( aB >> 4 ) & 0x0F , 16 ) ; char lo = Character . forDigit ( aB & 0x0F , 16 ) ; d . append ( '[' ) . append ( Character . toUpperCase ( hi ) ) . append ( Character . toUpperCase ( lo ) ) . append ( ']' ) ; break ; } } else d . append ( c ) ; } return d . toString ( ) ; }
converts a byte array to printable characters
37,180
public Disjunction add ( IDisjunct disjunct ) { for ( Iterator < IAssertion > assertions = disjunct . getAssertions ( ) ; assertions . hasNext ( ) ; ) { add ( assertions . next ( ) ) ; } return this ; }
Adds all assertions for the given IDisjunct to this disjunction .
37,181
public static FormattedString of ( String format , Object object ) { return object == null ? new Null ( ) : "binary" . equals ( format ) ? new Base64 ( ( byte [ ] ) object ) : "byte" . equals ( format ) ? new Base64 ( ( byte [ ] ) object ) : "date" . equals ( format ) ? new Date ( ( java . util . Date ) object ) : "date-time" . equals ( format ) ? new DateTime ( ( java . util . Date ) object ) : "uuid" . equals ( format ) ? new Uuid ( ( UUID ) object ) : new Native ( object ) ; }
Creates a FormattedString for the given object .
37,182
public static List < FormattedString > of ( String format , List < ? > objects ) { return objects . stream ( ) . map ( object -> of ( format , object ) ) . collect ( toList ( ) ) ; }
Creates a FormattedString for each of the given objects .
37,183
public void write ( SystemInputDef systemInput ) { xmlWriter_ . writeDeclaration ( ) ; xmlWriter_ . element ( SYSTEM_TAG ) . attribute ( NAME_ATR , systemInput . getName ( ) ) . content ( ( ) -> { writeAnnotations ( systemInput ) ; toStream ( systemInput . getFunctionInputDefs ( ) ) . forEach ( this :: writeFunction ) ; } ) . write ( ) ; }
Writes the given system test definition the form of an XML document .
37,184
protected void writeFunction ( FunctionInputDef function ) { xmlWriter_ . element ( FUNCTION_TAG ) . attribute ( NAME_ATR , function . getName ( ) ) . content ( ( ) -> { writeAnnotations ( function ) ; for ( String varType : function . getVarTypes ( ) ) { writeInputs ( varType , toStream ( function . getVarDefs ( ) ) . filter ( varDef -> varDef . getType ( ) . equals ( varType ) ) . sorted ( ) ) ; } } ) . write ( ) ; }
Writes the given function input definition .
37,185
protected void writeInputs ( String varType , Stream < IVarDef > varDefs ) { xmlWriter_ . element ( INPUT_TAG ) . attribute ( TYPE_ATR , varType ) . content ( ( ) -> varDefs . forEach ( this :: writeVarDef ) ) . write ( ) ; }
Writes the given input variable list .
37,186
protected void writeVarDef ( IVarDef varDef ) { Stream < VarValueDef > values = varDef . getValues ( ) == null ? null : toStream ( varDef . getValues ( ) ) ; Stream < IVarDef > members = varDef . getMembers ( ) == null ? null : toStream ( varDef . getMembers ( ) ) ; String varTag = members == null ? VAR_TAG : VARSET_TAG ; ConditionWriter conditionWriter = new ConditionWriter ( varDef . getCondition ( ) ) ; xmlWriter_ . element ( varTag ) . attribute ( NAME_ATR , varDef . getName ( ) ) . attributeIf ( WHEN_ATR , conditionWriter . getWhenAttribute ( ) ) . content ( ( ) -> { writeAnnotations ( varDef ) ; conditionWriter . writeWhenElement ( ) ; if ( varTag . equals ( VAR_TAG ) ) { values . forEach ( this :: writeValue ) ; } else { members . forEach ( this :: writeVarDef ) ; } } ) . write ( ) ; }
Writes the given variable definition .
37,187
protected void writeValue ( VarValueDef value ) { ConditionWriter conditionWriter = new ConditionWriter ( value . getCondition ( ) ) ; xmlWriter_ . element ( VALUE_TAG ) . attribute ( NAME_ATR , String . valueOf ( value . getName ( ) ) ) . attributeIf ( value . getType ( ) == FAILURE , FAILURE_ATR , "true" ) . attributeIf ( value . getType ( ) == ONCE , ONCE_ATR , "true" ) . attributeIf ( WHEN_ATR , conditionWriter . getWhenAttribute ( ) ) . attributeIf ( PROPERTY_ATR , propertyList ( toStream ( value . getProperties ( ) ) ) ) . contentIf ( value . getAnnotationCount ( ) > 0 || conditionWriter . hasWhenElement ( ) , ( ) -> { writeAnnotations ( value ) ; conditionWriter . writeWhenElement ( ) ; } ) . write ( ) ; }
Writes the given variable input value definition .
37,188
protected void writeAnnotations ( IAnnotated annotated ) { toStream ( annotated . getAnnotations ( ) ) . sorted ( ) . forEach ( annotation -> { xmlWriter_ . element ( HAS_TAG ) . attribute ( NAME_ATR , annotation ) . attribute ( VALUE_ATR , annotated . getAnnotation ( annotation ) ) . write ( ) ; } ) ; }
Writes the given annotation definitions .
37,189
public Conjunction append ( IConjunct conjunct ) { for ( Iterator < IDisjunct > disjuncts = conjunct . getDisjuncts ( ) ; disjuncts . hasNext ( ) ; add ( disjuncts . next ( ) ) ) ; return this ; }
Appends another conjunction to this conjunction .
37,190
public static void assertIdentifier ( String id ) throws IllegalArgumentException { if ( ! isIdentifier ( id ) ) { throw new IllegalArgumentException ( ( id == null ? "null" : ( "\"" + String . valueOf ( id ) + "\"" ) ) + " is not a valid identifier" ) ; } }
Throws an exception if the given string is not a valid identifier .
37,191
public static boolean isVarValue ( Object val ) { return val == null || ! val . getClass ( ) . equals ( String . class ) || varValueRegex_ . matcher ( val . toString ( ) ) . matches ( ) ; }
Returns true if the given string is a valid variable value .
37,192
public static void assertVarValue ( Object val ) throws IllegalArgumentException { if ( ! isVarValue ( val ) ) { throw new IllegalArgumentException ( "\"" + String . valueOf ( val ) + "\"" + " is not a valid variable value" ) ; } }
Throws an exception if the given string is not a valid variable value .
37,193
public static void assertPath ( String pathName ) throws IllegalArgumentException { String ids [ ] = toPath ( pathName ) ; for ( int i = 0 ; i < ids . length ; i ++ ) { assertIdentifier ( ids [ i ] ) ; } }
Throws an exception if the given string is not a valid identifier path name .
37,194
public static void assertPropertyIdentifiers ( Collection < String > properties ) throws IllegalArgumentException { if ( properties != null ) { for ( String property : properties ) { assertIdentifier ( property ) ; } } }
Throws an exception if any member of the given set of properties is not a valid identifier .
37,195
public void addProperty ( String property ) { String candidate = StringUtils . trimToNull ( property ) ; if ( candidate != null ) { properties_ . add ( property ) ; } }
Adds a property to this set .
37,196
protected void setWriter ( Writer writer ) { writer_ = writer == null ? writerFor ( System . out ) : writer ; }
Changes the output stream for this writer .
37,197
private static Writer writerFor ( OutputStream stream ) { try { return stream == null ? null : new OutputStreamWriter ( stream , "UTF-8" ) ; } catch ( Exception e ) { throw new RuntimeException ( "Can't create writer" , e ) ; } }
Returns a Writer for the given output stream ;
37,198
public static Project asProject ( JsonObject json ) { return ProjectBuilder . with ( asSystemInputDef ( json . get ( INPUTDEF_KEY ) ) ) . systemInputRef ( asSystemInputRef ( json . get ( INPUTDEF_KEY ) ) ) . generators ( asGeneratorSet ( json . get ( GENERATORS_KEY ) ) ) . generatorsRef ( asGeneratorSetRef ( json . get ( GENERATORS_KEY ) ) ) . baseTests ( asSystemTestDef ( json . get ( BASETESTS_KEY ) ) ) . baseTestRef ( asSystemTestRef ( json . get ( BASETESTS_KEY ) ) ) . refBase ( asRefBase ( json . getJsonString ( REFBASE_KEY ) ) ) . build ( ) ; }
Returns the Project represented by the given JSON object .
37,199
private static URI asRefBase ( JsonString uri ) { try { return uri == null ? null : new URI ( uri . getChars ( ) . toString ( ) ) ; } catch ( Exception e ) { throw new ProjectException ( String . format ( "Error defining reference base=%s" , uri ) , e ) ; } }
Returns the reference base URI represented by the given JSON string .