idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
36,700
protected static Map < String , String > initializeSystemProperties ( final String [ ] args ) { final Map < String , String > result = new HashMap < > ( ) ; final Pattern pattern = Pattern . compile ( "-D(.+)=(.+)" ) ; for ( final String arg : args ) { final Matcher matcher = pattern . matcher ( arg ) ; if ( matcher . matches ( ) ) { final String key = matcher . group ( 1 ) ; final String value = matcher . group ( 2 ) ; result . put ( key , value ) ; System . setProperty ( key , value ) ; } } return result ; }
Initializes system properties based on the arguments passed
36,701
protected static boolean initializeLogging ( ) { try { { final URL url = Main . class . getResource ( "log4j-initial.xml" ) ; assert url != null ; DOMConfigurator . configure ( url ) ; } if ( ClassLoaderUtils . IS_WEB_START ) { final URL url = Main . class . getResource ( "log4j-jnlp.xml" ) ; assert url != null ; println ( "Using JNLP log configuration: " + url ) ; DOMConfigurator . configure ( url ) ; return true ; } final File dataCleanerHome = DataCleanerHome . getAsFile ( ) ; if ( initializeLoggingFromDirectory ( dataCleanerHome ) ) { return true ; } if ( initializeLoggingFromDirectory ( new File ( "." ) ) ) { return true ; } final URL url = Main . class . getResource ( "log4j-default.xml" ) ; assert url != null ; println ( "Using default log configuration: " + url ) ; DOMConfigurator . configure ( url ) ; return false ; } catch ( final NoClassDefFoundError e ) { println ( "Failed to initialize logging, class not found: " + e . getMessage ( ) ) ; return false ; } }
Initializes logging specifically by looking for log4j . xml or log4j . properties file in DataCleaner s home directory .
36,702
public Packer setContainer ( final Container cont ) throws IllegalAccessException { if ( container != null ) { final Packer p = ( Packer ) clone ( ) ; container . setLayout ( p ) ; } container = cont ; cont . setLayout ( this ) ; return this ; }
Set the designated container for objects packed by this instance .
36,703
public Packer pack ( final Component cp ) { if ( container != null ) { container . add ( cp ) ; } comp = cp ; gc = new GridBagConstraints ( ) ; setConstraints ( comp , gc ) ; return this ; }
Establishes a new set of constraints to layout the widget passed . The created constraints are applied to the passed Component and if a Container is known to this object the component is added to the known container .
36,704
public Packer setAnchorNorth ( final boolean how ) { if ( how == true ) { gc . anchor = GridBagConstraints . NORTH ; } else { gc . anchor &= ~ GridBagConstraints . NORTH ; } setConstraints ( comp , gc ) ; return this ; }
Add anchor = NORTH to the constraints for the current component if how == true remove it if false .
36,705
public Packer setAnchorSouth ( final boolean how ) { if ( how == true ) { gc . anchor = GridBagConstraints . SOUTH ; } else { gc . anchor &= ~ GridBagConstraints . SOUTH ; } setConstraints ( comp , gc ) ; return this ; }
Add anchor = SOUTH to the constraints for the current component if how == true remove it if false .
36,706
public Packer setAnchorEast ( final boolean how ) { if ( how == true ) { gc . anchor = GridBagConstraints . EAST ; } else { gc . anchor &= ~ GridBagConstraints . EAST ; } setConstraints ( comp , gc ) ; return this ; }
Add anchor = EAST to the constraints for the current component if how == true remove it if false .
36,707
public Packer setAnchorWest ( final boolean how ) { if ( how == true ) { gc . anchor = GridBagConstraints . WEST ; } else { gc . anchor &= ~ GridBagConstraints . WEST ; } setConstraints ( comp , gc ) ; return this ; }
Add anchor = WEST to the constraints for the current component if how == true remove it if false .
36,708
public Packer setAnchorNorthWest ( final boolean how ) { if ( how == true ) { gc . anchor = GridBagConstraints . NORTHWEST ; } else { gc . anchor &= ~ GridBagConstraints . NORTHWEST ; } setConstraints ( comp , gc ) ; return this ; }
Add anchor = NORTHWEST to the constraints for the current component if how == true remove it if false .
36,709
public Packer setAnchorSouthWest ( final boolean how ) { if ( how == true ) { gc . anchor = GridBagConstraints . SOUTHWEST ; } else { gc . anchor &= ~ GridBagConstraints . SOUTHWEST ; } setConstraints ( comp , gc ) ; return this ; }
Add anchor = SOUTHWEST to the constraints for the current component if how == true remove it if false .
36,710
public Packer setAnchorNorthEast ( final boolean how ) { if ( how == true ) { gc . anchor = GridBagConstraints . NORTHEAST ; } else { gc . anchor &= ~ GridBagConstraints . NORTHEAST ; } setConstraints ( comp , gc ) ; return this ; }
Add anchor = NORTHEAST to the constraints for the current component if how == true remove it if false .
36,711
public Packer setAnchorSouthEast ( final boolean how ) { if ( how == true ) { gc . anchor = GridBagConstraints . SOUTHEAST ; } else { gc . anchor &= ~ GridBagConstraints . SOUTHEAST ; } setConstraints ( comp , gc ) ; return this ; }
Add anchor = SOUTHEAST to the constraints for the current component if how == true remove it if false .
36,712
public Packer setXLeftRelative ( final boolean how ) { if ( how == true ) { gc . gridx = GridBagConstraints . RELATIVE ; } else { gc . gridx = 0 ; } setConstraints ( comp , gc ) ; return this ; }
Add gridx = RELATIVE to the constraints for the current component if how == true 0 it if false .
36,713
public Packer setYTopRelative ( final boolean how ) { if ( how == true ) { gc . gridy = GridBagConstraints . RELATIVE ; } else { gc . gridy = 0 ; } setConstraints ( comp , gc ) ; return this ; }
Add gridy = RELATIVE to the constraints for the current component if how == true 0 it if false .
36,714
public Packer setFillX ( final boolean how ) { if ( how == true ) { gc . fill = GridBagConstraints . HORIZONTAL ; gc . weightx = 1 ; } else { gc . weightx = 0 ; gc . fill = 0 ; } setConstraints ( comp , gc ) ; return this ; }
Add fill = HORIZONTAL weightx = 1 to the constraints for the current component if how == true . fill = 0 weightx = 0 if how is false .
36,715
public Packer fillx ( final double wtx ) { gc . fill = GridBagConstraints . HORIZONTAL ; gc . weightx = wtx ; setConstraints ( comp , gc ) ; return this ; }
Add fill = HORIZONTAL weightx = wtx to the constraints for the current component .
36,716
public Packer setFillY ( final boolean how ) { if ( how == true ) { gc . fill = GridBagConstraints . VERTICAL ; gc . weighty = 1 ; } else { gc . weighty = 0 ; gc . fill = 0 ; } setConstraints ( comp , gc ) ; return this ; }
Add fill = VERITCAL to the constraints for the current component if how == true 1 it if false .
36,717
public Packer filly ( final double wty ) { gc . fill = GridBagConstraints . VERTICAL ; gc . weighty = wty ; setConstraints ( comp , gc ) ; return this ; }
Add fill = VERTICAL weighty = wty to the constraints for the current component .
36,718
public Packer setFillBoth ( final boolean how ) { if ( how == true ) { gc . fill = GridBagConstraints . BOTH ; gc . weightx = 1 ; gc . weighty = 1 ; } else { gc . weightx = 0 ; gc . weighty = 0 ; gc . fill = 0 ; } setConstraints ( comp , gc ) ; return this ; }
Add fill = BOTH weightx = 1 weighty = 1 to the constraints for the current component if how == true fill = 0 weightx = 0 weighty = 0 if it is false .
36,719
public Packer fillboth ( final double wtx , final double wty ) { gc . fill = GridBagConstraints . BOTH ; gc . weightx = wtx ; gc . weighty = wty ; setConstraints ( comp , gc ) ; return this ; }
Add fill = BOTH weighty = 1 weightx = 1 to the constraints for the current component .
36,720
public Packer setInsetTop ( final int val ) { Insets i = gc . insets ; if ( i == null ) { i = new Insets ( 0 , 0 , 0 , 0 ) ; } gc . insets = new Insets ( val , i . left , i . bottom , i . right ) ; setConstraints ( comp , gc ) ; return this ; }
sets top Insets on the constraints for the current component to the value specified .
36,721
public Packer setInsetBottom ( final int val ) { Insets i = gc . insets ; if ( i == null ) { i = new Insets ( 0 , 0 , 0 , 0 ) ; } gc . insets = new Insets ( i . top , i . left , val , i . right ) ; setConstraints ( comp , gc ) ; return this ; }
sets bottom Insets on the constraints for the current component to the value specified .
36,722
public Packer setInsetLeft ( final int val ) { Insets i = gc . insets ; if ( i == null ) { i = new Insets ( 0 , 0 , 0 , 0 ) ; } gc . insets = new Insets ( i . top , val , i . bottom , i . right ) ; setConstraints ( comp , gc ) ; return this ; }
sets left Insets on the constraints for the current component to the value specified .
36,723
public Packer setInsetRight ( final int val ) { Insets i = gc . insets ; if ( i == null ) { i = new Insets ( 0 , 0 , 0 , 0 ) ; } gc . insets = new Insets ( i . top , i . left , i . bottom , val ) ; setConstraints ( comp , gc ) ; return this ; }
sets right Insets on the constraints for the current component to the value specified .
36,724
public static void removeSshCertificateChecks ( final HttpClient httpClient ) throws IllegalStateException { try { final SSLContext sslContext = SSLContext . getInstance ( "SSL" ) ; final TrustManager trustManager = new NaiveTrustManager ( ) ; sslContext . init ( null , new TrustManager [ ] { trustManager } , new SecureRandom ( ) ) ; final org . apache . http . conn . ssl . SSLSocketFactory schemeSocketFactory = new org . apache . http . conn . ssl . SSLSocketFactory ( sslContext ) ; final org . apache . http . conn . scheme . Scheme sslScheme = new org . apache . http . conn . scheme . Scheme ( "https" , 443 , schemeSocketFactory ) ; final org . apache . http . conn . scheme . SchemeRegistry registry = httpClient . getConnectionManager ( ) . getSchemeRegistry ( ) ; registry . register ( sslScheme ) ; } catch ( final Exception e ) { throw new IllegalStateException ( e ) ; } }
Removes the certificate checks of HTTPS traffic on a HTTP client . Use with caution!
36,725
public AnalyzerJob getAnalyzerJob ( final String descriptorName , final String analyzerName , final String analyzerInputName ) { List < AnalyzerJob > candidates = new ArrayList < > ( _jobs ) ; candidates = CollectionUtils2 . refineCandidates ( candidates , o -> { final String actualDescriptorName = o . getDescriptor ( ) . getDisplayName ( ) ; return descriptorName . equals ( actualDescriptorName ) ; } ) ; if ( analyzerName != null ) { candidates = CollectionUtils2 . refineCandidates ( candidates , o -> { final String actualAnalyzerName = o . getName ( ) ; return analyzerName . equals ( actualAnalyzerName ) ; } ) ; } if ( analyzerInputName != null ) { candidates = CollectionUtils2 . refineCandidates ( candidates , o -> { final InputColumn < ? > inputColumn = getIdentifyingInputColumn ( o ) ; if ( inputColumn == null ) { return false ; } return analyzerInputName . equals ( inputColumn . getName ( ) ) ; } ) ; } if ( candidates . isEmpty ( ) ) { logger . error ( "No more AnalyzerJob candidates to choose from" ) ; return null ; } else if ( candidates . size ( ) > 1 ) { logger . warn ( "Multiple ({}) AnalyzerJob candidates to choose from, picking first" ) ; } return candidates . iterator ( ) . next ( ) ; }
Gets the best candidate analyzer job based on search criteria offered in parameters .
36,726
public static boolean isSingleWord ( String value ) { if ( value == null ) { return false ; } value = value . trim ( ) ; if ( value . isEmpty ( ) ) { return false ; } return ! SINGLE_WORD_PATTERN . matcher ( value ) . matches ( ) ; }
Determines if a String represents a single word . A single word is defined as a non - null string containing no word boundaries after trimming .
36,727
public void autoMap ( final Datastore datastore ) { setDatastore ( datastore ) ; try ( DatastoreConnection con = datastore . openConnection ( ) ) { final SchemaNavigator schemaNavigator = con . getSchemaNavigator ( ) ; for ( final Entry < String , Column > entry : _map . entrySet ( ) ) { if ( entry . getValue ( ) == null ) { final String path = entry . getKey ( ) ; final Column column = schemaNavigator . convertToColumn ( path ) ; entry . setValue ( column ) ; } } } }
Automatically maps all unmapped paths by looking them up in a datastore .
36,728
public boolean endLink ( final Object endVertex , final MouseEvent mouseEvent ) { logger . debug ( "endLink({})" , endVertex ) ; boolean result = false ; if ( _startVertex != null && endVertex != null ) { if ( mouseEvent . getButton ( ) == MouseEvent . BUTTON1 ) { final boolean created = createLink ( _startVertex , endVertex , mouseEvent ) ; if ( created && _graphContext . getVisualizationViewer ( ) . isVisible ( ) ) { _graphContext . getJobGraph ( ) . refresh ( ) ; } result = true ; } } stopDrawing ( ) ; return result ; }
If startVertex is non - null this method will attempt to end the link - painting at the given endVertex
36,729
private boolean scopeUpdatePermitted ( final AnalysisJobBuilder sourceAnalysisJobBuilder , final ComponentBuilder componentBuilder ) { if ( sourceAnalysisJobBuilder != componentBuilder . getAnalysisJobBuilder ( ) ) { if ( componentBuilder . getInput ( ) . length > 0 || componentBuilder . getComponentRequirement ( ) != null ) { final String scopeText ; scopeText = LabelUtils . getScopeLabel ( sourceAnalysisJobBuilder ) ; final int response = JOptionPane . showConfirmDialog ( _graphContext . getVisualizationViewer ( ) , "This will move " + LabelUtils . getLabel ( componentBuilder ) + " into the " + scopeText + ", thereby losing its configured columns and/or requirements" , "Change scope?" , JOptionPane . OK_CANCEL_OPTION , JOptionPane . WARNING_MESSAGE ) ; if ( response == JOptionPane . CANCEL_OPTION ) { _graphContext . getJobGraph ( ) . refresh ( ) ; return false ; } } } return true ; }
This will check if components are in a different scope and ask the user for permission to change the scope of the target component
36,730
public static Color colorBetween ( final Color c1 , final Color c2 ) { final int red = ( c1 . getRed ( ) + c2 . getRed ( ) ) / 2 ; final int green = ( c1 . getGreen ( ) + c2 . getGreen ( ) ) / 2 ; final int blue = ( c1 . getBlue ( ) + c2 . getBlue ( ) ) / 2 ; return new Color ( red , green , blue ) ; }
Creates a color that is in between two colors in terms of RGB balance .
36,731
public static DCPanel decorateWithShadow ( final JComponent comp , final boolean outline , final int margin ) { final DCPanel panel = new DCPanel ( ) ; panel . setLayout ( new BorderLayout ( ) ) ; Border border = BORDER_SHADOW ; if ( outline ) { border = new CompoundBorder ( border , BORDER_THIN ) ; } if ( margin > 0 ) { border = new CompoundBorder ( new EmptyBorder ( margin , margin , margin , margin ) , border ) ; } panel . setBorder ( border ) ; panel . add ( comp , BorderLayout . CENTER ) ; return panel ; }
Decorates a JComponent with a nice shadow border . Since not all JComponents handle opacity correctly they will be wrapped inside a DCPanel which actually has the border .
36,732
public static Font findCompatibleFont ( final String text , final Font fallbackFont ) { final String [ ] searchFonts = new String [ ] { Font . SANS_SERIF , Font . SERIF , "Verdana" , "Arial Unicode MS" , "MS UI Gothic" , "MS Mincho" , "MS Gothic" , "Osaka" } ; for ( final String fontName : searchFonts ) { Font font = fonts . get ( fontName ) ; if ( font == null ) { font = new Font ( fontName , fallbackFont . getStyle ( ) , fallbackFont . getSize ( ) ) ; } if ( font . canDisplayUpTo ( text ) == - 1 ) { logger . info ( "Font '{}' was capable, returning" , fontName ) ; font = font . deriveFont ( fallbackFont . getSize2D ( ) ) ; return font ; } } logger . warn ( "Didn't find any capable fonts for text '{}'" , text ) ; return fallbackFont ; }
Finds a font that is capable of displaying the provided text .
36,733
private InputColumn < ? > findOrderByColumn ( final AnalysisJobBuilder jobBuilder ) { final Table sourceTable = jobBuilder . getSourceTables ( ) . get ( 0 ) ; final List < Column > primaryKeys = sourceTable . getPrimaryKeys ( ) ; if ( primaryKeys . size ( ) == 1 ) { final Column primaryKey = primaryKeys . get ( 0 ) ; final InputColumn < ? > sourceColumn = jobBuilder . getSourceColumnByName ( primaryKey . getName ( ) ) ; if ( sourceColumn == null ) { jobBuilder . addSourceColumn ( primaryKey ) ; logger . info ( "Added PK source column for ORDER BY clause on slave jobs: {}" , sourceColumn ) ; return jobBuilder . getSourceColumnByName ( primaryKey . getName ( ) ) ; } else { logger . info ( "Using existing PK source column for ORDER BY clause on slave jobs: {}" , sourceColumn ) ; return sourceColumn ; } } else { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Found {} primary keys, cannot select a single for ORDER BY clause on slave jobs: {}" , primaryKeys . size ( ) , primaryKeys . size ( ) ) ; } } final List < MetaModelInputColumn > sourceColumns = jobBuilder . getSourceColumns ( ) ; final String tableName = sourceTable . getName ( ) . toLowerCase ( ) ; for ( final MetaModelInputColumn sourceColumn : sourceColumns ) { String name = sourceColumn . getName ( ) ; if ( name != null ) { name = StringUtils . replaceWhitespaces ( name , "" ) ; name = StringUtils . replaceAll ( name , "_" , "" ) ; name = StringUtils . replaceAll ( name , "-" , "" ) ; name = name . toLowerCase ( ) ; if ( "id" . equals ( name ) || ( tableName + "id" ) . equals ( name ) || ( tableName + "number" ) . equals ( name ) || ( tableName + "key" ) . equals ( name ) ) { logger . info ( "Using existing source column for ORDER BY clause on slave jobs: {}" , sourceColumn ) ; return sourceColumn ; } } } final MetaModelInputColumn sourceColumn = sourceColumns . get ( 0 ) ; logger . warn ( "Couldn't pick a good source column for ORDER BY clause on slave jobs. Picking the first column: {}" , sourceColumn ) ; return sourceColumn ; }
Finds a source column which is appropriate for an ORDER BY clause in the generated paginated queries
36,734
protected String getCellValue ( final HtmlRenderingContext context , final int row , final int col , final Object value ) { final String stringValue = LabelUtils . getValueLabel ( value ) ; return context . escapeHtml ( stringValue ) ; }
Overrideable method for defining a cell s literal HTML value in the table
36,735
public Injector openAnalysisJob ( final FileObject file ) { final JaxbJobReader reader = new JaxbJobReader ( _configuration ) ; try { final AnalysisJobBuilder ajb = reader . create ( file ) ; return openAnalysisJob ( file , ajb ) ; } catch ( final NoSuchComponentException e ) { final String message ; if ( Version . EDITION_COMMUNITY . equals ( Version . getEdition ( ) ) ) { message = "<html><p>Failed to open job because of a missing component:</p><pre>" + e . getMessage ( ) + "</pre><p>This may happen if the job requires a " + "<a href=\"https://www.quadient.com/products/quadient-datacleaner#get-started-today\">" + "Commercial Edition of DataCleaner</a>, or an extension that you do not have installed.</p>" + "</html>" ; } else { message = "<html>Failed to open job because of a missing component: " + e . getMessage ( ) + "<br/><br/>" + "This may happen if the job requires an extension that you do not have installed.</html>" ; } WidgetUtils . showErrorMessage ( "Cannot open job" , message ) ; return null ; } catch ( final NoSuchDatastoreException e ) { if ( _windowContext == null ) { throw e ; } final AnalysisJobMetadata metadata = reader . readMetadata ( file ) ; final int result = JOptionPane . showConfirmDialog ( null , e . getMessage ( ) + "\n\nDo you wish to open this job as a template?" , "Error: " + e . getMessage ( ) , JOptionPane . OK_CANCEL_OPTION , JOptionPane . ERROR_MESSAGE ) ; if ( result == JOptionPane . OK_OPTION ) { final OpenAnalysisJobAsTemplateDialog dialog = new OpenAnalysisJobAsTemplateDialog ( _windowContext , _configuration , file , metadata , Providers . of ( this ) ) ; dialog . setVisible ( true ) ; } return null ; } catch ( final ComponentConfigurationException e ) { final String message ; final Throwable cause = e . getCause ( ) ; if ( cause != null ) { if ( ! Strings . isNullOrEmpty ( cause . getMessage ( ) ) ) { message = cause . getMessage ( ) ; } else { message = e . getMessage ( ) ; } } else { message = e . getMessage ( ) ; } WidgetUtils . showErrorMessage ( "Failed to validate job configuration" , message , e ) ; return null ; } catch ( final RuntimeException e ) { logger . error ( "Unexpected failure when opening job: {}" , file , e ) ; throw e ; } }
Opens a job file
36,736
public Injector openAnalysisJob ( final FileObject fileObject , final AnalysisJobBuilder ajb ) { final File file = VFSUtils . toFile ( fileObject ) ; if ( file != null ) { _userPreferences . setAnalysisJobDirectory ( file . getParentFile ( ) ) ; _userPreferences . addRecentJobFile ( fileObject ) ; } return Guice . createInjector ( new DCModuleImpl ( _parentModule , ajb ) { public FileObject getJobFilename ( ) { return fileObject ; } } ) ; }
Opens a job builder
36,737
public static FileSystemManager getFileSystemManager ( ) { try { final FileSystemManager manager = VFS . getManager ( ) ; if ( manager . getBaseFile ( ) == null ) { ( ( DefaultFileSystemManager ) manager ) . setBaseFile ( new File ( "." ) ) ; } return manager ; } catch ( final FileSystemException e ) { throw new IllegalStateException ( e ) ; } }
Gets the file system manager to use in typical scenarios .
36,738
private < E > E createCustomElement ( final CustomElementType customElementType , final Class < E > expectedClazz , final DataCleanerConfiguration configuration , final boolean initialize ) { final InjectionManager injectionManager = configuration . getEnvironment ( ) . getInjectionManagerFactory ( ) . getInjectionManager ( configuration ) ; return createCustomElementInternal ( customElementType , expectedClazz , injectionManager , initialize ) ; }
Creates a custom component based on an element which specified just a class name and an optional set of properties .
36,739
public static Object [ ] collapse ( String aString , int anInt ) { return new Object [ ] { aString , Integer . valueOf ( anInt ) } ; }
Collapse a String and int into an array
36,740
public Method createJavaMethod ( ) { Class < ? > clazz = rtype . getClazz ( ) ; String name = methodMember . getName ( ) ; String methodDescriptor = methodMember . getDescriptor ( ) ; ClassLoader classLoader = rtype . getTypeRegistry ( ) . getClassLoader ( ) ; try { Class < ? > [ ] params = Utils . toParamClasses ( methodDescriptor , classLoader ) ; Class < ? > returnType = Utils . toClass ( Type . getReturnType ( methodDescriptor ) , classLoader ) ; Class < ? > [ ] exceptions = Utils . slashedNamesToClasses ( methodMember . getExceptions ( ) , classLoader ) ; return JVM . newMethod ( clazz , name , params , returnType , exceptions , methodMember . getModifiers ( ) , methodMember . getGenericSignature ( ) ) ; } catch ( ClassNotFoundException e ) { throw new IllegalStateException ( "Couldn't create j.l.r.Method for " + clazz . getName ( ) + "." + methodDescriptor , e ) ; } }
Create a mock Java Method which is dependent on ReflectiveInterceptor to catch calls to invoke .
36,741
public void setValue ( ReloadableType rtype , Object instance , Object value , String name ) throws IllegalAccessException { FieldMember fieldmember = rtype . findInstanceField ( name ) ; if ( fieldmember == null ) { FieldReaderWriter frw = rtype . locateField ( name ) ; if ( frw == null ) { log . info ( "Unexpectedly unable to locate instance field " + name + " starting from type " + rtype . dottedtypename + ": clinit running late?" ) ; return ; } frw . setValue ( instance , value , this ) ; } else { if ( fieldmember . isStatic ( ) ) { throw new IncompatibleClassChangeError ( "Expected non-static field " + rtype . dottedtypename + "." + fieldmember . getName ( ) ) ; } Map < String , Object > typeValues = values . get ( fieldmember . getDeclaringTypeName ( ) ) ; if ( typeValues == null ) { typeValues = new HashMap < String , Object > ( ) ; values . put ( fieldmember . getDeclaringTypeName ( ) , typeValues ) ; } typeValues . put ( name , value ) ; } }
Set the value of a field .
36,742
private void collectAll ( MethodProvider methodProvider , Map < String , Invoker > found ) { MethodProvider [ ] itfs = methodProvider . getInterfaces ( ) ; for ( int i = itfs . length - 1 ; i >= 0 ; i -- ) { collectAll ( itfs [ i ] , found ) ; } MethodProvider supr = methodProvider . getSuper ( ) ; if ( supr != null && ! methodProvider . isInterface ( ) ) { collectAll ( supr , found ) ; } for ( Invoker method : methodProvider . getDeclaredMethods ( ) ) { if ( Modifier . isPublic ( method . getModifiers ( ) ) ) { found . put ( method . getName ( ) + method . getMethodDescriptor ( ) , method ) ; } } }
Collect all public methods from methodProvider and its supertypes into the found hasmap indexed by name + descriptor .
36,743
public static void generateJLObjectStream_hasStaticInitializer ( ClassWriter cw , String classname ) { FieldVisitor fv = cw . visitField ( ACC_PUBLIC + ACC_STATIC , jloObjectStream_hasInitializerMethod , "Ljava/lang/reflect/Method;" , null , null ) ; fv . visitEnd ( ) ; MethodVisitor mv = cw . visitMethod ( ACC_PRIVATE + ACC_STATIC , jloObjectStream_hasInitializerMethod , "(Ljava/lang/Class;)Z" , null , null ) ; mv . visitCode ( ) ; Label l0 = new Label ( ) ; Label l1 = new Label ( ) ; Label l2 = new Label ( ) ; mv . visitTryCatchBlock ( l0 , l1 , l2 , "java/lang/Exception" ) ; mv . visitLabel ( l0 ) ; mv . visitFieldInsn ( GETSTATIC , classname , jloObjectStream_hasInitializerMethod , "Ljava/lang/reflect/Method;" ) ; mv . visitInsn ( ACONST_NULL ) ; mv . visitInsn ( ICONST_1 ) ; mv . visitTypeInsn ( ANEWARRAY , "java/lang/Object" ) ; mv . visitInsn ( DUP ) ; mv . visitInsn ( ICONST_0 ) ; mv . visitVarInsn ( ALOAD , 0 ) ; mv . visitInsn ( AASTORE ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , "java/lang/reflect/Method" , "invoke" , "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;" , false ) ; mv . visitTypeInsn ( CHECKCAST , "java/lang/Boolean" ) ; mv . visitMethodInsn ( INVOKEVIRTUAL , "java/lang/Boolean" , "booleanValue" , "()Z" , false ) ; mv . visitLabel ( l1 ) ; mv . visitInsn ( IRETURN ) ; mv . visitLabel ( l2 ) ; mv . visitVarInsn ( ASTORE , 1 ) ; mv . visitVarInsn ( ALOAD , 0 ) ; mv . visitMethodInsn ( INVOKESTATIC , classname , "hasStaticInitializer" , "(Ljava/lang/Class;)Z" ) ; mv . visitInsn ( IRETURN ) ; mv . visitMaxs ( 3 , 1 ) ; mv . visitEnd ( ) ; }
Create a method that can be used to intercept the calls to hasStaticInitializer made in the ObjectStreamClass . The method will ask SpringLoaded whether the type has a static initializer . SpringLoaded will be able to answer if it is a reloadable type . If it is not a reloadable type then springloaded will throw an exception which will be caught here and the regular call to hasStaticInitializer will be made .
36,744
@ SuppressWarnings ( "unused" ) private static void checkNotTheSame ( byte [ ] bs , byte [ ] bytes ) { if ( bs . length == bytes . length ) { System . out . println ( "same length!" ) ; boolean same = true ; for ( int i = 0 ; i < bs . length ; i ++ ) { if ( bs [ i ] != bytes [ i ] ) { same = false ; break ; } } if ( same ) { System . out . println ( "same data!!" ) ; } else { System . out . println ( "diff data" ) ; } } else { System . out . println ( "different" ) ; } }
method useful when debugging
36,745
private void ensurePreparedForInjection ( ) { if ( ! prepared ) { try { Class < ReflectiveInterceptor > clazz = ReflectiveInterceptor . class ; method_jlcgdfs = clazz . getDeclaredMethod ( "jlClassGetDeclaredFields" , Class . class ) ; method_jlcgdf = clazz . getDeclaredMethod ( "jlClassGetDeclaredField" , Class . class , String . class ) ; method_jlcgf = clazz . getDeclaredMethod ( "jlClassGetField" , Class . class , String . class ) ; method_jlcgdms = clazz . getDeclaredMethod ( "jlClassGetDeclaredMethods" , Class . class ) ; method_jlcgdm = clazz . getDeclaredMethod ( "jlClassGetDeclaredMethod" , Class . class , String . class , EMPTY_CLASS_ARRAY_CLAZZ ) ; method_jlcgm = clazz . getDeclaredMethod ( "jlClassGetMethod" , Class . class , String . class , EMPTY_CLASS_ARRAY_CLAZZ ) ; method_jlcgdc = clazz . getDeclaredMethod ( "jlClassGetDeclaredConstructor" , Class . class , EMPTY_CLASS_ARRAY_CLAZZ ) ; method_jlcgc = clazz . getDeclaredMethod ( "jlClassGetConstructor" , Class . class , EMPTY_CLASS_ARRAY_CLAZZ ) ; method_jlcgmods = clazz . getDeclaredMethod ( "jlClassGetModifiers" , Class . class ) ; method_jlcgms = clazz . getDeclaredMethod ( "jlClassGetMethods" , Class . class ) ; method_jlcgdcs = clazz . getDeclaredMethod ( "jlClassGetDeclaredConstructors" , Class . class ) ; method_jlrfg = clazz . getDeclaredMethod ( "jlrFieldGet" , Field . class , Object . class ) ; method_jlrfgl = clazz . getDeclaredMethod ( "jlrFieldGetLong" , Field . class , Object . class ) ; method_jlrmi = clazz . getDeclaredMethod ( "jlrMethodInvoke" , Method . class , Object . class , Object [ ] . class ) ; method_jloObjectStream_hasInitializerMethod = clazz . getDeclaredMethod ( "jlosHasStaticInitializer" , Class . class ) ; } catch ( NoSuchMethodException nsme ) { throw new Impossible ( nsme ) ; } prepared = true ; } }
Cache the Method objects that will be injected .
36,746
private void ensureWatchThreadRunning ( ) { if ( ! threadRunning ) { thread = new Thread ( watchThread ) ; thread . setDaemon ( true ) ; thread . start ( ) ; watchThread . setThread ( thread ) ; watchThread . updateName ( ) ; threadRunning = true ; } }
Start the thread if it isn t already started .
36,747
public static TypeRegistry getTypeRegistryFor ( ClassLoader classloader ) { if ( classloader == null ) { return null ; } TypeRegistry existingRegistry = loaderToRegistryMap . get ( classloader ) ; if ( existingRegistry != null ) { return existingRegistry ; } if ( GlobalConfiguration . isRuntimeLogging && log . isLoggable ( Level . INFO ) ) { if ( excludedLoaderInstances . contains ( classloader . toString ( ) ) ) { return null ; } } String classloaderName = classloader . getClass ( ) . getName ( ) ; if ( classloaderName . equals ( "sun.reflect.DelegatingClassLoader" ) ) { return null ; } for ( String excluded : excludedLoaders ) { if ( classloaderName . startsWith ( excluded ) ) { if ( GlobalConfiguration . isRuntimeLogging && log . isLoggable ( Level . FINEST ) ) { log . info ( "Classloader " + classloaderName + " has been deliberately excluded" ) ; } excludedLoaderInstances . add ( classloader . toString ( ) ) ; return null ; } } try { Class . forName ( "org.springsource.loaded.ri.ReflectiveInterceptor" , false , classloader ) ; } catch ( ClassNotFoundException ex ) { if ( GlobalConfiguration . isRuntimeLogging && log . isLoggable ( Level . INFO ) ) { log . info ( "No TypeRegistry (can't load ReflectiveInterceptor) for loader " + classloader ) ; } return null ; } if ( GlobalConfiguration . isRuntimeLogging && log . isLoggable ( Level . INFO ) ) { log . info ( "TypeRegistry.getRegistryFor(): creating new TypeRegistry for loader " + classloader ) ; } TypeRegistry tr = new TypeRegistry ( classloader ) ; return tr ; }
Factory access method for obtaining TypeRegistry instances . Returns a TypeRegistry for the specified classloader .
36,748
private void loadPlugins ( ) { try { Enumeration < URL > pluginResources = classLoader . get ( ) . getResources ( "META-INF/services/org.springsource.reloading.agent.Plugins" ) ; while ( pluginResources . hasMoreElements ( ) ) { URL pluginResource = pluginResources . nextElement ( ) ; if ( GlobalConfiguration . isRuntimeLogging && log . isLoggable ( Level . FINEST ) ) { log . finest ( "loadPlugins: TypeRegistry=" + this . toString ( ) + ": loading plugin list file " + pluginResource ) ; } InputStream is = pluginResource . openStream ( ) ; BufferedReader pluginClassNamesReader = new BufferedReader ( new InputStreamReader ( is ) ) ; try { while ( true ) { String pluginName = pluginClassNamesReader . readLine ( ) ; if ( pluginName == null ) { break ; } if ( ! pluginName . startsWith ( "#" ) ) { pluginClassNames . add ( pluginName ) ; } } } catch ( IOException ioe ) { } is . close ( ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } for ( String pluginClassName : pluginClassNames ) { if ( GlobalConfiguration . isRuntimeLogging && log . isLoggable ( Level . FINEST ) ) { log . finest ( "loadPlugins: TypeRegistry=" + this . toString ( ) + ": loading plugin " + pluginClassName ) ; } try { Class < ? > pluginClass = Class . forName ( pluginClassName , false , this . classLoader . get ( ) ) ; Plugin pluginInstance = ( Plugin ) pluginClass . newInstance ( ) ; localPlugins . add ( pluginInstance ) ; } catch ( Exception e ) { log . log ( Level . WARNING , "Unable to find and instantiate plugin " + pluginClassName , e ) ; } } }
Determine if any plugins are visible from the attached classloader
36,749
private void parseRebasePaths ( String rebaseDefinitions ) { StringTokenizer tokenizer = new StringTokenizer ( rebaseDefinitions , "," ) ; while ( tokenizer . hasMoreTokens ( ) ) { String rebasePair = tokenizer . nextToken ( ) ; int equals = rebasePair . indexOf ( '=' ) ; String fromPrefix = rebasePair . substring ( 0 , equals ) ; String toPrefix = rebasePair . substring ( equals + 1 ) ; if ( GlobalConfiguration . isRuntimeLogging && log . isLoggable ( Level . INFO ) ) { log . info ( "processPropertiesConfiguration: adding rebase rule from '" + fromPrefix + "' to '" + toPrefix + "'" ) ; } rebasePaths . put ( fromPrefix , toPrefix ) ; } }
Process a set of rebase definitions of the form a = b c = d e = f .
36,750
public int getTypeIdFor ( String slashname , boolean allocateIfNotFound ) { if ( allocateIfNotFound ) { return NameRegistry . getIdOrAllocateFor ( slashname ) ; } else { return NameRegistry . getIdFor ( slashname ) ; } }
Lookup the type ID for a string . First checks those allocated but not yet registered then those that are already registered . If not found then a new one is allocated and recorded .
36,751
public void rememberReloadableType ( int typeId , ReloadableType rtype ) { if ( typeId >= reloadableTypes . length ) { resizeReloadableTypeArray ( typeId ) ; } reloadableTypes [ typeId ] = rtype ; if ( ( typeId + 1 ) > reloadableTypesSize ) { reloadableTypesSize = typeId + 1 ; } }
Sometimes we discover the reloadabletype during program execution for example A calls B and we haven t yet seen B . We find B has been loaded by a parent classloader let s remember B here so we can do fast lookups for it .
36,752
public ReloadableType getReloadableType ( String slashedClassName ) { int id = getTypeIdFor ( slashedClassName , true ) ; if ( id >= reloadableTypesSize ) { return null ; } return getReloadableType ( id ) ; }
Determine the reloadabletype object representation for a specified class . If the caller already knows the ID for the type that would be a quicker way to locate the reloadable type object .
36,753
public ReloadableType getReloadableType ( String slashedClassname , boolean allocateIdIfNotYetLoaded ) { if ( allocateIdIfNotYetLoaded ) { return getReloadableType ( getTypeIdFor ( slashedClassname , allocateIdIfNotYetLoaded ) ) ; } else { for ( int i = 0 ; i < reloadableTypesSize ; i ++ ) { ReloadableType rtype = reloadableTypes [ i ] ; if ( rtype != null && rtype . getSlashedName ( ) . equals ( slashedClassname ) ) { return rtype ; } } return null ; } }
Find the ReloadableType object for a given classname . If the allocateIdIfNotYetLoaded option is set then a new id will be allocated for this classname if it hasn t previously been seen before . This method does not create new ReloadableType objects they are expected to come into existence when defined by the classloader .
36,754
public static Object istcheck ( int ids , String nameAndDescriptor ) { if ( TypeRegistry . nothingReloaded ) { return null ; } int registryId = ids >>> 16 ; int typeId = ids & 0xffff ; TypeRegistry typeRegistry = registryInstances [ registryId ] . get ( ) ; ReloadableType reloadableType = typeRegistry . getReloadableType ( typeId ) ; if ( reloadableType == null ) { reloadableType = searchForReloadableType ( typeId , typeRegistry ) ; } if ( reloadableType != null && ! reloadableType . isAffectedByReload ( ) ) { return null ; } if ( reloadableType != null && reloadableType . hasBeenReloaded ( ) ) { MethodMember method = reloadableType . getLiveVersion ( ) . incrementalTypeDescriptor . getFromLatestByDescriptor ( nameAndDescriptor ) ; boolean dispatchThroughDescriptor = false ; if ( method == null ) { Object dispatcherToUse = null ; String supertypename = reloadableType . getTypeDescriptor ( ) . getSupertypeName ( ) ; TypeRegistry reg = reloadableType . getTypeRegistry ( ) ; boolean found = false ; while ( supertypename != null ) { ReloadableType nextInHierarchy = reg . getReloadableType ( supertypename ) ; if ( nextInHierarchy == null ) { TypeDescriptor td = reg . getDescriptorFor ( supertypename ) ; if ( td != null ) { method = td . getByNameAndDescriptor ( nameAndDescriptor ) ; supertypename = td . getSupertypeName ( ) ; } else { break ; } } else if ( nextInHierarchy . hasBeenReloaded ( ) ) { method = nextInHierarchy . getLiveVersion ( ) . incrementalTypeDescriptor . getFromLatestByDescriptor ( nameAndDescriptor ) ; if ( method != null && IncrementalTypeDescriptor . wasDeleted ( method ) ) { method = null ; } if ( method != null && ( MethodMember . isCatcher ( method ) || MethodMember . isSuperDispatcher ( method ) ) ) { method = null ; } } else { method = nextInHierarchy . getMethod ( nameAndDescriptor ) ; } if ( method != null ) { found = true ; break ; } if ( nextInHierarchy != null ) { supertypename = nextInHierarchy . getSlashedSupertypeName ( ) ; } } if ( found ) { return dispatcherToUse ; } throw new NoSuchMethodError ( reloadableType . getBaseName ( ) + "." + nameAndDescriptor ) ; } else if ( IncrementalTypeDescriptor . isBrandNewMethod ( method ) ) { dispatchThroughDescriptor = true ; } else if ( IncrementalTypeDescriptor . hasChanged ( method ) ) { if ( IncrementalTypeDescriptor . isNowNonStatic ( method ) ) { throw new IncompatibleClassChangeError ( "SpringLoaded: Target of static call is no longer static '" + reloadableType . getBaseName ( ) + "." + nameAndDescriptor + "'" ) ; } } if ( dispatchThroughDescriptor ) { if ( GlobalConfiguration . isRuntimeLogging && log . isLoggable ( Level . FINER ) ) { log . info ( "istcheck(): reloadabletype=" + reloadableType + " versionstamp " + reloadableType . getLiveVersion ( ) . versionstamp ) ; } return reloadableType . getLatestDispatcherInstance ( ) ; } } return null ; }
Determine if something has changed in a particular type related to a particular descriptor and so the dispatcher interface should be used . The type registry ID and class ID are merged in the ids parameter . This method is for INVOKESTATIC rewrites and so performs additional checks because it assumes the target is static .
36,755
public static boolean instanceFieldInterceptionRequired ( int ids , String name ) { if ( nothingReloaded ) { return false ; } int registryId = ids >>> 16 ; int typeId = ids & 0xffff ; TypeRegistry typeRegistry = registryInstances [ registryId ] . get ( ) ; ReloadableType reloadableType = typeRegistry . getReloadableType ( typeId ) ; if ( reloadableType != null ) { if ( reloadableType . hasFieldChangedInHierarchy ( name ) ) { return true ; } } return false ; }
Called for a field operation - trying to determine whether a particular field needs special handling .
36,756
public static boolean ivicheck ( int ids , String nameAndDescriptor ) { if ( nothingReloaded ) { return false ; } int registryId = ids >>> 16 ; int typeId = ids & 0xffff ; TypeRegistry typeRegistry = registryInstances [ registryId ] . get ( ) ; ReloadableType reloadableType = typeRegistry . getReloadableType ( typeId ) ; if ( reloadableType == null ) { reloadableType = searchForReloadableType ( typeId , typeRegistry ) ; } if ( reloadableType != null && ! reloadableType . isAffectedByReload ( ) ) { return false ; } if ( reloadableType != null && reloadableType . hasBeenReloaded ( ) ) { MethodMember method = reloadableType . getLiveVersion ( ) . incrementalTypeDescriptor . getFromLatestByDescriptor ( nameAndDescriptor ) ; boolean dispatchThroughDescriptor = false ; if ( method == null ) { if ( ! reloadableType . getTypeDescriptor ( ) . isFinalInHierarchy ( nameAndDescriptor ) ) { throw new NoSuchMethodError ( reloadableType . getBaseName ( ) + "." + nameAndDescriptor ) ; } } else if ( IncrementalTypeDescriptor . isBrandNewMethod ( method ) ) { dispatchThroughDescriptor = true ; } else if ( IncrementalTypeDescriptor . hasChanged ( method ) ) { if ( ! IncrementalTypeDescriptor . isCatcher ( method ) ) { if ( ! IncrementalTypeDescriptor . wasDeleted ( method ) ) { dispatchThroughDescriptor = true ; } } } if ( dispatchThroughDescriptor ) { if ( GlobalConfiguration . isRuntimeLogging && log . isLoggable ( Level . FINER ) ) { log . info ( "versionstamp " + reloadableType . getLiveVersion ( ) . versionstamp ) ; log . exiting ( "TypeRegistry" , "ivicheck" , true ) ; } return true ; } } return false ; }
Used in code the generated code replaces invokevirtual calls . Determine if the code can run as it was originally compiled .
36,757
public static ReloadableType getReloadableType ( int typeRegistryId , int typeId ) { if ( GlobalConfiguration . verboseMode && log . isLoggable ( Level . INFO ) ) { log . info ( ">TypeRegistry.getReloadableType(typeRegistryId=" + typeRegistryId + ",typeId=" + typeId + ")" ) ; } TypeRegistry typeRegistry = registryInstances [ typeRegistryId ] . get ( ) ; if ( typeRegistry == null ) { throw new IllegalStateException ( "Request to access registry id " + typeRegistryId + " but no registry with that id has been created" ) ; } ReloadableType reloadableType = typeRegistry . getReloadableType ( typeId ) ; if ( reloadableType == null ) { throw new IllegalStateException ( "The type registry " + typeRegistry + " does not know about type id " + typeId ) ; } reloadableType . setResolved ( ) ; if ( GlobalConfiguration . verboseMode && log . isLoggable ( Level . INFO ) ) { log . info ( "<TypeRegistry.getReloadableType(typeRegistryId=" + typeRegistryId + ",typeId=" + typeId + ") returning " + reloadableType ) ; } reloadableType . createTypeAssociations ( ) ; return reloadableType ; }
This method discovers the reloadable type instance for the registry and type id specified .
36,758
private List < TypePattern > getPatternsFrom ( String value ) { if ( value == null ) { return Collections . emptyList ( ) ; } List < TypePattern > typePatterns = new ArrayList < TypePattern > ( ) ; StringTokenizer st = new StringTokenizer ( value , "," ) ; while ( st . hasMoreElements ( ) ) { String typepattern = st . nextToken ( ) ; TypePattern typePattern = null ; if ( typepattern . endsWith ( "..*" ) ) { typePattern = new PrefixTypePattern ( typepattern ) ; if ( GlobalConfiguration . isRuntimeLogging && log . isLoggable ( Level . INFO ) ) { log . info ( "registered package prefix '" + typepattern + "'" ) ; } } else if ( typepattern . equals ( "*" ) ) { typePattern = new AnyTypePattern ( ) ; } else { typePattern = new ExactTypePattern ( typepattern ) ; } typePatterns . add ( typePattern ) ; } return typePatterns ; }
Process some type pattern objects from the supplied value . For example the value might be com . foo . Bar !com . foo . Goo
36,759
public synchronized int recordBootstrapMethod ( String slashedClassName , Handle bsm , Object [ ] bsmArgs ) { if ( bsmmap == null ) { bsmmap = new HashMap < String , BsmInfo [ ] > ( ) ; } BsmInfo [ ] bsminfo = bsmmap . get ( slashedClassName ) ; if ( bsminfo == null ) { bsminfo = new BsmInfo [ 1 ] ; bsminfo [ 0 ] = new BsmInfo ( bsm , bsmArgs ) ; bsmmap . put ( slashedClassName , bsminfo ) ; return 0 ; } else { int len = bsminfo . length ; BsmInfo [ ] newarray = new BsmInfo [ len + 1 ] ; System . arraycopy ( bsminfo , 0 , newarray , 0 , len ) ; bsminfo = newarray ; bsmmap . put ( slashedClassName , bsminfo ) ; bsminfo [ len ] = new BsmInfo ( bsm , bsmArgs ) ; return len ; } }
When an invokedynamic instruction is reached we allocate an id that recognizes that bsm and the parameters to that bsm . The index can be used when rewriting that invokedynamic
36,760
public static void associateReloadableType ( ReloadableType child , Class < ? > parent ) { ClassLoader parentClassLoader = parent . getClassLoader ( ) ; if ( parentClassLoader == null ) { return ; } TypeRegistry parentTypeRegistry = TypeRegistry . getTypeRegistryFor ( parent . getClassLoader ( ) ) ; ReloadableType parentReloadableType = parentTypeRegistry . getReloadableType ( parent ) ; if ( parentReloadableType != null ) { parentReloadableType . recordSubtype ( child ) ; } }
Called from the static initializer of a reloadabletype allowing it to connect itself to the parent type such that when reloading occurs we can mark all relevant types in the hierarchy as being impacted by the reload .
36,761
private void clearLocalVariableTableParameterNameDiscovererCache ( Class < ? > clazz ) { if ( localVariableTableParameterNameDiscovererInstances == null ) { return ; } if ( debug ) { System . out . println ( "SPRING_PLUGIN: ParameterNamesCache: Clearing parameter name discoverer caches" ) ; } if ( parameterNamesCacheField == null ) { try { parameterNamesCacheField = localVariableTableParameterNameDiscovererInstances . get ( 0 ) . getClass ( ) . getDeclaredField ( "parameterNamesCache" ) ; } catch ( NoSuchFieldException nsfe ) { log . log ( Level . SEVERE , "Unexpectedly cannot find parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class" ) ; } } for ( Object instance : localVariableTableParameterNameDiscovererInstances ) { try { parameterNamesCacheField . setAccessible ( true ) ; Map < ? , ? > parameterNamesCache = ( Map < ? , ? > ) parameterNamesCacheField . get ( instance ) ; Object o = parameterNamesCache . remove ( clazz ) ; if ( debug ) { System . out . println ( "SPRING_PLUGIN: ParameterNamesCache: Removed " + clazz . getName ( ) + " from cache?" + ( o != null ) ) ; } } catch ( IllegalAccessException e ) { log . log ( Level . SEVERE , "Unexpected IllegalAccessException trying to access parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class" ) ; } catch ( IllegalArgumentException iae ) { log . log ( Level . SEVERE , "Unexpected IllegalArgumentException trying to access parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class" ) ; } } }
The Spring class LocalVariableTableParameterNameDiscoverer holds a cache of parameter names discovered for members within classes and needs clearing if the class changes .
36,762
private void clearMappingRegistry ( Object o , Class < ? > clazz_AbstractHandlerMethodMapping ) { if ( debug ) { System . out . println ( "SPRING_PLUGIN: clearing out mapping registry..." ) ; } Object mappingRegistryInstance = null ; try { Field field_mappingRegistry = clazz_AbstractHandlerMethodMapping . getDeclaredField ( "mappingRegistry" ) ; field_mappingRegistry . setAccessible ( true ) ; mappingRegistryInstance = field_mappingRegistry . get ( o ) ; } catch ( NoSuchFieldException e ) { if ( debug ) { System . out . println ( "SPRING_PLUGIN: Unable to get mappingRegistry field on AbstractHandlerMethodMapping" ) ; } } catch ( IllegalAccessException e ) { if ( GlobalConfiguration . debugplugins || debug ) { System . out . println ( "SPRING_PLUGIN: Problem accessing mappingRegistry field on AbstractHandlerMethodMapping: " ) ; e . printStackTrace ( System . out ) ; } } if ( mappingRegistryInstance == null ) { return ; } Class mappingRegistryClass = mappingRegistryInstance . getClass ( ) ; clearMapField ( mappingRegistryClass , mappingRegistryInstance , "registry" ) ; clearMapField ( mappingRegistryClass , mappingRegistryInstance , "mappingLookup" ) ; clearMapField ( mappingRegistryClass , mappingRegistryInstance , "urlLookup" ) ; clearMapField ( mappingRegistryClass , mappingRegistryInstance , "nameLookup" ) ; clearMapField ( mappingRegistryClass , mappingRegistryInstance , "corsLookup" ) ; if ( debug ) { System . out . println ( "SPRING_PLUGIN: ... cleared out the mapping registry contents" ) ; } }
the initHandlerMethods below we will get an error about already existing mappings
36,763
private static Field asSetableField ( Field field , Object target , Class < ? > valueType , Object value , boolean makeAccessibleCopy ) throws IllegalAccessException { if ( isDeleted ( field ) ) { throw Exceptions . noSuchFieldError ( field ) ; } Class < ? > clazz = field . getDeclaringClass ( ) ; int mods = field . getModifiers ( ) ; if ( field . isAccessible ( ) || Modifier . isPublic ( mods & jlClassGetModifiers ( clazz ) ) ) { } else { Class < ? > callerClass = getCallerClass ( ) ; JVM . ensureMemberAccess ( callerClass , clazz , target , mods ) ; if ( makeAccessibleCopy ) { field = JVM . copyField ( field ) ; field . setAccessible ( true ) ; } } if ( isPrimitive ( valueType ) ) { typeCheckFieldSet ( field , valueType , value ) ; if ( ! field . isAccessible ( ) && Modifier . isFinal ( mods ) ) { throw Exceptions . illegalSetFinalFieldException ( field , field . getType ( ) , coerce ( value , field . getType ( ) ) ) ; } } else { if ( ! field . isAccessible ( ) && Modifier . isFinal ( mods ) ) { throw Exceptions . illegalSetFinalFieldException ( field , valueType , value ) ; } typeCheckFieldSet ( field , valueType , value ) ; } return makeAccessibleCopy ? field : null ; }
Performs all necessary checks that need to be done before a field set should be allowed .
36,764
private static void typeCheckFieldSet ( Field field , Object value ) throws IllegalAccessException { Class < ? > fieldType = field . getType ( ) ; if ( value == null ) { if ( fieldType . isPrimitive ( ) ) { throw Exceptions . illegalSetFieldTypeException ( field , null , value ) ; } } else { if ( fieldType . isPrimitive ( ) ) { fieldType = boxTypeFor ( fieldType ) ; } Class < ? > valueType = value . getClass ( ) ; if ( ! Utils . isConvertableFrom ( fieldType , valueType ) ) { throw Exceptions . illegalSetFieldTypeException ( field , valueType , value ) ; } } }
Perform a dynamic type check needed when setting a field value onto a field . Raises the appropriate exception when the check fails and returns normally otherwise . This method should only be called for object types . For primitive types call the three parameter variant instead .
36,765
private static void typeCheckFieldSet ( Field field , Class < ? > valueType , Object value ) throws IllegalAccessException { if ( ! isPrimitive ( valueType ) ) { typeCheckFieldSet ( field , value ) ; } else { Class < ? > fieldType = field . getType ( ) ; if ( ! Utils . isConvertableFrom ( fieldType , valueType ) ) { throw Exceptions . illegalSetFieldTypeException ( field , valueType , value ) ; } } }
Perform a dynamic type check needed when setting a field value onto a field . Raises the appropriate exception when the check fails and returns normally otherwise .
36,766
public static int jlClassGetModifiers ( Class < ? > clazz ) { ReloadableType rtype = getRType ( clazz ) ; if ( rtype == null ) { return clazz . getModifiers ( ) ; } else { return rtype . getLatestTypeDescriptor ( ) . getModifiers ( ) & ~ Opcodes . ACC_SUPER ; } }
Retrieve modifiers for a Java class which might or might not be reloadable or reloaded .
36,767
public static ReloadableType getRType ( Class < ? > clazz ) { WeakReference < ReloadableType > ref = classToRType . get ( clazz ) ; ReloadableType rtype = null ; if ( ref != null ) { rtype = ref . get ( ) ; } if ( rtype == null ) { if ( ! theOldWay ) { ClassLoader cl = clazz . getClassLoader ( ) ; TypeRegistry tr = TypeRegistry . getTypeRegistryFor ( cl ) ; if ( tr == null ) { classToRType . put ( clazz , ReloadableType . NOT_RELOADABLE_TYPE_REF ) ; } else { rtype = tr . getReloadableType ( clazz . getName ( ) . replace ( '.' , '/' ) ) ; if ( rtype == null ) { classToRType . put ( clazz , ReloadableType . NOT_RELOADABLE_TYPE_REF ) ; } else { classToRType . put ( clazz , new WeakReference < ReloadableType > ( rtype ) ) ; } } } else { Field rtypeField ; try { rtypeField = clazz . getDeclaredField ( Constants . fReloadableTypeFieldName ) ; } catch ( NoSuchFieldException nsfe ) { classToRType . put ( clazz , ReloadableType . NOT_RELOADABLE_TYPE_REF ) ; return null ; } try { rtypeField . setAccessible ( true ) ; rtype = ( ReloadableType ) rtypeField . get ( null ) ; if ( rtype == null ) { classToRType . put ( clazz , ReloadableType . NOT_RELOADABLE_TYPE_REF ) ; throw new ReloadException ( "ReloadableType field '" + Constants . fReloadableTypeFieldName + "' is 'null' on type " + clazz . getName ( ) ) ; } else { classToRType . put ( clazz , new WeakReference < ReloadableType > ( rtype ) ) ; } } catch ( Exception e ) { throw new ReloadException ( "Unable to access ReloadableType field '" + Constants . fReloadableTypeFieldName + "' on type " + clazz . getName ( ) , e ) ; } } } else if ( rtype == ReloadableType . NOT_RELOADABLE_TYPE ) { return null ; } return rtype ; }
Access and return the ReloadableType field on a specified class .
36,768
private static Class < ? > boxTypeFor ( Class < ? > primType ) { if ( primType == int . class ) { return Integer . class ; } else if ( primType == boolean . class ) { return Boolean . class ; } else if ( primType == byte . class ) { return Byte . class ; } else if ( primType == char . class ) { return Character . class ; } else if ( primType == double . class ) { return Double . class ; } else if ( primType == float . class ) { return Float . class ; } else if ( primType == long . class ) { return Long . class ; } else if ( primType == short . class ) { return Short . class ; } throw new IllegalStateException ( "Forgotten a case in this method?" ) ; }
What s the boxed version of a given primtive type .
36,769
private byte [ ] retransform ( byte [ ] bytes ) { if ( ! determinedNeedToRetransform ) { try { String s = System . getProperty ( "insight.enabled" , "false" ) ; if ( s . equals ( "true" ) ) { ClassLoader cl = typeRegistry . getClassLoader ( ) ; Field f = cl . getClass ( ) . getSuperclass ( ) . getDeclaredField ( "weavingTransformer" ) ; if ( f != null ) { f . setAccessible ( true ) ; retransformWeavingTransformer = f . get ( cl ) ; retransformWeavingTransformMethod = retransformWeavingTransformer . getClass ( ) . getDeclaredMethod ( "transformIfNecessary" , String . class , byte [ ] . class ) ; retransformNecessary = true ; } if ( GlobalConfiguration . isRuntimeLogging && log . isLoggable ( Level . INFO ) ) { log . info ( "Determining if retransform necessary, result = " + retransformNecessary ) ; } } } catch ( Exception e ) { log . log ( Level . SEVERE , "Unexpected exception when determining if Spring Insight enabled" , e ) ; retransformNecessary = false ; } determinedNeedToRetransform = true ; } if ( retransformNecessary ) { try { retransformWeavingTransformMethod . setAccessible ( true ) ; byte [ ] newdata = ( byte [ ] ) retransformWeavingTransformMethod . invoke ( retransformWeavingTransformer , this . slashedtypename , bytes ) ; if ( GlobalConfiguration . isRuntimeLogging && log . isLoggable ( Level . INFO ) ) { log . info ( "retransform was attempted, oldsize=" + bytes . length + " newsize=" + newdata . length ) ; } return newdata ; } catch ( Exception e ) { if ( GlobalConfiguration . isRuntimeLogging ) { log . log ( Level . SEVERE , "Unexpected exception when trying to run other weaving transformers" , e ) ; } } } return bytes ; }
This method will attempt to apply any pre - existing transforms to the provided bytecode if it is thought to be necessary . Currently necessary is determined by finding ourselves running under tcServer and Spring Insight being turned on .
36,770
private void resetEnumRelatedState ( ) { if ( clazz == null ) { return ; } try { Field f = clazz . getClass ( ) . getDeclaredField ( "enumConstants" ) ; f . setAccessible ( true ) ; f . set ( clazz , null ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } try { Field f = clazz . getClass ( ) . getDeclaredField ( "enumConstantDirectory" ) ; f . setAccessible ( true ) ; f . set ( clazz , null ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
When an enum type is reloaded two caches need to be cleared out from the Class object for the enum type .
36,771
public MethodMember getCurrentMethod ( String name , String descriptor ) { if ( liveVersion == null ) { return getMethod ( name , descriptor ) ; } else { return liveVersion . getReloadableMethod ( name , descriptor ) ; } }
Gets the method corresponding to given name and descriptor taking into consideration changes that have happened by reloading .
36,772
public int changed ( int methodId ) { if ( liveVersion == null ) { return 0 ; } else { int retval = 0 ; if ( liveVersion != null ) { if ( GlobalConfiguration . logging && log . isLoggable ( Level . FINER ) ) { log . info ( "MethodId=" + methodId + " method=" + typedescriptor . getMethod ( methodId ) ) ; } boolean b = liveVersion . incrementalTypeDescriptor . hasBeenDeleted ( methodId ) ; if ( b ) { retval = 2 ; } else { retval = liveVersion . incrementalTypeDescriptor . mustUseExecutorForThisMethod ( methodId ) ? 1 : 0 ; } } return retval ; } }
Check if the specified method is different to the original form from the type as loaded .
36,773
public __DynamicallyDispatchable determineDispatcher ( Object instance , String nameAndDescriptor ) { if ( nameAndDescriptor . startsWith ( "<init>" ) ) { if ( ! hasBeenReloaded ( ) ) { loadNewVersion ( "0" , bytesInitial ) ; } return ( __DynamicallyDispatchable ) getLiveVersion ( ) . dispatcherInstance ; } String dynamicTypeName = instance . getClass ( ) . getName ( ) ; ReloadableType rtype = typeRegistry . getReloadableType ( dynamicTypeName . replace ( '.' , '/' ) ) ; if ( rtype == null ) { throw new ReloadException ( "ReloadableType.determineDispatcher(): expected " + dynamicTypeName + " to be reloadable" ) ; } boolean found = false ; while ( rtype != null && ! found ) { if ( rtype . hasBeenReloaded ( ) ) { List < MethodMember > mms = rtype . getLiveVersion ( ) . incrementalTypeDescriptor . getNewOrChangedMethods ( ) ; for ( MethodMember mm : mms ) { if ( mm . isPrivate ( ) ) { continue ; } if ( mm . getNameAndDescriptor ( ) . equals ( nameAndDescriptor ) ) { found = true ; break ; } } } else { MethodMember [ ] mms = rtype . getTypeDescriptor ( ) . getMethods ( ) ; for ( MethodMember mm : mms ) { if ( mm . getNameAndDescriptor ( ) . equals ( nameAndDescriptor ) && ! MethodMember . isCatcher ( mm ) && ! MethodMember . isSuperDispatcher ( mm ) ) { found = true ; break ; } } } if ( ! found ) { String slashedSupername = rtype . getTypeDescriptor ( ) . getSupertypeName ( ) ; rtype = typeRegistry . getReloadableType ( slashedSupername ) ; } } if ( found ) { if ( GlobalConfiguration . isRuntimeLogging && log . isLoggable ( Level . INFO ) ) { log . log ( Level . INFO , "appears that type " + rtype . getName ( ) + " implements " + nameAndDescriptor ) ; } } if ( rtype == null ) { return null ; } if ( ! rtype . hasBeenReloaded ( ) ) { rtype . loadNewVersion ( "0" , rtype . bytesInitial ) ; } return ( __DynamicallyDispatchable ) rtype . getLiveVersion ( ) . dispatcherInstance ; }
Intended to handle dynamic dispatch . This will determine the right type to handle the specified method and return a dispatcher that can handle it .
36,774
public FieldMember findInstanceField ( String name ) { FieldMember found = getLatestTypeDescriptor ( ) . getField ( name ) ; if ( found != null ) { return found ; } String slashedSupername = getTypeDescriptor ( ) . getSupertypeName ( ) ; ReloadableType rtype = typeRegistry . getReloadableType ( slashedSupername ) ; while ( rtype != null ) { found = rtype . getLatestTypeDescriptor ( ) . getField ( name ) ; if ( found != null ) { break ; } slashedSupername = rtype . getTypeDescriptor ( ) . getSupertypeName ( ) ; rtype = typeRegistry . getReloadableType ( slashedSupername ) ; } return found ; }
Find the named instance field either on this reloadable type or on a reloadable supertype - it will not go into the non - reloadable types . This method also avoids interfaces because it is looking for instance fields . This is slightly naughty but if we assume the code we are reloading is valid code it should never be referring to interface fields .
36,775
public void setField ( Object instance , String fieldname , boolean isStatic , Object newValue ) throws IllegalAccessException { FieldReaderWriter fieldReaderWriter = locateField ( fieldname ) ; if ( isStatic && ! fieldReaderWriter . isStatic ( ) ) { throw new IncompatibleClassChangeError ( "Expected static field " + fieldReaderWriter . theField . getDeclaringTypeName ( ) + "." + fieldReaderWriter . theField . getName ( ) ) ; } else if ( ! isStatic && fieldReaderWriter . isStatic ( ) ) { throw new IncompatibleClassChangeError ( "Expected non-static field " + fieldReaderWriter . theField . getDeclaringTypeName ( ) + "." + fieldReaderWriter . theField . getName ( ) ) ; } if ( fieldReaderWriter . isStatic ( ) ) { fieldReaderWriter . setStaticFieldValue ( getClazz ( ) , newValue , null ) ; } else { fieldReaderWriter . setValue ( instance , newValue , null ) ; } }
Attempt to set the value of a field on an instance to the specified value .
36,776
public ReloadableType getSuperRtype ( ) { if ( superRtype != null ) { return superRtype ; } if ( superclazz == null ) { String name = this . getSlashedSupertypeName ( ) ; if ( name == null ) { return null ; } else { ReloadableType rtype = typeRegistry . getReloadableSuperType ( name ) ; superRtype = rtype ; return superRtype ; } } else { ClassLoader superClassLoader = superclazz . getClassLoader ( ) ; TypeRegistry superTypeRegistry = TypeRegistry . getTypeRegistryFor ( superClassLoader ) ; superRtype = superTypeRegistry . getReloadableType ( superclazz ) ; return superRtype ; } }
Return the ReloadableType representing the superclass of this type . If the supertype is not reloadable this method will return null . The ReloadableType that is returned may not be within the same type registry if the supertype was loaded by a different classloader .
36,777
public void define ( ) { staticInitializer = null ; haveLookedForStaticInitializer = false ; if ( ! typeDescriptor . isInterface ( ) ) { try { dispatcherClass = reloadableType . typeRegistry . defineClass ( dispatcherName , dispatcher , false ) ; } catch ( RuntimeException t ) { if ( t . getMessage ( ) . indexOf ( "duplicate class definition" ) == - 1 ) { throw t ; } else { t . printStackTrace ( ) ; } } } try { executorClass = reloadableType . typeRegistry . defineClass ( executorName , executor , false ) ; } catch ( RuntimeException t ) { if ( t . getMessage ( ) . indexOf ( "duplicate class definition" ) == - 1 ) { throw t ; } else { t . printStackTrace ( ) ; } } if ( ! typeDescriptor . isInterface ( ) ) { try { dispatcherInstance = dispatcherClass . newInstance ( ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( "Unable to build dispatcher class instance" , e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( "Unable to build dispatcher class instance" , e ) ; } } }
Defines this version . Called up front but can also be called later if the ChildClassLoader in a type registry is discarded and recreated .
36,778
public MethodMember getByDescriptor ( String name , String descriptor ) { for ( MethodMember existingMethod : methods ) { if ( existingMethod . getName ( ) . equals ( name ) && existingMethod . getDescriptor ( ) . equals ( descriptor ) ) { return existingMethod ; } } return null ; }
Check if this descriptor defines a method with the specified name and descriptor . Return the method if it is found . Modifiers generic signature and exceptions are ignored in this search .
36,779
public static byte [ ] extract ( byte [ ] classbytes , TypeRegistry registry , TypeDescriptor typeDescriptor ) { return new InterfaceExtractor ( registry ) . extract ( classbytes , typeDescriptor ) ; }
Extract the fixed interface for a class and a type descriptor with more details on the methods .
36,780
public static byte [ ] createFor ( ReloadableType rtype , IncrementalTypeDescriptor newVersionTypeDescriptor , String versionstamp ) { ClassReader fileReader = new ClassReader ( rtype . interfaceBytes ) ; DispatcherBuilderVisitor dispatcherVisitor = new DispatcherBuilderVisitor ( rtype , newVersionTypeDescriptor , versionstamp ) ; fileReader . accept ( dispatcherVisitor , 0 ) ; return dispatcherVisitor . getBytes ( ) ; }
Factory method that builds the dispatcher for a specified reloadabletype .
36,781
public void setValue ( Object instance , Object newValue , ISMgr stateManager ) throws IllegalAccessException { if ( typeDescriptor . isReloadable ( ) ) { if ( stateManager == null ) { stateManager = findInstanceStateManager ( instance ) ; } String declaringTypeName = typeDescriptor . getName ( ) ; Map < String , Object > typeLevelValues = stateManager . getMap ( ) . get ( declaringTypeName ) ; if ( typeLevelValues == null ) { typeLevelValues = new HashMap < String , Object > ( ) ; stateManager . getMap ( ) . put ( declaringTypeName , typeLevelValues ) ; } typeLevelValues . put ( theField . getName ( ) , newValue ) ; } else { if ( typeDescriptor . isInterface ( ) ) { throw new IncompatibleClassChangeError ( "Expected non-static field " + instance . getClass ( ) . getName ( ) + "." + theField . getName ( ) ) ; } else { findAndSetFieldValueInHierarchy ( instance , newValue ) ; } } }
Set the value of an instance field on the specified instance to the specified value . If a state manager is passed in things can be done in a more optimal way otherwise the state manager has to be discovered from the instance .
36,782
public Object getValue ( Object instance , ISMgr stateManager ) throws IllegalAccessException , IllegalArgumentException { Object result = null ; String fieldname = theField . getName ( ) ; if ( typeDescriptor . isReloadable ( ) ) { if ( stateManager == null ) { stateManager = findInstanceStateManager ( instance ) ; } String declaringTypeName = typeDescriptor . getName ( ) ; Map < String , Object > typeLevelValues = stateManager . getMap ( ) . get ( declaringTypeName ) ; boolean knownField = false ; if ( typeLevelValues != null ) { knownField = typeLevelValues . containsKey ( fieldname ) ; } if ( knownField ) { result = typeLevelValues . get ( fieldname ) ; } if ( typeLevelValues == null || ! knownField ) { FieldMember fieldOnOriginalType = typeDescriptor . getReloadableType ( ) . getTypeRegistry ( ) . getReloadableType ( declaringTypeName ) . getTypeDescriptor ( ) . getField ( fieldname ) ; if ( fieldOnOriginalType != null ) { ReloadableType rt = typeDescriptor . getReloadableType ( ) ; try { Field f = rt . getClazz ( ) . getDeclaredField ( fieldname ) ; f . setAccessible ( true ) ; result = f . get ( instance ) ; if ( typeLevelValues == null ) { typeLevelValues = new HashMap < String , Object > ( ) ; stateManager . getMap ( ) . put ( declaringTypeName , typeLevelValues ) ; } typeLevelValues . put ( fieldname , result ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Unexpectedly unable to access field " + fieldname + " on class " + rt . getClazz ( ) , e ) ; } } else { result = Utils . toResultCheckIfNull ( null , theField . getDescriptor ( ) ) ; if ( typeLevelValues == null ) { typeLevelValues = new HashMap < String , Object > ( ) ; stateManager . getMap ( ) . put ( declaringTypeName , typeLevelValues ) ; } typeLevelValues . put ( fieldname , result ) ; return result ; } } if ( result != null ) { result = Utils . checkCompatibility ( typeDescriptor . getTypeRegistry ( ) , result , theField . getDescriptor ( ) ) ; if ( result == null ) { typeLevelValues . remove ( fieldname ) ; } } result = Utils . toResultCheckIfNull ( result , theField . getDescriptor ( ) ) ; } else { if ( typeDescriptor . isInterface ( ) ) { throw new IncompatibleClassChangeError ( "Expected non-static field " + instance . getClass ( ) . getName ( ) + "." + fieldname ) ; } else { result = findAndGetFieldValueInHierarchy ( instance ) ; } } if ( GlobalConfiguration . isRuntimeLogging && log . isLoggable ( Level . FINER ) ) { log . finer ( "<getValue() value of " + theField + " is " + result ) ; } return result ; }
Return the value of the field for which is reader - writer exists . To improve performance a fieldAccessor can be supplied but if it is missing the code will go and discover it .
36,783
private Field locateFieldByReflection ( Class < ? > clazz , String typeWanted , boolean isInterface , String name ) { if ( clazz . getName ( ) . equals ( typeWanted ) ) { Field [ ] fs = clazz . getDeclaredFields ( ) ; if ( fs != null ) { for ( Field f : fs ) { if ( f . getName ( ) . equals ( name ) ) { return f ; } } } } if ( ! isInterface ) { Class < ? > [ ] interfaces = clazz . getInterfaces ( ) ; if ( interfaces != null ) { for ( Class < ? > intface : interfaces ) { Field f = locateFieldByReflection ( intface , typeWanted , isInterface , name ) ; if ( f != null ) { return f ; } } } } Class < ? > superclass = clazz . getSuperclass ( ) ; if ( superclass == null ) { return null ; } else { return locateFieldByReflection ( superclass , typeWanted , isInterface , name ) ; } }
Discover the named field in the hierarchy using the standard rules of resolution .
36,784
private ISMgr findInstanceStateManager ( Object instance ) { Class < ? > clazz = typeDescriptor . getReloadableType ( ) . getClazz ( ) ; try { Field fieldAccessorField = clazz . getField ( Constants . fInstanceFieldsName ) ; if ( fieldAccessorField == null ) { throw new IllegalStateException ( "Cant find field accessor for type " + clazz . getName ( ) ) ; } ISMgr stateManager = ( ISMgr ) fieldAccessorField . get ( instance ) ; if ( stateManager == null ) { ISMgr instanceStateManager = new ISMgr ( instance , typeDescriptor . getReloadableType ( ) ) ; fieldAccessorField . set ( instance , instanceStateManager ) ; stateManager = ( ISMgr ) fieldAccessorField . get ( instance ) ; if ( stateManager == null ) { throw new IllegalStateException ( "The class '" + clazz . getName ( ) + "' has a null instance state manager object, instance is " + instance ) ; } } return stateManager ; } catch ( Exception e ) { throw new IllegalStateException ( "Unexpectedly unable to find instance state manager on class " + clazz . getName ( ) , e ) ; } }
Discover the instance state manager for the specific object instance . Will fail by exception rather than returning null .
36,785
private SSMgr findStaticStateManager ( Class < ? > clazz ) { try { Field stateManagerField = clazz . getField ( Constants . fStaticFieldsName ) ; if ( stateManagerField == null ) { throw new IllegalStateException ( "Cant find field accessor for type " + typeDescriptor . getReloadableType ( ) . getName ( ) ) ; } SSMgr stateManager = ( SSMgr ) stateManagerField . get ( null ) ; if ( stateManager == null ) { throw new IllegalStateException ( "Instance of this class has no state manager: " + clazz . getName ( ) ) ; } return stateManager ; } catch ( Exception e ) { throw new IllegalStateException ( "Unexpectedly unable to find static state manager on class " + clazz . getName ( ) , e ) ; } }
Discover the static state manager on the specified class and return it . Will fail by exception rather than returning null .
36,786
private Object findAndGetFieldValueInHierarchy ( Object instance ) { Class < ? > clazz = instance . getClass ( ) ; String fieldname = theField . getName ( ) ; String searchName = typeDescriptor . getName ( ) . replace ( '/' , '.' ) ; while ( clazz != null && ! clazz . getName ( ) . equals ( searchName ) ) { clazz = clazz . getSuperclass ( ) ; } if ( clazz == null ) { throw new IllegalStateException ( "Failed to find " + searchName + " in hierarchy of " + instance . getClass ( ) ) ; } try { Field f = clazz . getDeclaredField ( fieldname ) ; f . setAccessible ( true ) ; return f . get ( instance ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Unexpectedly could not access field named " + fieldname + " on class " + clazz . getName ( ) ) ; } }
Walk up the instance hierarchy looking for the field and when it is found access it and return the result . Will exit via exception if it cannot find the field or something goes wrong when accessing it .
36,787
public static void addCorrectReturnInstruction ( MethodVisitor mv , ReturnType returnType , boolean createCast ) { if ( returnType . isPrimitive ( ) ) { char ch = returnType . descriptor . charAt ( 0 ) ; switch ( ch ) { case 'V' : mv . visitInsn ( RETURN ) ; break ; case 'I' : case 'Z' : case 'S' : case 'B' : case 'C' : mv . visitInsn ( IRETURN ) ; break ; case 'F' : mv . visitInsn ( FRETURN ) ; break ; case 'D' : mv . visitInsn ( DRETURN ) ; break ; case 'J' : mv . visitInsn ( LRETURN ) ; break ; default : throw new IllegalArgumentException ( "Not supported for '" + ch + "'" ) ; } } else { if ( GlobalConfiguration . assertsMode ) { if ( returnType . descriptor . endsWith ( ";" ) && ! returnType . descriptor . startsWith ( "[" ) ) { throw new IllegalArgumentException ( "Invalid signature of '" + returnType . descriptor + "'" ) ; } } if ( createCast ) { mv . visitTypeInsn ( CHECKCAST , returnType . descriptor ) ; } mv . visitInsn ( ARETURN ) ; } }
Depending on the signature of the return type add the appropriate instructions to the method visitor .
36,788
public static int getParameterCount ( String methodDescriptor ) { int pos = 1 ; int count = 0 ; char ch ; while ( ( ch = methodDescriptor . charAt ( pos ) ) != ')' ) { if ( ch == 'L' ) { pos = methodDescriptor . indexOf ( ';' , pos + 1 ) ; } else if ( ch == '[' ) { while ( methodDescriptor . charAt ( ++ pos ) == '[' ) { } if ( methodDescriptor . charAt ( pos ) == 'L' ) { pos = methodDescriptor . indexOf ( ';' , pos + 1 ) ; } } count ++ ; pos ++ ; } return count ; }
Return the number of parameters in the descriptor . Copes with primitives and arrays and reference types .
36,789
public static void createLoadsBasedOnDescriptor ( MethodVisitor mv , String descriptor , int startindex ) { int slot = startindex ; int descriptorpos = 1 ; char ch ; while ( ( ch = descriptor . charAt ( descriptorpos ) ) != ')' ) { switch ( ch ) { case '[' : mv . visitVarInsn ( ALOAD , slot ) ; slot ++ ; while ( descriptor . charAt ( ++ descriptorpos ) == '[' ) { } if ( descriptor . charAt ( descriptorpos ) == 'L' ) { descriptorpos = descriptor . indexOf ( ';' , descriptorpos ) + 1 ; } else { descriptorpos ++ ; } break ; case 'L' : mv . visitVarInsn ( ALOAD , slot ) ; slot ++ ; descriptorpos = descriptor . indexOf ( ';' , descriptorpos ) + 1 ; break ; case 'J' : mv . visitVarInsn ( LLOAD , slot ) ; slot += 2 ; descriptorpos ++ ; break ; case 'D' : mv . visitVarInsn ( DLOAD , slot ) ; slot += 2 ; descriptorpos ++ ; break ; case 'F' : mv . visitVarInsn ( FLOAD , slot ) ; descriptorpos ++ ; slot ++ ; break ; case 'I' : case 'Z' : case 'B' : case 'C' : case 'S' : mv . visitVarInsn ( ILOAD , slot ) ; descriptorpos ++ ; slot ++ ; break ; default : throw new IllegalStateException ( "Unexpected type in descriptor: " + ch ) ; } } }
Create the set of LOAD instructions to load the method parameters . Take into account the size and type .
36,790
public static Class < ? > [ ] toParamClasses ( String methodDescriptor , ClassLoader classLoader ) throws ClassNotFoundException { Type [ ] paramTypes = Type . getArgumentTypes ( methodDescriptor ) ; Class < ? > [ ] paramClasses = new Class < ? > [ paramTypes . length ] ; for ( int i = 0 ; i < paramClasses . length ; i ++ ) { paramClasses [ i ] = toClass ( paramTypes [ i ] , classLoader ) ; } return paramClasses ; }
Given a method descriptor extract the parameter descriptor and convert into corresponding Class objects . This requires a reference to a class loader to convert type names into Class objects .
36,791
public static Class < ? > toClass ( Type type , ClassLoader classLoader ) throws ClassNotFoundException { switch ( type . getSort ( ) ) { case Type . VOID : return void . class ; case Type . BOOLEAN : return boolean . class ; case Type . CHAR : return char . class ; case Type . BYTE : return byte . class ; case Type . SHORT : return short . class ; case Type . INT : return int . class ; case Type . FLOAT : return float . class ; case Type . LONG : return long . class ; case Type . DOUBLE : return double . class ; case Type . ARRAY : Class < ? > clazz = toClass ( type . getElementType ( ) , classLoader ) ; return Array . newInstance ( clazz , 0 ) . getClass ( ) ; default : return Class . forName ( type . getClassName ( ) , false , classLoader ) ; } }
Convert an asm Type into a corresponding Class object requires a reference to a ClassLoader to be able to convert classnames to class objects .
36,792
public static String toPaddedNumber ( int value , int width ) { StringBuilder s = new StringBuilder ( "00000000" ) . append ( Integer . toString ( value ) ) ; return s . substring ( s . length ( ) - width ) ; }
Create the string representation of an integer and pad it to a particular width using leading zeroes .
36,793
public static byte [ ] loadBytesFromStream ( InputStream stream ) { try { BufferedInputStream bis = new BufferedInputStream ( stream ) ; byte [ ] theData = new byte [ 10000000 ] ; int dataReadSoFar = 0 ; byte [ ] buffer = new byte [ 1024 ] ; int read = 0 ; while ( ( read = bis . read ( buffer ) ) != - 1 ) { System . arraycopy ( buffer , 0 , theData , dataReadSoFar , read ) ; dataReadSoFar += read ; } bis . close ( ) ; byte [ ] returnData = new byte [ dataReadSoFar ] ; System . arraycopy ( theData , 0 , returnData , 0 , dataReadSoFar ) ; return returnData ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Load all the byte data from an input stream .
36,794
public static int sizeOf ( String typeDescriptor ) { if ( typeDescriptor . length ( ) != 1 ) { return 1 ; } char ch = typeDescriptor . charAt ( 0 ) ; if ( ch == 'J' || ch == 'D' ) { return 2 ; } else { return 1 ; } }
Return the size of a type . The size is usually 1 except for double and long which are of size 2 . The descriptor passed in is the full descriptor including any leading L and trailing ; .
36,795
public static void dumpClass ( String file , byte [ ] bytes ) { File f = new File ( file ) ; try { FileOutputStream fos = new FileOutputStream ( f ) ; fos . write ( bytes ) ; fos . flush ( ) ; fos . close ( ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; } }
Dump some bytes into the specified file .
36,796
public static int getSize ( String descriptor ) { int size = 0 ; int descriptorpos = 1 ; char ch ; while ( ( ch = descriptor . charAt ( descriptorpos ) ) != ')' ) { switch ( ch ) { case '[' : size ++ ; while ( descriptor . charAt ( ++ descriptorpos ) == '[' ) { ; } if ( descriptor . charAt ( descriptorpos ) == 'L' ) { descriptorpos = descriptor . indexOf ( ';' , descriptorpos ) + 1 ; } else { descriptorpos ++ ; } break ; case 'L' : size ++ ; descriptorpos = descriptor . indexOf ( ';' , descriptorpos ) + 1 ; break ; case 'J' : size = size + 2 ; descriptorpos ++ ; break ; case 'D' : size = size + 2 ; descriptorpos ++ ; break ; case 'F' : case 'B' : case 'S' : case 'I' : case 'Z' : case 'C' : size ++ ; descriptorpos ++ ; break ; default : throw new IllegalStateException ( "Unexpected character in descriptor: " + ch ) ; } } return size ; }
Compute the size required for a specific method descriptor .
36,797
public static byte [ ] loadFromStream ( InputStream stream ) { try { BufferedInputStream bis = new BufferedInputStream ( stream ) ; int size = 2048 ; byte [ ] theData = new byte [ size ] ; int dataReadSoFar = 0 ; byte [ ] buffer = new byte [ size / 2 ] ; int read = 0 ; while ( ( read = bis . read ( buffer ) ) != - 1 ) { if ( ( read + dataReadSoFar ) > theData . length ) { byte [ ] newTheData = new byte [ theData . length * 2 ] ; System . arraycopy ( theData , 0 , newTheData , 0 , dataReadSoFar ) ; theData = newTheData ; } System . arraycopy ( buffer , 0 , theData , dataReadSoFar , read ) ; dataReadSoFar += read ; } bis . close ( ) ; byte [ ] returnData = new byte [ dataReadSoFar ] ; System . arraycopy ( theData , 0 , returnData , 0 , dataReadSoFar ) ; return returnData ; } catch ( IOException e ) { throw new ReloadException ( "Unexpectedly unable to load bytedata from input stream" , e ) ; } }
Load the contents of an input stream .
36,798
public static < T > T [ ] arrayCopyOf ( T [ ] array , int newSize ) { @ SuppressWarnings ( "unchecked" ) T [ ] newArr = ( T [ ] ) Array . newInstance ( array . getClass ( ) . getComponentType ( ) , newSize ) ; System . arraycopy ( array , 0 , newArr , 0 , Math . min ( newSize , newArr . length ) ) ; return newArr ; }
Utility method similar to Java 1 . 6 Arrays . copyOf used instead of that method to stick to Java 1 . 5 only API .
36,799
public static int makePublicNonFinal ( int access ) { access = ( access & ~ ( ACC_PRIVATE | ACC_PROTECTED ) ) | ACC_PUBLIC ; access = ( access & ~ ACC_FINAL ) ; return access ; }
Modify visibility to be public .