signature:
public class CoreSocketFactory { /** * Creates a socket representing a connection to a Cloud SQL instance .
 * < p > Depending on the environment , it may return either a SSL Socket or a Unix Socket .
 * @ param props Properties used to configure the connection .
 * @ return the newly created Socket .
 * @ throws IOException if error occurs during socket creation . */
public Socket connect ( Properties props , String socketPathFormat ) throws IOException { } }

implementation:
// Gather parameters
final String csqlInstanceName = props . getProperty ( CLOUD_SQL_INSTANCE_PROPERTY ) ; final List < String > ipTypes = listIpTypes ( props . getProperty ( "ipTypes" , DEFAULT_IP_TYPES ) ) ; final boolean forceUnixSocket = System . getenv ( "CLOUD_SQL_FORCE_UNIX_SOCKET" ) != null ; // Validate parameters
Preconditions . checkArgument ( csqlInstanceName != null , "cloudSqlInstance property not set. Please specify this property in the JDBC URL or the " + "connection Properties with value in form \"project:region:instance\"" ) ; // GAE Standard runtimes provide a connection path at " / cloudsql / < CONNECTION _ NAME > "
if ( forceUnixSocket || runningOnGaeStandard ( ) ) { logger . info ( String . format ( "Connecting to Cloud SQL instance [%s] via unix socket." , csqlInstanceName ) ) ; UnixSocketAddress socketAddress = new UnixSocketAddress ( new File ( String . format ( socketPathFormat , csqlInstanceName ) ) ) ; return UnixSocketChannel . open ( socketAddress ) . socket ( ) ; } logger . info ( String . format ( "Connecting to Cloud SQL instance [%s] via SSL socket." , csqlInstanceName ) ) ; return getInstance ( ) . createSslSocket ( csqlInstanceName , ipTypes ) ;


signature:
public class CoreSocketFactory { /** * Returns { @ code true } if running in a Google App Engine Standard runtime . */
private boolean runningOnGaeStandard ( ) { } }

implementation:
// gaeEnv = " standard " indicates standard instances
String gaeEnv = System . getenv ( "GAE_ENV" ) ; // runEnv = " Production " requires to rule out Java 8 emulated environments
String runEnv = System . getProperty ( "com.google.appengine.runtime.environment" ) ; // gaeRuntime = " java11 " in Java 11 environments ( no emulated environments )
String gaeRuntime = System . getenv ( "GAE_RUNTIME" ) ; return "standard" . equals ( gaeEnv ) && ( "Production" . equals ( runEnv ) || "java11" . equals ( gaeRuntime ) ) ;


signature:
public class CoreSocketFactory { /** * TODO ( berezv ) : separate creating socket and performing connection to make it easier to test */
@ VisibleForTesting Socket createSslSocket ( String instanceName , List < String > ipTypes ) throws IOException { } }

implementation: try { return createAndConfigureSocket ( instanceName , ipTypes , CertificateCaching . USE_CACHE ) ; } catch ( SSLHandshakeException err ) { logger . warning ( String . format ( "SSL handshake failed for Cloud SQL instance [%s], " + "retrying with new certificate.\n%s" , instanceName , Throwables . getStackTraceAsString ( err ) ) ) ; if ( ! forcedRenewRateLimiter . tryAcquire ( ) ) { logger . warning ( String . format ( "Renewing too often, rate limiting certificate renewal for Cloud SQL " + "instance [%s]." , instanceName ) ) ; forcedRenewRateLimiter . acquire ( ) ; } return createAndConfigureSocket ( instanceName , ipTypes , CertificateCaching . BYPASS_CACHE ) ; }


signature:
public class CoreSocketFactory { /** * Converts the string property of IP types to a list by splitting by commas , and upper - casing . */
private static List < String > listIpTypes ( String cloudSqlIpTypes ) { } }

implementation: String [ ] rawTypes = cloudSqlIpTypes . split ( "," ) ; ArrayList < String > result = new ArrayList < > ( rawTypes . length ) ; for ( int i = 0 ; i < rawTypes . length ; i ++ ) { if ( rawTypes [ i ] . trim ( ) . equalsIgnoreCase ( "PUBLIC" ) ) { result . add ( i , "PRIMARY" ) ; } else { result . add ( i , rawTypes [ i ] . trim ( ) . toUpperCase ( ) ) ; } } return result ;


signature:
public class CoreSocketFactory { /** * TODO ( berezv ) : synchronize per instance , instead of globally */
@ VisibleForTesting synchronized InstanceSslInfo getInstanceSslInfo ( String instanceConnectionString , CertificateCaching certificateCaching ) { } }

implementation:
if ( certificateCaching . equals ( CertificateCaching . USE_CACHE ) ) { InstanceLookupResult lookupResult = cache . get ( instanceConnectionString ) ; if ( lookupResult != null ) { if ( ! lookupResult . isSuccessful ( ) && ( clock . now ( ) - lookupResult . getLastFailureMillis ( ) ) < 60 * 1000 ) { logger . warning ( "Re-throwing cached exception due to attempt to refresh instance information too " + "soon after error." ) ; throw lookupResult . getException ( ) . get ( ) ; } else if ( lookupResult . isSuccessful ( ) ) { InstanceSslInfo details = lookupResult . getInstanceSslInfo ( ) . get ( ) ; // Check if the cached certificate is still valid .
if ( details != null ) { GregorianCalendar calendar = new GregorianCalendar ( ) ; calendar . setTimeInMillis ( clock . now ( ) ) ; calendar . add ( Calendar . MINUTE , 5 ) ; try { details . getEphemeralCertificate ( ) . checkValidity ( calendar . getTime ( ) ) ; } catch ( CertificateException err ) { logger . info ( String . format ( "Ephemeral certificate for Cloud SQL instance [%s] is about to expire, " + "obtaining new one." , instanceConnectionString ) ) ; details = null ; } } if ( details != null ) { return details ; } } } } String invalidInstanceError = String . format ( "Invalid Cloud SQL instance [%s], expected value in form [project:region:name]." , instanceConnectionString ) ; int beforeNameIndex = instanceConnectionString . lastIndexOf ( ':' ) ; if ( beforeNameIndex <= 0 ) { throw new IllegalArgumentException ( invalidInstanceError ) ; } int beforeRegionIndex = instanceConnectionString . lastIndexOf ( ':' , beforeNameIndex - 1 ) ; if ( beforeRegionIndex <= 0 ) { throw new IllegalArgumentException ( invalidInstanceError ) ; } String projectId = instanceConnectionString . substring ( 0 , beforeRegionIndex ) ; String region = instanceConnectionString . substring ( beforeRegionIndex + 1 , beforeNameIndex ) ; String instanceName = instanceConnectionString . substring ( beforeNameIndex + 1 ) ; InstanceLookupResult instanceLookupResult ; InstanceSslInfo details ; try { details = fetchInstanceSslInfo ( instanceConnectionString , projectId , region , instanceName ) ; instanceLookupResult = new InstanceLookupResult ( details ) ; cache . put ( instanceConnectionString , instanceLookupResult ) ; } catch ( RuntimeException err ) { instanceLookupResult = new InstanceLookupResult ( err ) ; cache . put ( instanceConnectionString , instanceLookupResult ) ; throw err ; } return details ;


signature:
public class SocketFactory { /** * Implements the interface for com . mysql . cj . protocol . SocketFactory for mysql - connector - java prior
 * to version 8.0.13 . This change is required for backwards compatibility . */
public < T extends Closeable > T connect ( String host , int portNumber , Properties props , int loginTimeout ) throws IOException { } }

implementation: @ SuppressWarnings ( "unchecked" ) T socket = ( T ) CoreSocketFactory . getInstance ( ) . connect ( props , CoreSocketFactory . MYSQL_SOCKET_FILE_FORMAT ) ; return socket ;


signature:
public class FluentLoggerFactory { /** * Purges an invalid logger from the cache . */
protected synchronized void purgeLogger ( FluentLogger logger ) { } }

implementation: Iterator < Entry < FluentLogger , String > > it = loggers . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { if ( it . next ( ) . getKey ( ) == logger ) { it . remove ( ) ; return ; } }


signature:
public class InMemoryJavaCompiler { /** * Compile all sources
 * @ return Map containing instances of all compiled classes
 * @ throws Exception */
public Map < String , Class < ? > > compileAll ( ) throws Exception { } }

implementation: if ( sourceCodes . size ( ) == 0 ) { throw new CompilationException ( "No source code to compile" ) ; } Collection < SourceCode > compilationUnits = sourceCodes . values ( ) ; CompiledCode [ ] code ; code = new CompiledCode [ compilationUnits . size ( ) ] ; Iterator < SourceCode > iter = compilationUnits . iterator ( ) ; for ( int i = 0 ; i < code . length ; i ++ ) { code [ i ] = new CompiledCode ( iter . next ( ) . getClassName ( ) ) ; } DiagnosticCollector < JavaFileObject > collector = new DiagnosticCollector < > ( ) ; ExtendedStandardJavaFileManager fileManager = new ExtendedStandardJavaFileManager ( javac . getStandardFileManager ( null , null , null ) , classLoader ) ; JavaCompiler . CompilationTask task = javac . getTask ( null , fileManager , collector , options , null , compilationUnits ) ; boolean result = task . call ( ) ; if ( ! result || collector . getDiagnostics ( ) . size ( ) > 0 ) { StringBuffer exceptionMsg = new StringBuffer ( ) ; exceptionMsg . append ( "Unable to compile the source" ) ; boolean hasWarnings = false ; boolean hasErrors = false ; for ( Diagnostic < ? extends JavaFileObject > d : collector . getDiagnostics ( ) ) { switch ( d . getKind ( ) ) { case NOTE : case MANDATORY_WARNING : case WARNING : hasWarnings = true ; break ; case OTHER : case ERROR : default : hasErrors = true ; break ; } exceptionMsg . append ( "\n" ) . append ( "[kind=" ) . append ( d . getKind ( ) ) ; exceptionMsg . append ( ", " ) . append ( "line=" ) . append ( d . getLineNumber ( ) ) ; exceptionMsg . append ( ", " ) . append ( "message=" ) . append ( d . getMessage ( Locale . US ) ) . append ( "]" ) ; } if ( hasWarnings && ! ignoreWarnings || hasErrors ) { throw new CompilationException ( exceptionMsg . toString ( ) ) ; } } Map < String , Class < ? > > classes = new HashMap < String , Class < ? > > ( ) ; for ( String className : sourceCodes . keySet ( ) ) { classes . put ( className , classLoader . loadClass ( className ) ) ; } return classes ;


signature:
public class InMemoryJavaCompiler { /** * Compile single source
 * @ param className
 * @ param sourceCode
 * @ return
 * @ throws Exception */
public Class < ? > compile ( String className , String sourceCode ) throws Exception { } }

implementation: return addSource ( className , sourceCode ) . compileAll ( ) . get ( className ) ;


signature:
public class InMemoryJavaCompiler { /** * Add source code to the compiler
 * @ param className
 * @ param sourceCode
 * @ return
 * @ throws Exception
 * @ see { @ link # compileAll ( ) } */
public InMemoryJavaCompiler addSource ( String className , String sourceCode ) throws Exception { } }

implementation: sourceCodes . put ( className , new SourceCode ( className , sourceCode ) ) ; return this ;


signature:
public class GifHeaderParser { /** * Reads Graphics Control Extension values . */
private void readGraphicControlExt ( ) { } }

implementation:
// Block size .
read ( ) ; // Packed fields .
int packed = read ( ) ; // Disposal method .
header . currentFrame . dispose = ( packed & 0x1c ) >> 2 ; if ( header . currentFrame . dispose == 0 ) { // Elect to keep old image if discretionary .
header . currentFrame . dispose = 1 ; } header . currentFrame . transparency = ( packed & 1 ) != 0 ; // Delay in milliseconds .
int delayInHundredthsOfASecond = readShort ( ) ; // TODO : consider allowing - 1 to indicate show forever .
if ( delayInHundredthsOfASecond < MIN_FRAME_DELAY ) { delayInHundredthsOfASecond = DEFAULT_FRAME_DELAY ; } header . currentFrame . delay = delayInHundredthsOfASecond * 10 ; // Transparent color index
header . currentFrame . transIndex = read ( ) ; // Block terminator
read ( ) ;


signature:
public class GifHeaderParser { /** * Reads next variable length block from input .
 * @ return number of bytes stored in " buffer " */
private int readBlock ( ) { } }

implementation: blockSize = read ( ) ; int n = 0 ; if ( blockSize > 0 ) { int count = 0 ; try { while ( n < blockSize ) { count = blockSize - n ; rawData . get ( block , n , count ) ; n += count ; } } catch ( Exception e ) { if ( Log . isLoggable ( TAG , Log . DEBUG ) ) { Log . d ( TAG , "Error Reading Block n: " + n + " count: " + count + " blockSize: " + blockSize , e ) ; } header . status = GifDecoder . STATUS_FORMAT_ERROR ; } } return n ;


signature:
public class GifDecoder { /** * Get the next frame in the animation sequence .
 * @ return Bitmap representation of frame . */
synchronized Bitmap getNextFrame ( ) { } }

implementation:
if ( header . frameCount <= 0 || framePointer < 0 ) { if ( Log . isLoggable ( TAG , Log . DEBUG ) ) { Log . d ( TAG , "unable to decode frame, frameCount=" + header . frameCount + " framePointer=" + framePointer ) ; } status = STATUS_FORMAT_ERROR ; } if ( status == STATUS_FORMAT_ERROR || status == STATUS_OPEN_ERROR ) { if ( Log . isLoggable ( TAG , Log . DEBUG ) ) { Log . d ( TAG , "Unable to decode frame, status=" + status ) ; } return null ; } status = STATUS_OK ; GifFrame currentFrame = header . frames . get ( framePointer ) ; GifFrame previousFrame = null ; int previousIndex = framePointer - 1 ; if ( previousIndex >= 0 ) { previousFrame = header . frames . get ( previousIndex ) ; } // Set the appropriate color table .
act = currentFrame . lct != null ? currentFrame . lct : header . gct ; if ( act == null ) { if ( Log . isLoggable ( TAG , Log . DEBUG ) ) { Log . d ( TAG , "No Valid Color Table for frame #" + framePointer ) ; } // No color table defined .
status = STATUS_FORMAT_ERROR ; return null ; } // Reset the transparent pixel in the color table
if ( currentFrame . transparency ) { // Prepare local copy of color table ( " pct = act " ) , see # 1068
System . arraycopy ( act , 0 , pct , 0 , act . length ) ; // Forget about act reference from shared header object , use copied version
act = pct ; // Set transparent color if specified .
act [ currentFrame . transIndex ] = 0 ; } // Transfer pixel data to image .
return setPixels ( currentFrame , previousFrame ) ;


signature:
public class GifDecoder { /** * Creates new frame image from current data ( and previous frames as specified by their
 * disposition codes ) . */
private Bitmap setPixels ( GifFrame currentFrame , GifFrame previousFrame ) { } }

implementation:
// Final location of blended pixels .
final int [ ] dest = mainScratch ; // clear all pixels when meet first frame
if ( previousFrame == null ) { Arrays . fill ( dest , 0 ) ; } // fill in starting image contents based on last image ' s dispose code
if ( previousFrame != null && previousFrame . dispose > DISPOSAL_UNSPECIFIED ) { // We don ' t need to do anything for DISPOSAL _ NONE , if it has the correct pixels so will our
// mainScratch and therefore so will our dest array .
if ( previousFrame . dispose == DISPOSAL_BACKGROUND ) { // Start with a canvas filled with the background color
int c = 0 ; if ( ! currentFrame . transparency ) { c = header . bgColor ; if ( currentFrame . lct != null && header . bgIndex == currentFrame . transIndex ) { c = 0 ; } } else if ( framePointer == 0 ) { // TODO : We should check and see if all individual pixels are replaced . If they are , the
// first frame isn ' t actually transparent . For now , it ' s simpler and safer to assume
// drawing a transparent background means the GIF contains transparency .
isFirstFrameTransparent = true ; } fillRect ( dest , previousFrame , c ) ; } else if ( previousFrame . dispose == DISPOSAL_PREVIOUS ) { if ( previousImage == null ) { fillRect ( dest , previousFrame , 0 ) ; } else { // Start with the previous frame
int downsampledIH = previousFrame . ih / sampleSize ; int downsampledIY = previousFrame . iy / sampleSize ; int downsampledIW = previousFrame . iw / sampleSize ; int downsampledIX = previousFrame . ix / sampleSize ; int topLeft = downsampledIY * downsampledWidth + downsampledIX ; previousImage . getPixels ( dest , topLeft , downsampledWidth , downsampledIX , downsampledIY , downsampledIW , downsampledIH ) ; } } } // Decode pixels for this frame into the global pixels [ ] scratch .
decodeBitmapData ( currentFrame ) ; int downsampledIH = currentFrame . ih / sampleSize ; int downsampledIY = currentFrame . iy / sampleSize ; int downsampledIW = currentFrame . iw / sampleSize ; int downsampledIX = currentFrame . ix / sampleSize ; // Copy each source line to the appropriate place in the destination .
int pass = 1 ; int inc = 8 ; int iline = 0 ; boolean isFirstFrame = framePointer == 0 ; for ( int i = 0 ; i < downsampledIH ; i ++ ) { int line = i ; if ( currentFrame . interlace ) { if ( iline >= downsampledIH ) { pass ++ ; switch ( pass ) { case 2 : iline = 4 ; break ; case 3 : iline = 2 ; inc = 4 ; break ; case 4 : iline = 1 ; inc = 2 ; break ; default : break ; } } line = iline ; iline += inc ; } line += downsampledIY ; if ( line < downsampledHeight ) { int k = line * downsampledWidth ; // Start of line in dest .
int dx = k + downsampledIX ; // End of dest line .
int dlim = dx + downsampledIW ; if ( k + downsampledWidth < dlim ) { // Past dest edge .
dlim = k + downsampledWidth ; } // Start of line in source .
int sx = i * sampleSize * currentFrame . iw ; int maxPositionInSource = sx + ( ( dlim - dx ) * sampleSize ) ; while ( dx < dlim ) { // Map color and insert in destination .
int averageColor ; if ( sampleSize == 1 ) { int currentColorIndex = ( ( int ) mainPixels [ sx ] ) & 0x000000ff ; averageColor = act [ currentColorIndex ] ; } else { // TODO : This is substantially slower ( up to 50ms per frame ) than just grabbing the
// current color index above , even with a sample size of 1.
averageColor = averageColorsNear ( sx , maxPositionInSource , currentFrame . iw ) ; } if ( averageColor != 0 ) { dest [ dx ] = averageColor ; } else if ( ! isFirstFrameTransparent && isFirstFrame ) { isFirstFrameTransparent = true ; } sx += sampleSize ; dx ++ ; } } } // Copy pixels into previous image
if ( savePrevious && ( currentFrame . dispose == DISPOSAL_UNSPECIFIED || currentFrame . dispose == DISPOSAL_NONE ) ) { if ( previousImage == null ) { previousImage = getNextBitmap ( ) ; } previousImage . setPixels ( dest , 0 , downsampledWidth , 0 , 0 , downsampledWidth , downsampledHeight ) ; } // Set pixels for current image .
Bitmap result = getNextBitmap ( ) ; result . setPixels ( dest , 0 , downsampledWidth , 0 , 0 , downsampledWidth , downsampledHeight ) ; return result ;


signature:
public class GifDecoder { /** * Reads next variable length block from input .
 * @ return number of bytes stored in " buffer " . */
private int readBlock ( ) { } }

implementation:
int blockSize = readByte ( ) ; if ( blockSize > 0 ) { try { if ( block == null ) { block = bitmapProvider . obtainByteArray ( 255 ) ; } final int remaining = workBufferSize - workBufferPosition ; if ( remaining >= blockSize ) { // Block can be read from the current work buffer .
System . arraycopy ( workBuffer , workBufferPosition , block , 0 , blockSize ) ; workBufferPosition += blockSize ; } else if ( rawData . remaining ( ) + remaining >= blockSize ) { // Block can be read in two passes .
System . arraycopy ( workBuffer , workBufferPosition , block , 0 , remaining ) ; workBufferPosition = workBufferSize ; readChunkIfNeeded ( ) ; final int secondHalfRemaining = blockSize - remaining ; System . arraycopy ( workBuffer , 0 , block , remaining , secondHalfRemaining ) ; workBufferPosition += secondHalfRemaining ; } else { status = STATUS_FORMAT_ERROR ; } } catch ( Exception e ) { Log . w ( TAG , "Error Reading Block" , e ) ; status = STATUS_FORMAT_ERROR ; } } return blockSize ;


signature:
public class DialogHelper { /** * Use this method to initialize the show / hide listeners for the dialog .
 * @ param openProperty the boolean property that defines whether the dialog
 * should be shown or hidden . Set this property to < code > true < / code > to open
 * the dialog . Set it to < code > false < / code > to close the dialog . When the
 * dialog is closed by the user by clicking on the close - button of the
 * window , this property will also be set to < code > false < / code > by the
 * dialog .
 * @ param parentStage the Stage that is used as parent to initialize the
 * ownership of the dialog . This way modal dialogs can be created .
 * @ param rootSupplier a supplier function that is called when the dialog is
 * made visible for the first time . This function has to return a
 * { @ link Parent } instance that is used as the root node of the dialog
 * scene . */
public static void initDialog ( BooleanProperty openProperty , final Stage parentStage , Supplier < Parent > rootSupplier ) { } }

implementation:
final Stage dialogStage = new Stage ( StageStyle . UTILITY ) ; dialogStage . initOwner ( parentStage ) ; dialogStage . initModality ( Modality . APPLICATION_MODAL ) ; openProperty . addListener ( ( obs , oldValue , newValue ) -> { if ( newValue ) { // when it is the first time the dialog is made visible ( and therefore no scene exists ) . . .
if ( dialogStage . getScene ( ) == null ) { // . . . we create a new scene and register it in the stage .
Scene dialogScene = new Scene ( rootSupplier . get ( ) ) ; dialogScene . getStylesheets ( ) . add ( "/contacts.css" ) ; dialogStage . setScene ( dialogScene ) ; } else { // . . . otherwise we simple bring the dialog to front .
dialogStage . toFront ( ) ; } dialogStage . sizeToScene ( ) ; dialogStage . show ( ) ; } else { dialogStage . close ( ) ; } } ) ; // when the user clicks on the close button of the dialog window
// we want to set the property to false
dialogStage . setOnCloseRequest ( event -> openProperty . set ( false ) ) ;


signature:
public class PersonLoginViewModel { /** * Persons in string representation .
 * @ return persons */
public SelectableStringList selectablePersonsProperty ( ) { } }

implementation: if ( selectablePersons == null ) { selectablePersons = new SelectableItemList < > ( FXCollections . observableArrayList ( repository . getPersons ( ) ) , person -> person . getFirstName ( ) + " " + person . getLastName ( ) ) ; } return selectablePersons ;


signature:
public class MvvmfxGuiceApplication { /** * This method is called by the javafx runtime when the application is initialized .
 * See { @ link Application # init ( ) } for more details .
 * In this method the initialization of the guice container is done .
 * For this reason , this method is marked as final and cannot be overwritten by users .
 * Please use { @ link # initMvvmfx ( ) } for your own initialization logic .
 * @ throws Exception */
public final void init ( ) throws Exception { } }

implementation: List < Module > modules = new ArrayList < > ( ) ; modules . add ( new MvvmfxModule ( ) ) ; modules . add ( new AbstractModule ( ) { @ Override protected void configure ( ) { bind ( HostServices . class ) . toProvider ( MvvmfxGuiceApplication . this :: getHostServices ) ; bind ( Stage . class ) . toProvider ( ( ) -> primaryStage ) ; bind ( Parameters . class ) . toProvider ( MvvmfxGuiceApplication . this :: getParameters ) ; } } ) ; this . initGuiceModules ( modules ) ; final Injector injector = Guice . createInjector ( modules ) ; MvvmFX . setCustomDependencyInjector ( injector :: getInstance ) ; injector . injectMembers ( this ) ; this . initMvvmfx ( ) ;


signature:
public class ResourceBundleInjector { /** * Try to inject the given { @ link ResourceBundle } into the given target instance .
 * @ param target
 * the View / ViewModel instance that the ResourceBundle will be injected to . May not be < code > null < / code > .
 * @ param resourceBundle
 * the ResourceBundle instance that is used . */
static void injectResourceBundle ( Object target , ResourceBundle resourceBundle ) { } }

implementation:
final List < Field > fieldsWithAnnotation = ReflectionUtils . getFieldsWithAnnotation ( target , InjectResourceBundle . class ) ; final boolean notAssignableFieldPresent = fieldsWithAnnotation . stream ( ) . anyMatch ( field -> ! field . getType ( ) . isAssignableFrom ( ResourceBundle . class ) ) ; if ( notAssignableFieldPresent ) { throw new IllegalStateException ( "The class [" + target + "] has at least one field with the annotation @InjectResourceBundle but the field is not of type ResourceBundle." ) ; } // check whether the user has provided any resourceBundle or not
if ( resourceBundle == null || resourceBundle . equals ( EMPTY_RESOURCE_BUNDLE ) ) { if ( ! fieldsWithAnnotation . isEmpty ( ) ) { final boolean nonOptionalFieldsPresent = fieldsWithAnnotation . stream ( ) . flatMap ( field -> Arrays . stream ( field . getAnnotationsByType ( InjectResourceBundle . class ) ) ) . anyMatch ( annotation -> ! annotation . optional ( ) ) ; // if all annotated fields are marked as " optional " , no exception has to be thrown .
if ( nonOptionalFieldsPresent ) { throw new IllegalStateException ( "The class [" + target + "] expects a ResourceBundle to be injected but no ResourceBundle was defined while loading." ) ; } } } else { fieldsWithAnnotation . forEach ( field -> { if ( field . getType ( ) . isAssignableFrom ( ResourceBundle . class ) ) { ReflectionUtils . setField ( field , target , resourceBundle ) ; } else { throw new IllegalStateException ( "The class [" + target + "] has a field with the @InjectResourceBundle annotation but the type of the field doesn't match ResourceBundle" ) ; } } ) ; }


signature:
public class CentralClock { /** * This method is used to set the clock to a fixed time . This is useful for
 * tests . This way it ' s possible to create date / time instances with a
 * predictable value for your tests . */
public static void setFixedClock ( ZonedDateTime zonedDateTime ) { } }

implementation: CentralClock . clock = Clock . fixed ( zonedDateTime . toInstant ( ) , ZoneId . systemDefault ( ) ) ;


signature:
public class ValidationStatus { /** * Returns the message with the highest priority using the following algorithm : - if there are messages with
 * { @ link Severity # ERROR } , take the first one . - otherwise , if there are messages with { @ link Severity # WARNING } ,
 * take the first one . - otherwise , an empty Optional is returned .
 * @ return an Optional containing the ValidationMessage or an empty Optional . */
public Optional < ValidationMessage > getHighestMessage ( ) { } }

implementation: final Optional < ValidationMessage > error = getMessages ( ) . stream ( ) . filter ( message -> message . getSeverity ( ) . equals ( Severity . ERROR ) ) . findFirst ( ) ; if ( error . isPresent ( ) ) { return error ; } else { final Optional < ValidationMessage > warning = getMessages ( ) . stream ( ) . filter ( message -> message . getSeverity ( ) . equals ( Severity . WARNING ) ) . findFirst ( ) ; return warning ; }


signature:
public class ResourceBundleManager { /** * Merges the provided ResourceBundle with the global one ( if any ) .
 * The global resourceBundle has a lower priority then the provided one . If there is the same key defined in the
 * global and the provided resourceBundle , the value from the provided resourceBundle will be used .
 * @ param resourceBundle
 * a resourceBundle that will be merged .
 * @ return the merged resourceBundle or null , if there is no global resource bundle and not given resource bundle . */
public ResourceBundle mergeWithGlobal ( ResourceBundle resourceBundle ) { } }

implementation: if ( globalResourceBundle == null ) { if ( resourceBundle == null ) { return EMPTY_RESOURCE_BUNDLE ; } else { return new ResourceBundleWrapper ( resourceBundle ) ; } } else { if ( resourceBundle == null ) { return new ResourceBundleWrapper ( globalResourceBundle ) ; } else { return merge ( resourceBundle , globalResourceBundle ) ; } }


signature:
public class ResourceBundleManager { /** * Merges the list of ResourceBundles with the global one ( if any ) .
 * The global resourceBundle has a lower priority then the provided ones . If there is the same key defined in the
 * global and in one of the provided resourceBundles , the value from the provided resourceBundle will be used .
 * The order of resourceBundles in the list defines the priority for resourceBundles .
 * ResourceBundles at the start of the list have a < strong > lower < / strong > priority compared to bundles
 * at the end of the list . This means that the last resourceBundle will overwrite values from previous resourceBundles
 * ( including the global resourceBundle ( if any ) ) . *
 * @ param bundles
 * a list of resourceBundles that will be merged . < code > null < / code > is accepted .
 * @ return the merged resourceBundle . */
public ResourceBundle mergeListWithGlobal ( List < ResourceBundle > bundles ) { } }

implementation: if ( globalResourceBundle == null ) { if ( bundles == null ) { return EMPTY_RESOURCE_BUNDLE ; } else { return reduce ( bundles ) ; } } else { if ( bundles == null ) { return new ResourceBundleWrapper ( globalResourceBundle ) ; } else { final List < ResourceBundle > resourceBundles = new ArrayList < > ( ) ; resourceBundles . add ( globalResourceBundle ) ; resourceBundles . addAll ( bundles ) ; return reduce ( resourceBundles ) ; } }


signature:
public class DependencyInjector { /** * Returns an instance of the given type . When there is a custom injector defined ( See :
 * { @ link # setCustomInjector ( javafx . util . Callback ) } ) then this injector is used . Otherwise a new instance of the
 * desired type is created . This is done by a call to { @ link Class # newInstance ( ) } which means that all constraints
 * of the newInstance method are also need to be satisfied .
 * @ param type
 * @ param < T >
 * @ return */
@ SuppressWarnings ( "unchecked" ) public < T > T getInstanceOf ( Class < ? extends T > type ) { } }

implementation:
if ( isCustomInjectorDefined ( ) ) { return ( T ) customInjector . call ( type ) ; } else { try { // use default creation
return type . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { throw new RuntimeException ( "Can't create instance of type " + type . getName ( ) + ". Make sure that the class has a public no-arg constructor." , e ) ; } }


signature:
public class ListTransformation { /** * If the list changed we want the recreate the targetType representation */
private void initListEvents ( ) { } }

implementation:
this . listChangeListener = new ListChangeListener < SourceType > ( ) { @ Override public void onChanged ( Change < ? extends SourceType > listEvent ) { // We have to stage delete events , because if we process them
// separately , there will be unwanted ChangeEvents on the
// targetList
List < TargetType > deleteStaging = new ArrayList < > ( ) ; while ( listEvent . next ( ) ) { if ( listEvent . wasUpdated ( ) ) { processUpdateEvent ( listEvent ) ; } else if ( listEvent . wasReplaced ( ) ) { processReplaceEvent ( listEvent , deleteStaging ) ; } else if ( listEvent . wasAdded ( ) ) { processAddEvent ( listEvent ) ; } else if ( listEvent . wasRemoved ( ) ) { processRemoveEvent ( listEvent , deleteStaging ) ; } } // Process the staged elements
processStagingLists ( deleteStaging ) ; } } ; modelListProperty ( ) . addListener ( new WeakListChangeListener < > ( listChangeListener ) ) ;


signature:
public class ListTransformation { /** * Maps an add event of the model list to new elements of the { @ link # viewModelList } .
 * @ param listEvent
 * to analyze */
private void processAddEvent ( ListChangeListener . Change < ? extends SourceType > listEvent ) { } }

implementation: final List < TargetType > toAdd = new ArrayList < > ( ) ; for ( int index = listEvent . getFrom ( ) ; index < listEvent . getTo ( ) ; index ++ ) { final SourceType item = listEvent . getList ( ) . get ( index ) ; toAdd . add ( function . apply ( item ) ) ; } viewModelList . addAll ( listEvent . getFrom ( ) , toAdd ) ;


signature:
public class ListTransformation { /** * Maps an remove event of the model list to new elements of the { @ link # viewModelList } .
 * @ param listEvent
 * to process
 * @ param deleteStaging
 * for staging the delete events */
private void processRemoveEvent ( ListChangeListener . Change < ? extends SourceType > listEvent , List < TargetType > deleteStaging ) { } }

implementation: for ( int i = 0 ; i < listEvent . getRemovedSize ( ) ; i ++ ) { deleteStaging . add ( viewModelList . get ( listEvent . getFrom ( ) + i ) ) ; }


signature:
public class ListTransformation { /** * Maps an update event of the model list to new elements of the { @ link # viewModelList } .
 * @ param listEvent
 * to process */
private void processUpdateEvent ( ListChangeListener . Change < ? extends SourceType > listEvent ) { } }

implementation: for ( int i = listEvent . getFrom ( ) ; i < listEvent . getTo ( ) ; i ++ ) { SourceType item = listEvent . getList ( ) . get ( i ) ; viewModelList . set ( i , ListTransformation . this . function . apply ( item ) ) ; }


signature:
public class ListTransformation { /** * Maps an replace event of the model list to new elements of the { @ link # viewModelList } .
 * @ param listEvent
 * to process */
private void processReplaceEvent ( ListChangeListener . Change < ? extends SourceType > listEvent , List < TargetType > deletedStaging ) { } }

implementation: processRemoveEvent ( listEvent , deletedStaging ) ; processStagingLists ( deletedStaging ) ; processAddEvent ( listEvent ) ;


signature:
public class Repository { /** * Gets a Person . s
 * @ param id of the person
 * @ return person */
public Person getPersonById ( final int id ) { } }

implementation: for ( Person person : persons ) { if ( id == person . getId ( ) ) { return person ; } } return null ;


signature:
public class GlobalBuilderFactory { /** * Create a new BuilderFactory instance that contains all custom factories of this instance
 * combined with the list of factories passed as argument to this method .
 * < br / >
 * This instance of the builderFactory is not changed by this method . */
public BuilderFactory mergeWith ( List < BuilderFactory > factories ) { } }

implementation: GlobalBuilderFactory factory = new GlobalBuilderFactory ( ) ; factory . factories . addAll ( factories ) ; return factory ;


signature:
public class WeakValueHashMap { /** * Puts a new ( key , value ) into the map .
 * @ param key
 * key with which the specified value is to be associated .
 * @ param value
 * value to be associated with the specified key .
 * @ return previous value associated with specified key , or null if there was no mapping for key or the value has
 * been garbage collected by the garbage collector . */
@ Override public Object put ( Object key , Object value ) { } }

implementation:
// If the map already contains an equivalent key , the new key
// of a ( key , value ) pair is NOT stored in the map but the new
// value only . But as the key is strongly referenced by the
// map , it can not be removed from the garbage collector , even
// if the key becomes weakly reachable due to the old
// value . So , it isn ' t necessary to remove all garbage
// collected values with their keys from the map before the
// new entry is made . We only clean up here to distribute
// clean up calls on different operations .
processQueue ( ) ; WeakValue oldValue = ( WeakValue ) super . put ( key , WeakValue . create ( key , value , queue ) ) ; return getReferenceObject ( oldValue ) ;


signature:
public class WeakValueHashMap { /** * Removes all garbage collected values with their keys from the map . Since we don ' t know how much the
 * ReferenceQueue . poll ( ) operation costs , we should not call it every map operation . */
private void processQueue ( ) { } }

implementation:
WeakValue wv = null ; while ( ( wv = ( WeakValue ) this . queue . poll ( ) ) != null ) { // " super " is not really necessary but use it
// to be on the safe side
super . remove ( wv . key ) ; }


signature:
public class WeakValueHashMap { /** * Returns a < code > Set < / code > view of the mappings in this map .
 * @ return a < code > Set < / code > view of the mappings in this map . */
@ Override public Set entrySet ( ) { } }

implementation: if ( entrySet == null ) { hashEntrySet = super . entrySet ( ) ; entrySet = new EntrySet ( ) ; } return entrySet ;


signature:
public class WeakValueHashMap { /** * Returns a < code > Collection < / code > view of the values contained in this map .
 * @ return a < code > Collection < / code > view of the values contained in this map . */
@ Override public Collection values ( ) { } }

implementation:
// delegates to entrySet , because super method returns
// WeakValues instead of value objects
if ( values == null ) { values = new AbstractCollection ( ) { @ Override public Iterator iterator ( ) { return new Iterator ( ) { private final Iterator i = entrySet ( ) . iterator ( ) ; @ Override public boolean hasNext ( ) { return i . hasNext ( ) ; } @ Override public Object next ( ) { return ( ( Entry ) i . next ( ) ) . getValue ( ) ; } @ Override public void remove ( ) { i . remove ( ) ; } } ; } @ Override public int size ( ) { return WeakValueHashMap . this . size ( ) ; } @ Override public boolean contains ( Object v ) { return WeakValueHashMap . this . containsValue ( v ) ; } } ; } return values ;


signature:
public class CompositeValidationStatus { /** * Add a list of validation messages for the specified validator . */
void addMessage ( Validator validator , List < ? extends ValidationMessage > messages ) { } }

implementation:
if ( messages . isEmpty ( ) ) { return ; } final int validatorHash = System . identityHashCode ( validator ) ; if ( ! validatorToMessagesMap . containsKey ( validatorHash ) ) { validatorToMessagesMap . put ( validatorHash , new ArrayList < > ( ) ) ; } final List < Integer > messageHashesOfThisValidator = validatorToMessagesMap . get ( validatorHash ) ; // add the hashCodes of the messages to the internal map
messages . stream ( ) . map ( System :: identityHashCode ) . forEach ( messageHashesOfThisValidator :: add ) ; // add the actual messages to the message list so that they are accessible by the user .
getMessagesInternal ( ) . addAll ( messages ) ;


signature:
public class CompositeValidationStatus { /** * Remove all given messages for the given validator . */
void removeMessage ( final Validator validator , final List < ? extends ValidationMessage > messages ) { } }

implementation:
if ( messages . isEmpty ( ) ) { return ; } final int validatorHash = System . identityHashCode ( validator ) ; // if the validator is unknown by the map we haven ' t stored any messages for it yet that could be removed
if ( validatorToMessagesMap . containsKey ( validatorHash ) ) { final List < Integer > messageHashesOfThisValidator = validatorToMessagesMap . get ( validatorHash ) ; final List < Integer > hashesOfMessagesToRemove = messages . stream ( ) . filter ( m -> { // only those messages that are stored for this validator
int hash = System . identityHashCode ( m ) ; return messageHashesOfThisValidator . contains ( hash ) ; } ) . map ( System :: identityHashCode ) // we only need the hashCode here
. collect ( Collectors . toList ( ) ) ; // only remove those messages that we have the hashCode stored
getMessagesInternal ( ) . removeIf ( message -> { int hash = System . identityHashCode ( message ) ; return hashesOfMessagesToRemove . contains ( hash ) ; } ) ; // we need to cleanup our internal map
messageHashesOfThisValidator . removeAll ( hashesOfMessagesToRemove ) ; if ( messageHashesOfThisValidator . isEmpty ( ) ) { validatorToMessagesMap . remove ( validatorHash ) ; } }


signature:
public class CompositeValidationStatus { /** * Remove all messages for this particular validator . */
void removeMessage ( final Validator validator ) { } }

implementation: final int validatorHash = System . identityHashCode ( validator ) ; if ( validatorToMessagesMap . containsKey ( validatorHash ) ) { final List < Integer > messageHashesOfThisValidator = validatorToMessagesMap . get ( validatorHash ) ; getMessagesInternal ( ) . removeIf ( message -> { int hash = System . identityHashCode ( message ) ; return messageHashesOfThisValidator . contains ( hash ) ; } ) ; validatorToMessagesMap . remove ( validatorHash ) ; }


signature:
public class PersonWelcomeViewModel { /** * Set Person id for the screen
 * @ param personId for the screen */
public void setPersonId ( int personId ) { } }

implementation: person = repository . getPersonById ( personId ) ; StringBinding salutationBinding = Bindings . when ( person . genderProperty ( ) . isEqualTo ( Gender . NOT_SPECIFIED ) ) . then ( "Herr/Frau/* " ) . otherwise ( Bindings . when ( person . genderProperty ( ) . isEqualTo ( Gender . MALE ) ) . then ( "Herr " ) . otherwise ( "Frau " ) ) ; welcomeString . unbind ( ) ; welcomeString . bind ( Bindings . concat ( "Willkommen " , salutationBinding , person . firstNameProperty ( ) , " " , person . lastNameProperty ( ) ) ) ;


signature:
public class JavaViewLoader { /** * Loads the java written view of the given type and injects the ViewModel
 * for this view . < br >
 * If the given view type implements the { @ link javafx . fxml . Initializable }
 * interface the " initialize " method of this interface will be invoked . When
 * this is not the case an implicit initialization will be done that is
 * working similar to the way the { @ link javafx . fxml . FXMLLoader } is working .
 * < br >
 * When there is a < strong > public < / strong > no - args method named " initialize "
 * is available this method will be called . When there is a
 * < strong > public < / strong > field of type { @ link java . util . ResourceBundle }
 * named " resources " is available this field will get the provided
 * ResourceBundle injected . < br >
 * The " initialize " method ( whether from the
 * { @ link javafx . fxml . Initializable } interface or implicit ) will be invoked
 * < strong > after < / strong > the viewModel was injected . This way the user can
 * create bindings to the viewModel in the initialize method .
 * @ param viewType
 * class of the view .
 * @ param resourceBundle
 * optional ResourceBundle that will be injected into the view .
 * @ param existingViewModel
 * the viewModel instance that is used to load the view .
 * @ param < ViewType >
 * the generic type of the view .
 * @ param < ViewModelType >
 * the generic type of the viewModel .
 * @ return a fully loaded and initialized instance of the view . */
public < ViewType extends View < ? extends ViewModelType > , ViewModelType extends ViewModel > ViewTuple < ViewType , ViewModelType > loadJavaViewTuple ( Class < ? extends ViewType > viewType , ResourceBundle resourceBundle , final ViewModelType existingViewModel , ViewType codeBehind , Context parentContext , Collection < Scope > providedScopes ) { } }

implementation:
// FIXME Woanders hin ? !
ContextImpl context = ViewLoaderScopeUtils . prepareContext ( parentContext , providedScopes ) ; DependencyInjector injectionFacade = DependencyInjector . getInstance ( ) ; final ViewType view = codeBehind == null ? injectionFacade . getInstanceOf ( viewType ) : codeBehind ; if ( ! ( view instanceof Parent ) ) { throw new IllegalArgumentException ( "Can not load java view! The view class has to extend from " + Parent . class . getName ( ) + " or one of it's subclasses" ) ; } ViewModelType viewModel = null ; // when no viewmodel was provided by the user . . .
if ( existingViewModel == null ) { // . . . we create a new one ( if possible )
viewModel = ViewLoaderReflectionUtils . createViewModel ( view ) ; } else { viewModel = existingViewModel ; } ResourceBundleInjector . injectResourceBundle ( view , resourceBundle ) ; // if no ViewModel is available . . .
if ( viewModel == null ) { // we need to check if the user is trying to inject a viewModel .
final List < Field > viewModelFields = ViewLoaderReflectionUtils . getViewModelFields ( viewType ) ; if ( ! viewModelFields . isEmpty ( ) ) { throw new RuntimeException ( "The given view of type <" + view . getClass ( ) + "> has no generic viewModel type declared but tries to inject a viewModel." ) ; } } else { ResourceBundleInjector . injectResourceBundle ( viewModel , resourceBundle ) ; // if the user has provided an existing ViewModel , we will not
// ( re - ) initialize this existing instance
ViewLoaderReflectionUtils . createAndInjectScopes ( viewModel , context ) ; if ( existingViewModel == null ) { ViewLoaderReflectionUtils . initializeViewModel ( viewModel ) ; } ViewLoaderReflectionUtils . injectViewModel ( view , viewModel ) ; } if ( view instanceof Initializable ) { Initializable initializable = ( Initializable ) view ; initializable . initialize ( null , resourceBundle ) ; } else { injectResourceBundle ( view , resourceBundle ) ; callInitialize ( view ) ; } return new ViewTuple < > ( view , ( Parent ) view , viewModel ) ;


signature:
public class JavaViewLoader { /** * This method is trying to invoke the initialize method of the given view
 * by reflection . This is done to meet the conventions of the
 * { @ link javafx . fxml . FXMLLoader } . The conventions say that when there is a
 * < strong > public < / strong > no - args method with the simple name " initialize "
 * and the class does not implement the { @ link javafx . fxml . Initializable }
 * interface , the initialize method will be invoked . < br >
 * This method is package scoped for better testability .
 * @ param view
 * the view instance of which the initialize method will be
 * invoked .
 * @ param < ViewModelType >
 * the generic type of the view . */
< ViewModelType extends ViewModel > void callInitialize ( View < ? extends ViewModelType > view ) { } }

implementation:
try { final Method initializeMethod = view . getClass ( ) . getMethod ( NAMING_CONVENTION_INITIALIZE_IDENTIFIER ) ; AccessController . doPrivileged ( ( PrivilegedAction ) ( ) -> { try { return initializeMethod . invoke ( view ) ; } catch ( InvocationTargetException e ) { LOG . warn ( "The '{}' method of the view {} has thrown an exception!" , NAMING_CONVENTION_INITIALIZE_IDENTIFIER , view ) ; Throwable cause = e . getCause ( ) ; if ( cause instanceof RuntimeException ) { throw ( RuntimeException ) cause ; } else { throw new RuntimeException ( cause ) ; } } catch ( IllegalAccessException e ) { LOG . warn ( "Can't invoke the '{}' method of the view {} because it is not accessible" , NAMING_CONVENTION_INITIALIZE_IDENTIFIER , view ) ; } return null ; } ) ; } catch ( NoSuchMethodException e ) { // This exception means that there is no initialize method declared .
// While it ' s possible that the user has no such method by design ,
// normally and in most cases you need an initialize method in your
// view ( either with Initialize interface
// or implicit ) .
// So it ' s likely that the user has misspelled the method name or
// uses a wrong naming convention .
// For this reason we give the user the log message .
LOG . debug ( "There is no '{}' method declared at the view {}" , NAMING_CONVENTION_INITIALIZE_IDENTIFIER , view ) ; }


signature:
public class JavaViewLoader { /** * Injects the given ResourceBundle into the given view using reflection .
 * This is done to meet the conventions of the
 * { @ link javafx . fxml . FXMLLoader } . The resourceBundle is only injected when
 * there is a < strong > public < / strong > field of the type
 * { @ link java . util . ResourceBundle } named " resources " . < br >
 * This method is package scoped for better testability .
 * @ param view
 * the view instance that gets the resourceBundle injected .
 * @ param resourceBundle
 * the resourceBundle instance that will be injected .
 * @ param < ViewModelType >
 * the generic type of the view . */
< ViewModelType extends ViewModel > void injectResourceBundle ( View < ? extends ViewModelType > view , ResourceBundle resourceBundle ) { } }

implementation:
try { Field resourcesField = view . getClass ( ) . getField ( NAMING_CONVENTION_RESOURCES_IDENTIFIER ) ; if ( resourcesField . getType ( ) . isAssignableFrom ( ResourceBundle . class ) ) { resourcesField . set ( view , resourceBundle ) ; } } catch ( NoSuchFieldException e ) { // This exception means that there is no field for the
// ResourceBundle .
// This is no exceptional case but is normal when you don ' t need a
// resourceBundle in a specific view .
// Therefore it ' s save to silently catch the exception .
} catch ( IllegalAccessException e ) { LOG . warn ( "Can't inject the ResourceBundle into the view {} because the field isn't accessible" , view ) ; }


signature:
public class DetailViewModel { /** * When the given source binding has a value of < code > null < / code > an empty
 * string is used for the returned binding . Otherwise the value of the
 * source binding is used . */
private StringBinding emptyStringOnNull ( ObservableValue < String > source ) { } }

implementation: return Bindings . createStringBinding ( ( ) -> { if ( source . getValue ( ) == null ) { return "" ; } else { return source . getValue ( ) ; } } , source ) ;


signature:
public class ViewLoaderReflectionUtils { /** * Returns the { @ link java . lang . reflect . Field } of the viewModel for a given
 * view type and viewModel type . If there is no annotated field for the
 * viewModel in the view the returned Optional will be empty .
 * @ param viewType
 * the type of the view
 * @ param viewModelType
 * the type of the viewModel
 * @ return an Optional that contains the Field when the field exists . */
public static Optional < Field > getViewModelField ( Class < ? extends View > viewType , Class < ? > viewModelType ) { } }

implementation: List < Field > allViewModelFields = getViewModelFields ( viewType ) ; if ( allViewModelFields . isEmpty ( ) ) { return Optional . empty ( ) ; } if ( allViewModelFields . size ( ) > 1 ) { throw new RuntimeException ( "The View <" + viewType + "> may only define one viewModel but there were <" + allViewModelFields . size ( ) + "> viewModel fields with the @InjectViewModel annotation!" ) ; } Field field = allViewModelFields . get ( 0 ) ; if ( ! ViewModel . class . isAssignableFrom ( field . getType ( ) ) ) { throw new RuntimeException ( "The View <" + viewType + "> has a field annotated with @InjectViewModel but the type of the field doesn't implement the 'ViewModel' interface!" ) ; } if ( ! field . getType ( ) . isAssignableFrom ( viewModelType ) ) { throw new RuntimeException ( "The View <" + viewType + "> has a field annotated with @InjectViewModel but the type of the field doesn't match the generic ViewModel type of the View class. " + "The declared generic type is <" + viewModelType + "> but the actual type of the field is <" + field . getType ( ) + ">." ) ; } return Optional . of ( field ) ;


signature:
public class ViewLoaderReflectionUtils { /** * This method is used to get the ViewModel instance of a given
 * view / codeBehind .
 * @ param view
 * the view instance where the viewModel will be looked for .
 * @ param < ViewType >
 * the generic type of the View
 * @ param < ViewModelType >
 * the generic type of the ViewModel
 * @ return the ViewModel instance or null if no viewModel could be found . */
@ SuppressWarnings ( "unchecked" ) public static < ViewType extends View < ? extends ViewModelType > , ViewModelType extends ViewModel > ViewModelType getExistingViewModel ( ViewType view ) { } }

implementation: final Class < ? > viewModelType = TypeResolver . resolveRawArgument ( View . class , view . getClass ( ) ) ; Optional < Field > fieldOptional = getViewModelField ( view . getClass ( ) , viewModelType ) ; if ( fieldOptional . isPresent ( ) ) { Field field = fieldOptional . get ( ) ; return ReflectionUtils . accessMember ( field , ( ) -> ( ViewModelType ) field . get ( view ) , "Can't get the viewModel of type <" + viewModelType + ">" ) ; } else { return null ; }


signature:
public class ViewLoaderReflectionUtils { /** * Injects the given viewModel instance into the given view . The injection
 * will only happen when the class of the given view has a viewModel field
 * that fulfills all requirements for the viewModel injection ( matching
 * types , no viewModel already existing . . . ) .
 * @ param view
 * @ param viewModel */
public static void injectViewModel ( final View view , ViewModel viewModel ) { } }

implementation: if ( viewModel == null ) { return ; } final Optional < Field > fieldOptional = getViewModelField ( view . getClass ( ) , viewModel . getClass ( ) ) ; if ( fieldOptional . isPresent ( ) ) { Field field = fieldOptional . get ( ) ; ReflectionUtils . accessMember ( field , ( ) -> { Object existingViewModel = field . get ( view ) ; if ( existingViewModel == null ) { field . set ( view , viewModel ) ; } } , "Can't inject ViewModel of type <" + viewModel . getClass ( ) + "> into the view <" + view + ">" ) ; }


signature:
public class ViewLoaderReflectionUtils { /** * This method is used to create and inject the ViewModel for a given View
 * instance .
 * The following checks are done :
 * < ul >
 * < li > Check whether the View class specifies a ViewModel type as generic
 * type . < / li >
 * < li > Check whether the View has a field with a matching ViewModel type and
 * the annotation { @ link InjectViewModel } . < / li >
 * < li > Check whether field in the view instance already contains a ViewModel
 * instance . In this case nothing will happen to the existing ViewModel
 * instance . < / li >
 * < / ul >
 * If a suitable field was found a new ViewModel instance will be created
 * and injected into the field . After that the given Consumer function will
 * be applied with the injected ViewModel instance as argument .
 * @ param view
 * the view instance .
 * @ param < V >
 * the generic type of the View .
 * @ param < VM >
 * the generic type of the ViewModel .
 * @ param newVmConsumer
 * a Consumer function that is applied when a new ViewModel
 * instance is created .
 * @ throws RuntimeException
 * if there is a ViewModel field in the View with the
 * { @ link InjectViewModel } annotation whose type doesn ' t match
 * the generic ViewModel type from the View class . */
@ SuppressWarnings ( "unchecked" ) public static < V extends View < ? extends VM > , VM extends ViewModel > void createAndInjectViewModel ( final V view , Consumer < ViewModel > newVmConsumer ) { } }

implementation:
final Class < ? > viewModelType = TypeResolver . resolveRawArgument ( View . class , view . getClass ( ) ) ; if ( viewModelType == ViewModel . class ) { // if no viewModel can be created , we have to check if the user has
// tried to inject a ViewModel
final List < Field > viewModelFields = ViewLoaderReflectionUtils . getViewModelFields ( view . getClass ( ) ) ; if ( ! viewModelFields . isEmpty ( ) ) { throw new RuntimeException ( "The given view of type <" + view . getClass ( ) + "> has no generic viewModel type declared but tries to inject a viewModel." ) ; } return ; } if ( viewModelType == TypeResolver . Unknown . class ) { return ; } final Optional < Field > fieldOptional = getViewModelField ( view . getClass ( ) , viewModelType ) ; if ( fieldOptional . isPresent ( ) ) { Field field = fieldOptional . get ( ) ; ReflectionUtils . accessMember ( field , ( ) -> { Object existingViewModel = field . get ( view ) ; if ( existingViewModel == null ) { final Object newViewModel = DependencyInjector . getInstance ( ) . getInstanceOf ( viewModelType ) ; field . set ( view , newViewModel ) ; newVmConsumer . accept ( ( ViewModel ) newViewModel ) ; } } , "Can't inject ViewModel of type <" + viewModelType + "> into the view <" + view + ">" ) ; }


signature:
public class ViewLoaderReflectionUtils { /** * Creates a viewModel instance for a View type . The type of the view is
 * determined by the given view instance .
 * For the creation of the viewModel the { @ link DependencyInjector } is used .
 * @ param view
 * the view instance that is used to find out the type of the
 * ViewModel
 * @ param < ViewType >
 * the generic view type
 * @ param < ViewModelType >
 * the generic viewModel type
 * @ return the viewModel instance or < code > null < / code > if the viewModel type
 * can ' t be found or the viewModel can ' t be created . */
@ SuppressWarnings ( "unchecked" ) public static < ViewType extends View < ? extends ViewModelType > , ViewModelType extends ViewModel > ViewModelType createViewModel ( ViewType view ) { } }

implementation: final Class < ? > viewModelType = TypeResolver . resolveRawArgument ( View . class , view . getClass ( ) ) ; if ( viewModelType == ViewModel . class ) { return null ; } if ( TypeResolver . Unknown . class == viewModelType ) { return null ; } return ( ViewModelType ) DependencyInjector . getInstance ( ) . getInstanceOf ( viewModelType ) ;


signature:
public class ViewLoaderReflectionUtils { /** * If a ViewModel has a method annotated with { @ link Initialize }
 * or method with the signature < code > public void initialize ( ) < / code >
 * it will be invoked . If no such method is available nothing happens .
 * @ param viewModel
 * the viewModel that ' s initialize method ( if available ) will be
 * invoked .
 * @ param < ViewModelType >
 * the generic type of the ViewModel . */
public static < ViewModelType extends ViewModel > void initializeViewModel ( ViewModelType viewModel ) { } }

implementation:
if ( viewModel == null ) { return ; } final Collection < Method > initializeMethods = getInitializeMethods ( viewModel . getClass ( ) ) ; initializeMethods . forEach ( initMethod -> { // if there is a @ PostConstruct annotation , throw an exception to prevent double injection
final boolean postConstructPresent = Arrays . stream ( initMethod . getAnnotations ( ) ) . map ( Annotation :: annotationType ) . map ( Class :: getName ) . anyMatch ( "javax.annotation.PostConstruct" :: equals ) ; if ( postConstructPresent ) { throw new IllegalStateException ( String . format ( "initialize method of ViewModel [%s] is annotated with @PostConstruct. " + "This will lead to unexpected behaviour and duplicate initialization. " + "Please rename the method or remove the @PostConstruct annotation. " + "See mvvmFX wiki for more details: " + "https://github.com/sialcasa/mvvmFX/wiki/Dependency-Injection#lifecycle-postconstruct" , viewModel ) ) ; } ReflectionUtils . accessMember ( initMethod , ( ) -> initMethod . invoke ( viewModel ) , "mvvmFX wasn't able to call the initialize method of ViewModel [" + viewModel + "]." ) ; } ) ;


signature:
public class ViewLoaderReflectionUtils { /** * Returns a collection of { @ link Method } s that represent initializer methods .
 * A method is an " initializer method " if it either : < br / >
 * < ol >
 * < li > has a signature of " public void initialize ( ) " < / li >
 * < li > is annotated with { @ link Initialize } < / li >
 * < / ol > */
private static Collection < Method > getInitializeMethods ( Class < ? > classType ) { } }

implementation: final List < Method > initializeMethods = new ArrayList < > ( ) ; Arrays . stream ( classType . getMethods ( ) ) . filter ( method -> "initialize" . equals ( method . getName ( ) ) ) . filter ( method -> void . class . equals ( method . getReturnType ( ) ) ) . filter ( method -> method . getParameterCount ( ) == 0 ) . forEach ( initializeMethods :: add ) ; Arrays . stream ( classType . getDeclaredMethods ( ) ) . filter ( method -> method . isAnnotationPresent ( Initialize . class ) ) . forEach ( initializeMethods :: add ) ; return initializeMethods ;


signature:
public class ViewLoaderReflectionUtils { /** * This method adds listeners for the { @ link SceneLifecycle } . */
static void addSceneLifecycleHooks ( ViewModel viewModel , ObservableBooleanValue viewInSceneProperty ) { } }

implementation: if ( viewModel != null ) { if ( viewModel instanceof SceneLifecycle ) { SceneLifecycle lifecycleViewModel = ( SceneLifecycle ) viewModel ; PreventGarbageCollectionStore . getInstance ( ) . put ( viewInSceneProperty ) ; viewInSceneProperty . addListener ( ( observable , oldValue , newValue ) -> { if ( newValue ) { lifecycleViewModel . onViewAdded ( ) ; } else { lifecycleViewModel . onViewRemoved ( ) ; PreventGarbageCollectionStore . getInstance ( ) . remove ( viewInSceneProperty ) ; } } ) ; } }


signature:
public class ViewLoaderReflectionUtils { /** * This method is used to check if the given View instance has one or more fields that try to inject a scope
 * with the { @ link InjectScope } annotation .
 * This is a violation of the mvvm - pattern and therefore this method will throw an exception with a message describing the
 * error . */
static void checkScopesInView ( View codeBehind ) { } }

implementation: List < Field > scopeFields = ReflectionUtils . getFieldsWithAnnotation ( codeBehind , InjectScope . class ) ; if ( ! scopeFields . isEmpty ( ) ) { throw new IllegalStateException ( "The view class [" + codeBehind . getClass ( ) . getSimpleName ( ) + "] tries to inject a Scope with " + "@InjectScope. This would be a violation of the mvvm pattern. Scopes are only supported in ViewModels." ) ; }


signature:
public class DataFxCountrySelector { /** * Set the currently selected country . This will lead to an update of the
 * { @ link # subdivisions ( ) } observable list and the
 * { @ link # subdivisionLabel ( ) } .
 * @ param country the country that will be selected or < code > null < / code > if
 * no country is selected . */
@ Override public void setCountry ( Country country ) { } }

implementation: if ( country == null ) { subdivisionLabel . set ( null ) ; subdivisions . clear ( ) ; return ; } subdivisionLabel . set ( countryCodeSubdivisionNameMap . get ( country ) ) ; subdivisions . clear ( ) ; if ( countryCodeSubdivisionMap . containsKey ( country ) ) { subdivisions . addAll ( countryCodeSubdivisionMap . get ( country ) ) ; }


signature:
public class DataFxCountrySelector { /** * Load all countries from the XML file source with DataFX . */
void loadCountries ( ) { } }

implementation:
InputStream iso3166Resource = this . getClass ( ) . getResourceAsStream ( ISO_3166_LOCATION ) ; if ( iso3166Resource == null ) { throw new IllegalStateException ( "Can't find the list of countries! Expected location was:" + ISO_3166_LOCATION ) ; } XmlConverter < Country > countryConverter = new XmlConverter < > ( "iso_3166_entry" , Country . class ) ; try { DataReader < Country > dataSource = new InputStreamSource < > ( iso3166Resource , countryConverter ) ; ListDataProvider < Country > listDataProvider = new ListDataProvider < > ( dataSource ) ; listDataProvider . setResultObservableList ( countries ) ; Worker < ObservableList < Country > > worker = listDataProvider . retrieve ( ) ; // when the countries are loaded we start the loading of the subdivisions .
worker . stateProperty ( ) . addListener ( obs -> { if ( worker . getState ( ) == Worker . State . SUCCEEDED ) { loadSubdivisions ( ) ; } } ) ; } catch ( IOException e ) { LOG . error ( "A problem was detected while loading the XML file with the available countries." , e ) ; }


signature:
public class DataFxCountrySelector { /** * Load all subdivisions from the XML file source with DataFX . */
void loadSubdivisions ( ) { } }

implementation: InputStream iso3166_2Resource = this . getClass ( ) . getResourceAsStream ( ISO_3166_2_LOCATION ) ; if ( iso3166_2Resource == null ) { throw new IllegalStateException ( "Can't find the list of subdivisions! Expected location was:" + ISO_3166_2_LOCATION ) ; } XmlConverter < ISO3166_2_CountryEntity > converter = new XmlConverter < > ( "iso_3166_country" , ISO3166_2_CountryEntity . class ) ; ObservableList < ISO3166_2_CountryEntity > subdivisionsEntities = FXCollections . observableArrayList ( ) ; try { DataReader < ISO3166_2_CountryEntity > dataSource = new InputStreamSource < > ( iso3166_2Resource , converter ) ; ListDataProvider < ISO3166_2_CountryEntity > listDataProvider = new ListDataProvider < > ( dataSource ) ; listDataProvider . setResultObservableList ( subdivisionsEntities ) ; Worker < ObservableList < ISO3166_2_CountryEntity > > worker = listDataProvider . retrieve ( ) ; worker . stateProperty ( ) . addListener ( obs -> { if ( worker . getState ( ) == Worker . State . SUCCEEDED ) { subdivisionsEntities . forEach ( entity -> { if ( entity . subsets != null && ! entity . subsets . isEmpty ( ) ) { Country country = findCountryByCode ( entity . code ) ; if ( ! countryCodeSubdivisionMap . containsKey ( country ) ) { countryCodeSubdivisionMap . put ( country , new ArrayList < > ( ) ) ; } List < Subdivision > subdivisionList = countryCodeSubdivisionMap . get ( country ) ; entity . subsets . forEach ( subset -> { subset . entryList . forEach ( entry -> { subdivisionList . add ( new Subdivision ( entry . name , entry . code , country ) ) ; } ) ; } ) ; String subdivisionName = entity . subsets . stream ( ) . map ( subset -> subset . subdivisionType ) . collect ( Collectors . joining ( "/" ) ) ; countryCodeSubdivisionNameMap . put ( country , subdivisionName ) ; } } ) ; inProgress . set ( false ) ; } } ) ; } catch ( IOException e ) { LOG . error ( "A problem was detected while loading the XML file with the available subdivisions." , e ) ; }


signature:
public class DefaultNotificationCenter { /** * This notification will be send to the UI - Thread ( if the UI - toolkit was bootstrapped ) .
 * If no UI - Toolkit is available the notification will be directly published . This is typically the case in unit tests .
 * @ param channel the channel
 * @ param messageName the message to sent
 * @ param payload additional arguments to the message */
@ Override public void publish ( Object channel , String messageName , Object [ ] payload ) { } }

implementation:
if ( channelObserverMap . containsKey ( channel ) ) { final ObserverMap observerMap = channelObserverMap . get ( channel ) ; if ( shouldPublishInThisThread ( ) ) { publish ( messageName , payload , observerMap ) ; } else { try { Platform . runLater ( ( ) -> publish ( messageName , payload , observerMap ) ) ; } catch ( IllegalStateException e ) { // If the toolkit isn ' t initialized yet we will publish the notification directly .
// In most cases this means that we are in a unit test and not JavaFX application is running .
if ( e . getMessage ( ) . equals ( "Toolkit not initialized" ) ) { publish ( messageName , payload , observerMap ) ; } else { throw e ; } } } }


signature:
public class DefaultNotificationCenter { /** * Helper */
private static void publish ( String messageName , Object [ ] payload , ObserverMap observerMap ) { } }

implementation:
Collection < NotificationObserver > notificationReceivers = observerMap . get ( messageName ) ; if ( notificationReceivers != null ) { // make a copy to prevent ConcurrentModificationException if inside of an observer a new observer is subscribed .
for ( NotificationObserver observer : notificationReceivers ) { observer . receivedNotification ( messageName , payload ) ; } }


signature:
public class MvvmfxSpringApplication { /** * This method is invoked when the javafx application is initialized . See { @ link javafx . application . Application # init ( ) } for more details .
 * Unlike the original init method in { @ link javafx . application . Application } this method contains logic to initialize
 * the Spring - Boot container . For this reason this method is now final to prevent unintended overriding .
 * Please use { @ link # initMvvmfx ( ) } for you own initialization logic .
 * @ throws Exception */
@ Override public final void init ( ) throws Exception { } }

implementation: ctx = SpringApplication . run ( this . getClass ( ) ) ; MvvmFX . setCustomDependencyInjector ( ctx :: getBean ) ; ctx . getBeanFactory ( ) . autowireBean ( this ) ; initMvvmfx ( ) ;


signature:
public class ModelWrapper { /** * Resets all defined fields to their default values .
 * Default values can be defined as last argument of the overloaded " field " methods
 * ( see { @ link # field ( StringGetter , StringSetter , String ) } )
 * or by using the { @ link # useCurrentValuesAsDefaults ( ) } method .
 * If no special default value was defined for a field the default value of the actual Property type will be used
 * ( e . g . 0 for { @ link IntegerProperty } , < code > null < / code > for { @ link StringProperty } and { @ link ObjectProperty } . . . ) .
 * < b > Note : < / b > This method has no effects on the wrapped model element but will only change the values of the
 * defined property fields . */
public void reset ( ) { } }

implementation: fields . forEach ( PropertyField :: resetToDefault ) ; immutableFields . forEach ( PropertyField :: resetToDefault ) ; calculateDifferenceFlag ( ) ;


signature:
public class ModelWrapper { /** * Use all values that are currently present in the wrapped model object as new default values for respective fields .
 * This overrides / updates the values that were set during the initialization of the field mappings .
 * Subsequent calls to { @ link # reset ( ) } will reset the values to this new default values .
 * Usage example :
 * < pre >
 * ModelWrapper { @ code < Person > } wrapper = new ModelWrapper { @ code < > } ( ) ;
 * wrapper . field ( Person : : getName , Person : : setName , " oldDefault " ) ;
 * Person p = new Person ( ) ;
 * wrapper . set ( p ) ;
 * p . setName ( " Luise " ) ;
 * wrapper . useCurrentValuesAsDefaults ( ) ; / / now " Luise " is the default value for the name field .
 * name . set ( " Hugo " ) ;
 * wrapper . commit ( ) ;
 * name . get ( ) ; / / Hugo
 * p . getName ( ) ; / / Hugo
 * wrapper . reset ( ) ; / / reset to the new defaults
 * name . get ( ) ; / / Luise
 * wrapper . commit ( ) ; / / put values from properties to the wrapped model object
 * p . getName ( ) ; / / Luise
 * < / pre >
 * If no model instance is set to be wrapped by the ModelWrapper , nothing will happen when this method is invoked .
 * Instead the old default values will still be available . */
public void useCurrentValuesAsDefaults ( ) { } }

implementation: M wrappedModelInstance = model . get ( ) ; if ( wrappedModelInstance != null ) { for ( final PropertyField < ? , M , ? > field : fields ) { field . updateDefault ( wrappedModelInstance ) ; } for ( final ImmutablePropertyField < ? , M , ? > field : immutableFields ) { field . updateDefault ( wrappedModelInstance ) ; } }


signature:
public class ModelWrapper { /** * Take the current value of each property field and write it into the wrapped model element .
 * If no model element is defined then nothing will happen .
 * < b > Note : < / b > This method has no effects on the values of the defined property fields but will only change the
 * state of the wrapped model element . */
public void commit ( ) { } }

implementation: if ( model . get ( ) != null ) { inCommitPhase = true ; fields . forEach ( field -> field . commit ( model . get ( ) ) ) ; if ( ! immutableFields . isEmpty ( ) ) { M tmp = model . get ( ) ; for ( ImmutablePropertyField < ? , M , ? > immutableField : immutableFields ) { tmp = immutableField . commitImmutable ( tmp ) ; } model . set ( tmp ) ; } inCommitPhase = false ; dirtyFlag . set ( false ) ; calculateDifferenceFlag ( ) ; }


signature:
public class ModelWrapper { /** * Take the current values from the wrapped model element and put them in the corresponding property fields .
 * If no model element is defined then nothing will happen .
 * < b > Note : < / b > This method has no effects on the wrapped model element but will only change the values of the
 * defined property fields . */
public void reload ( ) { } }

implementation: M wrappedModelInstance = model . get ( ) ; if ( wrappedModelInstance != null ) { fields . forEach ( field -> field . reload ( wrappedModelInstance ) ) ; immutableFields . forEach ( field -> field . reload ( wrappedModelInstance ) ) ; dirtyFlag . set ( false ) ; calculateDifferenceFlag ( ) ; }


signature:
public class ModelWrapper { /** * This method can be used to copy all values of this { @ link ModelWrapper } instance
 * to the model instance provided as argument .
 * Existing values in the provided model instance will be overwritten .
 * This method doesn ' t change the state of this modelWrapper or the wrapped model instance .
 * @ param model a non - null instance of a model . */
public void copyValuesTo ( M model ) { } }

implementation: Objects . requireNonNull ( model ) ; fields . forEach ( field -> field . commit ( model ) ) ;


signature:
public class ModelWrapper { /** * Add a new field of type String to this instance of the wrapper . This method is used for model elements that are
 * following the normal Java - Beans - standard i . e . the model fields are only available via getter and setter methods
 * and not as JavaFX Properties .
 * Example :
 * < pre >
 * ModelWrapper { @ code < Person > } personWrapper = new ModelWrapper { @ code < > } ( ) ;
 * StringProperty wrappedNameProperty = personWrapper . field ( person - > person . getName ( ) , ( person , value )
 * - > person . setName ( value ) ) ;
 * / / or with a method reference
 * StringProperty wrappedNameProperty = personWrapper . field ( Person : : getName , Person : : setName ) ;
 * < / pre >
 * @ param getter
 * a function that returns the current value of the field for a given model element . Typically you will
 * use a method reference to the getter method of the model element .
 * @ param setter
 * a function that sets the given value to the given model element . Typically you will use a method
 * reference to the setter method of the model element .
 * @ return The wrapped property instance . */
public StringProperty field ( StringGetter < M > getter , StringSetter < M > setter ) { } }

implementation: return add ( new BeanPropertyField < > ( this :: propertyWasChanged , getter , setter , SimpleStringProperty :: new ) ) ;


signature:
public class ModelWrapper { /** * Add a new immutable field of type String to this instance of the wrapper . This method is used for immutable
 * model elements that have getters to get values for it ' s fields but not setters .
 * Instead , immutables have methods that take a new value for a field and return a new cloned instance of the
 * model element with only this field updated to the new value . The old model instance isn ' t changed .
 * Example :
 * < pre >
 * ModelWrapper { @ code < Person > } personWrapper = new ModelWrapper { @ code < > } ( ) ;
 * StringProperty wrappedNameProperty = personWrapper . field ( person - > person . getName ( ) , ( person , value )
 * Person clone = person . withName ( value ) ;
 * return clone ;
 * / / or with a method reference
 * StringProperty wrappedNameProperty = personWrapper . field ( Person : : getName , Person : : withName ) ;
 * < / pre >
 * @ param getter
 * a function that returns the current value of the field for a given model element . Typically you will
 * use a method reference to the getter method of the model element .
 * @ param immutableSetter
 * a function that returns a clone of this the given model element that has the given value set . Typically you will use a method
 * reference to the immutable setter method of the model element .
 * @ return The wrapped property instance . */
public StringProperty immutableField ( StringGetter < M > getter , StringImmutableSetter < M > immutableSetter ) { } }

implementation: return addImmutable ( new ImmutableBeanPropertyField < > ( this :: propertyWasChanged , getter , immutableSetter , SimpleStringProperty :: new ) ) ;


signature:
public class ModelWrapper { /** * Add a new field of type { @ link String } to this instance of the wrapper . This method is used for model elements
 * that are following the enhanced JavaFX - Beans - standard i . e . the model fields are available as JavaFX Properties .
 * Example :
 * < pre >
 * ModelWrapper { @ code < Person > } personWrapper = new ModelWrapper { @ code < > } ( ) ;
 * StringProperty wrappedNameProperty = personWrapper . field ( person - > person . nameProperty ( ) ) ;
 * / / or with a method reference
 * StringProperty wrappedNameProperty = personWrapper . field ( Person : : nameProperty ) ;
 * < / pre >
 * @ param accessor
 * a function that returns the property for a given model instance . Typically you will use a method
 * reference to the javafx - property accessor method .
 * @ return The wrapped property instance . */
public StringProperty field ( StringPropertyAccessor < M > accessor ) { } }

implementation: return add ( new FxPropertyField < > ( this :: propertyWasChanged , accessor , SimpleStringProperty :: new ) ) ;


signature:
public class ModelWrapper { /** * Add a new field of type String to this instance of the wrapper . See { @ link # field ( StringGetter , StringSetter ) } .
 * This method additionally takes a string identifier as first parameter .
 * This identifier is used to return the same property instance even when the method is invoked multiple times .
 * @ param identifier
 * an identifier for the field .
 * @ param getter
 * a function that returns the current value of the field for a given model element . Typically you will
 * use a method reference to the getter method of the model element .
 * @ param setter
 * a function that sets the given value to the given model element . Typically you will use a method
 * reference to the setter method of the model element .
 * @ return The wrapped property instance . */
public StringProperty field ( String identifier , StringGetter < M > getter , StringSetter < M > setter ) { } }

implementation: return addIdentified ( identifier , new BeanPropertyField < > ( this :: propertyWasChanged , getter , setter , ( ) -> new SimpleStringProperty ( null , identifier ) ) ) ;


signature:
public class ModelWrapper { /** * Add a new immutable field of type String to this instance of the wrapper . See { @ link # immutableField ( StringGetter , StringImmutableSetter } ) .
 * This method additionally takes a string identifier as first parameter .
 * This identifier is used to return the same property instance even when the method is invoked multiple times .
 * @ param identifier
 * an identifier for the field .
 * @ param getter
 * a function that returns the current value of the field for a given model element . Typically you will
 * use a method reference to the getter method of the model element .
 * @ param immutableSetter
 * a function that returns a clone of this the given model element that has the given value set . Typically you will use a method
 * reference to the immutable setter method of the model element .
 * @ return The wrapped property instance . */
public StringProperty immutableField ( String identifier , StringGetter < M > getter , StringImmutableSetter < M > immutableSetter ) { } }

implementation: return addIdentifiedImmutable ( identifier , new ImmutableBeanPropertyField < > ( this :: propertyWasChanged , getter , immutableSetter , ( ) -> new SimpleStringProperty ( null , identifier ) ) ) ;


signature:
public class ModelWrapper { /** * Add a new field of type String to this instance of the wrapper . See { @ link # field ( StringPropertyAccessor ) } . This
 * method additionally takes a string identifier as first parameter .
 * This identifier is used to return the same property instance even when the method is invoked multiple times .
 * @ param identifier
 * an identifier for the field .
 * @ param accessor
 * a function that returns the property for a given model instance . Typically you will use a method
 * reference to the javafx - property accessor method .
 * @ return The wrapped property instance . */
public StringProperty field ( String identifier , StringPropertyAccessor < M > accessor ) { } }

implementation: return addIdentified ( identifier , new FxPropertyField < > ( this :: propertyWasChanged , accessor , ( ) -> new SimpleStringProperty ( null , identifier ) ) ) ;


signature:
public class ModelWrapper { /** * / * Field type Boolean */
public BooleanProperty field ( BooleanGetter < M > getter , BooleanSetter < M > setter ) { } }

implementation: return add ( new BeanPropertyField < > ( this :: propertyWasChanged , getter , setter , SimpleBooleanProperty :: new ) ) ;


signature:
public class ModelWrapper { /** * / * Field type Double */
public DoubleProperty field ( DoubleGetter < M > getter , DoubleSetter < M > setter ) { } }

implementation: return add ( new BeanPropertyField < > ( this :: propertyWasChanged , getter :: apply , ( m , number ) -> setter . accept ( m , number . doubleValue ( ) ) , SimpleDoubleProperty :: new ) ) ;


signature:
public class ModelWrapper { /** * / * Field type Float */
public FloatProperty field ( FloatGetter < M > getter , FloatSetter < M > setter ) { } }

implementation: return add ( new BeanPropertyField < > ( this :: propertyWasChanged , getter :: apply , ( m , number ) -> setter . accept ( m , number . floatValue ( ) ) , SimpleFloatProperty :: new ) ) ;


signature:
public class ModelWrapper { /** * / * Field type Integer */
public IntegerProperty field ( IntGetter < M > getter , IntSetter < M > setter ) { } }

implementation: return add ( new BeanPropertyField < > ( this :: propertyWasChanged , getter :: apply , ( m , number ) -> setter . accept ( m , number . intValue ( ) ) , SimpleIntegerProperty :: new ) ) ;


signature:
public class ModelWrapper { /** * / * Field type Long */
public LongProperty field ( LongGetter < M > getter , LongSetter < M > setter ) { } }

implementation: return add ( new BeanPropertyField < > ( this :: propertyWasChanged , getter :: apply , ( m , number ) -> setter . accept ( m , number . longValue ( ) ) , SimpleLongProperty :: new ) ) ;


signature:
public class ModelWrapper { /** * / * Field type generic */
public < T > ObjectProperty < T > field ( ObjectGetter < M , T > getter , ObjectSetter < M , T > setter ) { } }

implementation: return add ( new BeanPropertyField < > ( this :: propertyWasChanged , getter , setter , SimpleObjectProperty :: new ) ) ;


signature:
public class ModelWrapper { /** * / * Field type list */
public < E > ListProperty < E > field ( ListGetter < M , E > getter , ListSetter < M , E > setter ) { } }

implementation: return add ( new BeanListPropertyField < > ( this :: propertyWasChanged , getter , ( m , list ) -> setter . accept ( m , FXCollections . observableArrayList ( list ) ) , SimpleListProperty :: new ) ) ;


signature:
public class ModelWrapper { /** * This helper method is needed because there is no equivalent of { @ link FXCollections # observableArrayList ( Collection ) }
 * for { @ link Set } .
 * The only factory method available for sets is { @ link FXCollections # observableSet ( Set ) } which creates an observable set
 * that is backed by the given set . However , this would mean that changes to the observable set are directly synchronized back to the
 * source set . In contrast to this { @ link FXCollections # observableArrayList ( Collection ) } creates an observable list that has
 * initially all values of the source list but changes aren ' t synchronized back because internally a new ArrayList is created .
 * We need exactly this behaviour for Sets and therefore are using this helper method . */
private static < T > ObservableSet < T > observableHashSet ( Set < T > source ) { } }

implementation: return FXCollections . observableSet ( new HashSet < > ( source ) ) ;


signature:
public class ModelWrapper { /** * / * Field type map */
public < K , V > MapProperty < K , V > field ( MapGetter < M , K , V > getter , MapSetter < M , K , V > setter ) { } }

implementation: return add ( new BeanMapPropertyField < > ( this :: propertyWasChanged , getter , ( m , map ) -> setter . accept ( m , FXCollections . observableMap ( map ) ) , SimpleMapProperty :: new ) ) ;


signature:
public class ObservableRuleBasedValidator { /** * Add a rule for this validator .
 * The rule defines a condition that has to be fulfilled .
 * A rule is defined by an observable boolean value . If the rule has a value of < code > true < / code > the rule is
 * " fulfilled " . If the rule has a value of < code > false < / code > the rule is violated . In this case the given message
 * object will be added to the status of this validator .
 * There are some predefined rules for common use cases in the { @ link ObservableRules } class that can be used .
 * @ param rule
 * @ param message */
public void addRule ( ObservableValue < Boolean > rule , ValidationMessage message ) { } }

implementation: booleanRules . add ( rule ) ; rule . addListener ( ( observable , oldValue , newValue ) -> { validateBooleanRule ( newValue , message ) ; } ) ; validateBooleanRule ( rule . getValue ( ) , message ) ;


signature:
public class ObservableRuleBasedValidator { /** * Add a complex rule for this validator .
 * The rule is defined by an { @ link ObservableValue } . If this observable contains a { @ link ValidationMessage }
 * object the rule is considered to be violated and the { @ link ValidationStatus } of this validator will contain
 * the validation message object contained in the observable value .
 * If the observable doesn ' t contain a value ( in other words it contains < code > null < / code > ) the rule is considered to
 * be fulfilled and the validation status of this validator will be valid ( given that no other rule is violated ) .
 * This method allows some more complex rules compared to { @ link # addRule ( ObservableValue , ValidationMessage ) } .
 * This way you can define rules that have different messages for specific cases .
 * @ param rule */
public void addRule ( ObservableValue < ValidationMessage > rule ) { } }

implementation: complexRules . add ( rule ) ; rule . addListener ( ( observable , oldValue , newValue ) -> { if ( oldValue != null ) { validationStatus . removeMessage ( oldValue ) ; } if ( newValue != null ) { validationStatus . addMessage ( newValue ) ; } } ) ; if ( rule . getValue ( ) != null ) { validationStatus . addMessage ( rule . getValue ( ) ) ; }


signature:
public class AddressFormViewModel { /** * Creates an observable list that always has
 * { @ link # NOTHING _ SELECTED _ MARKER } as first element and the values of the
 * given observable list . */
static ObservableList < String > createListWithNothingSelectedMarker ( ObservableList < String > source ) { } }

implementation:
final ObservableList < String > result = FXCollections . observableArrayList ( ) ; result . add ( NOTHING_SELECTED_MARKER ) ; result . addAll ( source ) ; // for sure there are better solutions for this but it ' s sufficient for our demo
source . addListener ( ( ListChangeListener < String > ) c -> { result . clear ( ) ; result . add ( NOTHING_SELECTED_MARKER ) ; result . addAll ( source ) ; } ) ; return result ;


signature:
public class FluentViewLoader { /** * This method is the entry point of the Fluent API to load a java based
 * view .
 * @ param viewType
 * the type of the view that should be loaded .
 * @ param < ViewType >
 * the type of the View that should be loaded . This type has to
 * implement { @ link de . saxsys . mvvmfx . JavaView } .
 * @ param < ViewModelType >
 * the type of the ViewModel . This type has to implement
 * { @ link de . saxsys . mvvmfx . ViewModel } .
 * @ return a builder step that can be further configured and then load the
 * actual view . */
public static < ViewType extends JavaView < ? extends ViewModelType > , ViewModelType extends ViewModel > JavaViewStep < ViewType , ViewModelType > javaView ( Class < ? extends ViewType > viewType ) { } }

implementation: return new JavaViewStep < > ( viewType ) ;


signature:
public class FluentViewLoader { /** * This method is the entry point of the Fluent API to load a fxml based
 * View .
 * @ param viewType
 * the type of the view that should be loaded .
 * @ param < ViewType >
 * the generic type of the View that should be loaded . This type
 * has to implement { @ link de . saxsys . mvvmfx . FxmlView } .
 * @ param < ViewModelType >
 * the generic type of the ViewModel . This type has to implement
 * { @ link de . saxsys . mvvmfx . ViewModel } .
 * @ return a builder step that can be further configured and then load the
 * actual view . */
public static < ViewType extends FxmlView < ? extends ViewModelType > , ViewModelType extends ViewModel > FxmlViewStep < ViewType , ViewModelType > fxmlView ( Class < ? extends ViewType > viewType ) { } }

implementation: return new FxmlViewStep < > ( viewType ) ;


signature:
public class ListenerManager { /** * Register the given { @ link ChangeListener } to the { @ link ObservableValue } . The listener is added to the observable
 * and will be added for management so it can be cleaned up with the { @ link # clean ( ) } method .
 * @ param observable
 * the observable that the listener is added to .
 * @ param listener
 * the listener that is registered .
 * @ param < T >
 * the generic type of the observable value . */
public < T > void register ( ObservableValue < T > observable , ChangeListener < ? super T > listener ) { } }

implementation: if ( ! simpleChangeListeners . containsKey ( observable ) ) { this . simpleChangeListeners . put ( observable , Collections . newSetFromMap ( new WeakHashMap < > ( ) ) ) ; } Set < ChangeListener > observers = this . simpleChangeListeners . get ( observable ) ; observers . add ( listener ) ; observable . addListener ( listener ) ;


signature:
public class ListenerManager { /** * Register the given { @ link ListChangeListener } to the { @ link ObservableList } . The listener is added to the
 * observable and will be added for management so it can be cleaned up with the { @ link # clean ( ) } method .
 * @ param observable
 * the observable list that the listener is added to .
 * @ param listener
 * the listener that is registered .
 * @ param < T >
 * the generic type of the observable list . */
public < T > void register ( ObservableList < T > observable , ListChangeListener < ? super T > listener ) { } }

implementation: if ( ! listChangeListeners . containsKey ( observable ) ) { this . listChangeListeners . put ( observable , Collections . newSetFromMap ( new WeakHashMap < > ( ) ) ) ; } Set < ListChangeListener > observers = this . listChangeListeners . get ( observable ) ; observers . add ( listener ) ; observable . addListener ( listener ) ;


signature:
public class ListenerManager { /** * Register the given { @ link InvalidationListener } to the { @ link Observable } . The listener is added to the
 * observable and will be added for management so it can be cleaned up with the { @ link # clean ( ) } method .
 * @ param observable
 * the observable that the listener is added to .
 * @ param listener
 * the listener that is registered . */
public void register ( Observable observable , InvalidationListener listener ) { } }

implementation: if ( ! invalidationListeners . containsKey ( observable ) ) { this . invalidationListeners . put ( observable , Collections . newSetFromMap ( new WeakHashMap < > ( ) ) ) ; } Set < InvalidationListener > observers = this . invalidationListeners . get ( observable ) ; observers . add ( listener ) ; observable . addListener ( listener ) ;


signature:
public class ListenerManager { /** * This method is used to clear the given map . To do this you need to implement a BiConsumer that calls the specific
 * method to remove a listener from an observable .
 * This needs to be done as there is no common interface with a remove method that all types of observables are
 * implementing . Therefore the method call to the specific removeListener method needs to be done in an extra
 * function .
 * @ param map
 * the multimap that contains the observables and listeners .
 * @ param consumer
 * a function that calls the specific remove method for the given types . */
private < T , U > void clearMap ( Map < T , Set < U > > map , BiConsumer < T , U > consumer ) { } }

implementation: for ( T observable : map . keySet ( ) ) { for ( U listener : map . get ( observable ) ) { consumer . accept ( observable , listener ) ; } } map . clear ( ) ;


signature:
public class MvvmfxCdiApplication { /** * This method is overridden to initialize the mvvmFX framework . Override the
 * { @ link # startMvvmfx ( javafx . stage . Stage ) } method for your application entry point and startup code instead of this
 * method . */
@ Override public final void start ( Stage primaryStage ) throws Exception { } }

implementation: producer . setPrimaryStage ( primaryStage ) ; startMvvmfx ( primaryStage ) ;


signature:
public class MvvmfxCdiApplication { /** * This method is called when the javafx application is initialized . See
 * { @ link javafx . application . Application # init ( ) } for more details .
 * Unlike the original init method in { @ link javafx . application . Application } this method contains logic to
 * initialize the CDI container . For this reason this method is now final to prevent unintended overriding .
 * * Please use { @ link # initMvvmfx ( ) } for you own initialization logic .
 * @ throws Exception */
@ SuppressWarnings ( "unchecked" ) @ Override public final void init ( ) throws Exception { } }

implementation: ctx = beanManager . createCreationalContext ( null ) ; injectionTarget = beanManager . createInjectionTarget ( beanManager . createAnnotatedType ( ( Class < MvvmfxCdiApplication > ) this . getClass ( ) ) ) ; injectionTarget . inject ( this , ctx ) ; injectionTarget . postConstruct ( this ) ; producer . setApplicationParameters ( getParameters ( ) ) ; initMvvmfx ( ) ;


signature:
public class MvvmfxCdiApplication { /** * This method is called when the application should stop . See { @ link javafx . application . Application # stop ( ) } for
 * more details .
 * Unlike the original stop method in { @ link javafx . application . Application } this method contains logic to release
 * resources managed by the CDI container . For this reason this method is now final to prevent unintended overriding .
 * * Please use { @ link # stopMvvmfx ( ) } ( ) } for you own initialization logic .
 * @ throws Exception */
@ Override public final void stop ( ) throws Exception { } }

implementation: stopMvvmfx ( ) ; injectionTarget . preDestroy ( this ) ; injectionTarget . dispose ( this ) ; ctx . release ( ) ; container . close ( ) ;


signature:
public class SelectableItemList { /** * When the selected item changed we want to set the index property too */
private void createIndexEvents ( ) { } }

implementation:
selectionModel . selectedIndexProperty ( ) . addListener ( ( bean , oldVal , newVal ) -> { int index = newVal . intValue ( ) ; ListType item = index == - 1 ? null : modelListProperty ( ) . get ( index ) ; selectedItem . set ( item ) ; } ) ; selectedItem . addListener ( ( observable , oldVal , newVal ) -> { // Item null
if ( newVal == null ) { selectionModel . select ( - 1 ) ; selectedItem . set ( null ) ; } else { int index = modelListProperty ( ) . get ( ) . indexOf ( newVal ) ; // Item not found
if ( index != - 1 ) { selectionModel . select ( index ) ; } else { // If item not found - Rollback
selectedItem . set ( oldVal ) ; } } } ) ;


signature:
public class ReflectionUtils { /** * Returns all fields with the given annotation . Only fields that are declared in the actual class of the instance
 * are considered ( i . e . no fields from super classes ) . This includes private fields .
 * @ param target
 * the instance that ' s class is used to find annotations .
 * @ param annotationType
 * the type of the annotation that is searched for .
 * @ return a List of Fields that are annotated with the given annotation . */
public static List < Field > getFieldsWithAnnotation ( Object target , Class < ? extends Annotation > annotationType ) { } }

implementation: return ReflectionUtils . getFieldsFromClassHierarchy ( target . getClass ( ) ) . stream ( ) . filter ( field -> field . isAnnotationPresent ( annotationType ) ) . collect ( Collectors . toList ( ) ) ;


signature:
public class ReflectionUtils { /** * Returns all fields of the given type and all parent types ( except Object ) .
 * < br >
 * The difference to { @ link Class # getFields ( ) } is that getFields only returns public fields while this method will
 * return all fields whatever the access modifier is .
 * < br >
 * The difference to { @ link Class # getDeclaredFields ( ) } is that getDeclaredFields returns all fields ( with all
 * modifiers ) from the given class but not from super classes . This method instead will return all fields of all
 * modifiers from all super classes up in the class hierarchy , except from Object itself .
 * @ param type the type whose fields will be searched .
 * @ return a list of field instances . */
public static List < Field > getFieldsFromClassHierarchy ( Class < ? > type ) { } }

implementation: final List < Field > classFields = new ArrayList < > ( ) ; classFields . addAll ( Arrays . asList ( type . getDeclaredFields ( ) ) ) ; final Class < ? > parentClass = type . getSuperclass ( ) ; if ( parentClass != null && ! ( parentClass . equals ( Object . class ) ) ) { List < Field > parentClassFields = getFieldsFromClassHierarchy ( parentClass ) ; classFields . addAll ( parentClassFields ) ; } return classFields ;


signature:
public class ReflectionUtils { /** * Helper method to execute a callback on a given member . This method encapsulates the error handling logic and the
 * handling of accessibility of the member .
 * After the callback is executed the accessibility of the member will be reset to the originally state .
 * @ param member
 * the member that is made accessible to run the callback
 * @ param callable
 * the callback that will be executed .
 * @ param errorMessage
 * the error message that is used in the exception when something went wrong .
 * @ return the return value of the given callback .
 * @ throws IllegalStateException
 * when something went wrong . */
public static < T > T accessMember ( final AccessibleObject member , final Callable < T > callable , String errorMessage ) { } }

implementation: if ( callable == null ) { return null ; } return AccessController . doPrivileged ( ( PrivilegedAction < T > ) ( ) -> { boolean wasAccessible = member . isAccessible ( ) ; try { member . setAccessible ( true ) ; return callable . call ( ) ; } catch ( Exception exception ) { throw new IllegalStateException ( errorMessage , exception ) ; } finally { member . setAccessible ( wasAccessible ) ; } } ) ;


signature:
public class ReflectionUtils { /** * This method can be used to set ( private / public ) fields to a given value by reflection . Handling of accessibility
 * and errors is encapsulated .
 * @ param field
 * the field that ' s value should be set .
 * @ param target
 * the instance of which the field will be set .
 * @ param value
 * the new value that the field should be set to . */
public static void setField ( final Field field , Object target , Object value ) { } }

implementation: accessMember ( field , ( ) -> field . set ( target , value ) , "Cannot set the field [" + field . getName ( ) + "] of instance [" + target + "] to value [" + value + "]" ) ;