idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
4,500
private void generateInsert ( M2MEntity entity , String packageName ) { if ( ! isMethodAlreadyDefined ( entity , "insert" ) ) { MethodSpec methodSpec = MethodSpec . methodBuilder ( "insert" ) . addModifiers ( Modifier . PUBLIC ) . addModifiers ( Modifier . ABSTRACT ) . addAnnotation ( AnnotationSpec . builder ( BindSqlInsert . class ) . build ( ) ) . addParameter ( ParameterSpec . builder ( TypeUtility . className ( packageName , entity . name ) , "bean" ) . addAnnotation ( AnnotationSpec . builder ( BindSqlParam . class ) . addMember ( "value" , "$S" , "bean" ) . build ( ) ) . build ( ) ) . returns ( Integer . TYPE ) . build ( ) ; classBuilder . addMethod ( methodSpec ) ; } }
Generate insert .
4,501
public static void generate ( Elements elementUtils , Filer filer , SQLiteDatabaseSchema schema ) throws Exception { BindDaoFactoryBuilder visitor = new BindDaoFactoryBuilder ( elementUtils , filer , schema ) ; visitor . buildDaoFactoryInterface ( elementUtils , filer , schema ) ; String daoFactoryName = BindDaoFactoryBuilder . generateDaoFactoryName ( schema ) ; BindDataSourceBuilder visitorDao = new BindDataSourceBuilder ( elementUtils , filer , schema ) ; visitorDao . buildDataSource ( elementUtils , filer , schema , daoFactoryName ) ; generateSchema ( schema ) ; }
Generate database .
4,502
static String defineFileName ( SQLiteDatabaseSchema model ) { int lastIndex = model . fileName . lastIndexOf ( "." ) ; String schemaName = model . fileName ; if ( lastIndex > - 1 ) { schemaName = model . fileName . substring ( 0 , lastIndex ) ; } schemaName = schemaName . toLowerCase ( ) + "_schema_" + model . version + ".sql" ; return schemaName ; }
Define file name .
4,503
public static ClassName generateDataSourceName ( SQLiteDatabaseSchema schema ) { String dataSourceName = schema . getName ( ) ; dataSourceName = PREFIX + dataSourceName ; PackageElement pkg = BaseProcessor . elementUtils . getPackageOf ( schema . getElement ( ) ) ; String packageName = pkg . isUnnamed ( ) ? "" : pkg . getQualifiedName ( ) . toString ( ) ; return ClassName . get ( packageName , dataSourceName ) ; }
Generate dataSource name .
4,504
public static void generateDaoUids ( TypeSpec . Builder classBuilder , SQLiteDatabaseSchema schema ) { for ( SQLiteDaoDefinition dao : schema . getCollection ( ) ) { classBuilder . addField ( FieldSpec . builder ( Integer . TYPE , dao . daoUidName , Modifier . FINAL , Modifier . STATIC , Modifier . PUBLIC ) . initializer ( "" + dao . daoUidValue ) . addJavadoc ( "Unique identifier for Dao $L\n" , dao . getName ( ) ) . build ( ) ) ; } }
Generate Dao s UID . If specified prefix will be used to
4,505
private String extractDaoFieldNameForInternalDataSource ( SQLiteDaoDefinition dao ) { return "_" + CaseFormat . UPPER_CAMEL . to ( CaseFormat . LOWER_CAMEL , dao . getName ( ) ) ; }
Extract dao field name for internal data source .
4,506
private void generatePopulate ( SQLiteDatabaseSchema schema , MethodSpec . Builder methodBuilder , boolean instance ) { methodBuilder . beginControlFlow ( "try" ) ; methodBuilder . addStatement ( "instance.openWritableDatabase()" ) ; methodBuilder . addStatement ( "instance.close()" ) ; if ( ( instance && schema . configPopulatorClazz != null ) || ( ! instance ) ) { methodBuilder . addComment ( "force database DDL run" ) ; methodBuilder . beginControlFlow ( "if (options.populator!=null && instance.justCreated)" ) ; methodBuilder . addComment ( "run populator only a time" ) ; methodBuilder . addStatement ( "instance.justCreated=false" ) ; methodBuilder . addComment ( "run populator" ) ; methodBuilder . addStatement ( "options.populator.execute()" ) ; methodBuilder . endControlFlow ( ) ; } methodBuilder . nextControlFlow ( "catch($T e)" , Throwable . class ) ; methodBuilder . addStatement ( "$T.error(e.getMessage())" , Logger . class ) ; methodBuilder . addStatement ( "e.printStackTrace()" ) ; methodBuilder . endControlFlow ( ) ; }
Generate populate .
4,507
private void generateOpen ( String schemaName ) { MethodSpec . Builder methodBuilder = MethodSpec . methodBuilder ( "open" ) . addModifiers ( Modifier . PUBLIC , Modifier . STATIC ) . returns ( className ( schemaName ) ) ; methodBuilder . addJavadoc ( "Retrieve data source instance and open it.\n" ) ; methodBuilder . addJavadoc ( "@return opened dataSource instance.\n" ) ; methodBuilder . addStatement ( "$L instance=getInstance()" , schemaName ) ; methodBuilder . addStatement ( "instance.openWritableDatabase()" ) ; methodBuilder . addCode ( "return instance;\n" ) ; classBuilder . addMethod ( methodBuilder . build ( ) ) ; }
Generate open .
4,508
private void generateOnConfigure ( boolean useForeignKey ) { MethodSpec . Builder methodBuilder = MethodSpec . methodBuilder ( "onConfigure" ) . addAnnotation ( Override . class ) . addModifiers ( Modifier . PUBLIC ) ; methodBuilder . addParameter ( SQLiteDatabase . class , "database" ) ; methodBuilder . addJavadoc ( "onConfigure\n" ) ; methodBuilder . addCode ( "// configure database\n" ) ; if ( useForeignKey ) { methodBuilder . addStatement ( "database.setForeignKeyConstraintsEnabled(true)" ) ; } methodBuilder . beginControlFlow ( "if (options.databaseLifecycleHandler != null)" ) ; methodBuilder . addStatement ( "options.databaseLifecycleHandler.onConfigure(database)" ) ; methodBuilder . endControlFlow ( ) ; classBuilder . addMethod ( methodBuilder . build ( ) ) ; }
Generate on configure .
4,509
public static List < SQLiteEntity > orderEntitiesList ( SQLiteDatabaseSchema schema ) { List < SQLiteEntity > entities = schema . getEntitiesAsList ( ) ; Collections . sort ( entities , new Comparator < SQLiteEntity > ( ) { public int compare ( SQLiteEntity lhs , SQLiteEntity rhs ) { return lhs . getTableName ( ) . compareTo ( rhs . getTableName ( ) ) ; } } ) ; List < SQLiteEntity > list = schema . getEntitiesAsList ( ) ; EntitySorter < SQLiteEntity > sorder = new EntitySorter < SQLiteEntity > ( list ) { public Collection < SQLiteEntity > getDependencies ( SQLiteEntity item ) { return item . referedEntities ; } public void generateError ( SQLiteEntity item ) { throw new CircularRelationshipException ( item ) ; } } ; return sorder . order ( ) ; }
Generate ordered entities list .
4,510
private void generateRxInterface ( String daoFactory , RxInterfaceType interfaceType , Class < ? > clazz ) { { ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName . get ( ClassName . get ( clazz ) , TypeVariableName . get ( "T" ) ) ; String preExecutorName = clazz . getSimpleName ( ) . replace ( "Emitter" , "" ) ; String postExecutorName = com . abubusoft . kripton . common . CaseFormat . UPPER_UNDERSCORE . to ( CaseFormat . UPPER_CAMEL , interfaceType . toString ( ) ) ; if ( interfaceType == RxInterfaceType . BATCH ) { classBuilder . addType ( TypeSpec . interfaceBuilder ( preExecutorName + postExecutorName ) . addModifiers ( Modifier . PUBLIC ) . addTypeVariable ( TypeVariableName . get ( "T" ) ) . addMethod ( MethodSpec . methodBuilder ( "onExecute" ) . addParameter ( className ( daoFactory ) , "daoFactory" ) . addParameter ( parameterizedTypeName , "emitter" ) . addModifiers ( Modifier . PUBLIC , Modifier . ABSTRACT ) . returns ( Void . TYPE ) . build ( ) ) . build ( ) ) ; } else { classBuilder . addType ( TypeSpec . interfaceBuilder ( preExecutorName + postExecutorName ) . addModifiers ( Modifier . PUBLIC ) . addTypeVariable ( TypeVariableName . get ( "T" ) ) . addMethod ( MethodSpec . methodBuilder ( "onExecute" ) . addParameter ( className ( daoFactory ) , "daoFactory" ) . addParameter ( parameterizedTypeName , "emitter" ) . addModifiers ( Modifier . PUBLIC , Modifier . ABSTRACT ) . returns ( TransactionResult . class ) . build ( ) ) . build ( ) ) ; } } }
Generate rx interface .
4,511
private static void generateEditor ( PrefsEntity entity ) { com . abubusoft . kripton . common . Converter < String , String > converter = CaseFormat . LOWER_CAMEL . converterTo ( CaseFormat . UPPER_CAMEL ) ; Builder innerClassBuilder = TypeSpec . classBuilder ( "BindEditor" ) . addModifiers ( Modifier . PUBLIC ) . addJavadoc ( "editor class for shared preferences\n" ) . superclass ( typeName ( "AbstractEditor" ) ) ; innerClassBuilder . addMethod ( MethodSpec . constructorBuilder ( ) . addModifiers ( Modifier . PRIVATE ) . build ( ) ) ; PrefsTransform transform ; for ( PrefsProperty item : entity . getCollection ( ) ) { { MethodSpec . Builder builder = MethodSpec . methodBuilder ( "put" + converter . convert ( item . getName ( ) ) ) . addModifiers ( Modifier . PUBLIC ) . addParameter ( typeName ( item . getElement ( ) ) , "value" ) . addJavadoc ( "modifier for property $L\n" , item . getName ( ) ) . returns ( typeName ( "BindEditor" ) ) ; TypeName type ; if ( item . hasTypeAdapter ( ) ) { type = typeName ( item . typeAdapter . dataType ) ; } else { type = TypeUtility . typeName ( item . getElement ( ) ) ; } transform = PrefsTransformer . lookup ( type ) ; transform . generateWriteProperty ( builder , "editor" , null , "value" , item ) ; builder . addCode ( "\n" ) ; builder . addStatement ( "return this" ) ; innerClassBuilder . addMethod ( builder . build ( ) ) ; } { MethodSpec . Builder builder = MethodSpec . methodBuilder ( "remove" + converter . convert ( item . getName ( ) ) ) . addModifiers ( Modifier . PUBLIC ) . addJavadoc ( "remove property $L\n" , item . getName ( ) ) . returns ( typeName ( "BindEditor" ) ) ; builder . addStatement ( "editor.remove($S)" , item . getPreferenceKey ( ) ) ; builder . addStatement ( "return this" ) ; innerClassBuilder . addMethod ( builder . build ( ) ) ; } } { MethodSpec . Builder builder = MethodSpec . methodBuilder ( "clear" ) . addModifiers ( Modifier . PUBLIC ) . addJavadoc ( "clear all properties\n" ) . returns ( typeName ( "BindEditor" ) ) ; builder . addStatement ( "editor.clear()" ) ; builder . addStatement ( "return this" ) ; innerClassBuilder . addMethod ( builder . build ( ) ) ; } builder . addType ( innerClassBuilder . build ( ) ) ; }
create editor .
4,512
private static void generateInstance ( String className ) { builder . addField ( FieldSpec . builder ( className ( className ) , "instance" , Modifier . PRIVATE , Modifier . STATIC ) . addJavadoc ( "instance of shared preferences\n" ) . build ( ) ) ; MethodSpec . Builder methodBuilder = MethodSpec . methodBuilder ( "getInstance" ) . addModifiers ( Modifier . PUBLIC , Modifier . STATIC , Modifier . SYNCHRONIZED ) . addJavadoc ( "get instance of shared preferences\n" ) . returns ( className ( className ) ) ; methodBuilder . beginControlFlow ( "if (instance==null)" ) ; methodBuilder . addStatement ( "instance=new $L()" , className ( className ) ) ; methodBuilder . addComment ( "read and write instance to sync with default values" ) ; methodBuilder . addStatement ( "instance.write(instance.read())" ) ; methodBuilder . endControlFlow ( ) ; methodBuilder . addCode ( "return instance;\n" ) ; builder . addMethod ( methodBuilder . build ( ) ) ; }
Generate instance of shared preferences .
4,513
private static void generateRefresh ( String sharedPreferenceName , String className ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "refresh" ) . addModifiers ( Modifier . PUBLIC ) . addJavadoc ( "force to refresh values\n" ) . returns ( className ( className ) ) ; method . addStatement ( "createPrefs()" ) ; method . addStatement ( "return this" ) ; builder . addMethod ( method . build ( ) ) ; }
Generate refresh .
4,514
private static void generateResetMethod ( PrefsEntity entity ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "reset" ) . addModifiers ( Modifier . PUBLIC ) . addJavadoc ( "reset shared preferences\n" ) . returns ( Void . TYPE ) ; if ( entity . isImmutablePojo ( ) ) { ImmutableUtility . generateImmutableVariableInit ( entity , method ) ; ImmutableUtility . generateImmutableEntityCreation ( entity , method , "bean" , true ) ; } else { method . addStatement ( "$T bean=new $T()" , entity . getElement ( ) , entity . getElement ( ) ) ; } method . addStatement ( "write(bean)" ) ; builder . addMethod ( method . build ( ) ) ; }
Generate reset method .
4,515
private static void generateWriteMethod ( PrefsEntity entity ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "write" ) . addJavadoc ( "write bean entirely\n\n" ) . addJavadoc ( "@param bean bean to entirely write\n" ) . addModifiers ( Modifier . PUBLIC ) . addParameter ( typeName ( entity . getName ( ) ) , "bean" ) . returns ( Void . TYPE ) ; method . addStatement ( "$T editor=prefs.edit()" , SharedPreferences . Editor . class ) ; PrefsTransform transform ; for ( PrefsProperty item : entity . getCollection ( ) ) { if ( item . hasTypeAdapter ( ) ) { transform = PrefsTransformer . lookup ( item . typeAdapter . getDataTypeTypename ( ) ) ; } else { transform = PrefsTransformer . lookup ( item ) ; } transform . generateWriteProperty ( method , "editor" , typeName ( entity . getElement ( ) ) , "bean" , item ) ; method . addCode ( "\n" ) ; } method . addCode ( "\n" ) ; method . addStatement ( "editor.commit()" ) ; builder . addMethod ( method . build ( ) ) ; }
Generate write method .
4,516
private static void generateReadMethod ( PrefsEntity entity ) { MethodSpec . Builder methodBuilder = MethodSpec . methodBuilder ( "read" ) . addModifiers ( Modifier . PUBLIC ) . addJavadoc ( "read bean entirely\n\n" ) . addJavadoc ( "@return read bean\n" ) . returns ( typeName ( entity . getName ( ) ) ) ; if ( entity . isImmutablePojo ( ) ) { methodBuilder . addCode ( "\n" ) ; methodBuilder . addComment ( "initialize temporary variable for immutable POJO" ) ; ImmutableUtility . generateImmutableVariableInit ( entity , methodBuilder ) ; } else { methodBuilder . addStatement ( "$T bean=new $T()" , typeName ( entity . getName ( ) ) , typeName ( entity . getName ( ) ) ) ; } PrefsTransform transform ; for ( PrefsProperty item : entity . getCollection ( ) ) { if ( item . hasTypeAdapter ( ) ) { transform = PrefsTransformer . lookup ( item . typeAdapter . getDataTypeTypename ( ) ) ; } else { transform = PrefsTransformer . lookup ( item ) ; } if ( entity . isImmutablePojo ( ) ) { transform . generateReadProperty ( methodBuilder , "prefs" , typeName ( item . getElement ( ) . asType ( ) ) , null , item , true , ReadType . NONE ) ; } else { transform . generateReadProperty ( methodBuilder , "prefs" , typeName ( item . getElement ( ) . asType ( ) ) , "bean" , item , true , ReadType . NONE ) ; } methodBuilder . addCode ( "\n" ) ; } if ( entity . isImmutablePojo ( ) ) { methodBuilder . addComment ( "reset temporary variable for immutable POJO" ) ; ImmutableUtility . generateImmutableEntityCreation ( entity , methodBuilder , "bean" , true ) ; } methodBuilder . addCode ( "\n" ) ; methodBuilder . addStatement ( "return bean" ) ; builder . addMethod ( methodBuilder . build ( ) ) ; }
Generate read method .
4,517
private static void generateSingleReadMethod ( PrefsEntity entity ) { PrefsTransform transform ; Converter < String , String > converter = CaseFormat . LOWER_CAMEL . converterTo ( CaseFormat . UPPER_CAMEL ) ; for ( PrefsProperty item : entity . getCollection ( ) ) { MethodSpec . Builder methodBuilder = MethodSpec . methodBuilder ( "get" + converter . convert ( item . getName ( ) ) ) . addModifiers ( Modifier . PUBLIC ) . addJavadoc ( "reads property <code>$L</code> from shared pref with key <code>$L</code>\n\n" , item . getName ( ) , item . getPreferenceKey ( ) ) . addJavadoc ( "@return property $L value\n" , item . getName ( ) ) . returns ( item . getPropertyType ( ) . getTypeName ( ) ) ; if ( item . hasTypeAdapter ( ) ) { transform = PrefsTransformer . lookup ( item . typeAdapter . getDataTypeTypename ( ) ) ; } else { transform = PrefsTransformer . lookup ( item ) ; } transform . generateReadProperty ( methodBuilder , "prefs" , typeName ( item . getElement ( ) . asType ( ) ) , "defaultBean" , item , false , ReadType . RETURN ) ; builder . addMethod ( methodBuilder . build ( ) ) ; } }
Generate single read method .
4,518
protected void serialize ( BinderContext context , E object , SerializerWrapper serializerWrapper , boolean writeStartAndEnd ) throws Exception { switch ( context . getSupportedFormat ( ) ) { case XML : try { XmlWrapperSerializer wrapper = ( ( XmlWrapperSerializer ) serializerWrapper ) ; XMLSerializer xmlSerializer = wrapper . xmlSerializer ; if ( writeStartAndEnd ) { xmlSerializer . writeStartDocument ( ) ; } serializeOnXml ( object , xmlSerializer , 0 ) ; if ( writeStartAndEnd ) { xmlSerializer . writeEndDocument ( ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; throw ( new KriptonRuntimeException ( e ) ) ; } break ; default : if ( context . getSupportedFormat ( ) . onlyText ) serializeOnJacksonAsString ( object , ( ( JacksonWrapperSerializer ) serializerWrapper ) . jacksonGenerator ) ; else serializeOnJackson ( object , ( ( JacksonWrapperSerializer ) serializerWrapper ) . jacksonGenerator ) ; break ; } }
Serialize an object using the contxt and the serializerWrapper .
4,519
@ SuppressWarnings ( "unchecked" ) public static < T > Set < T > asSet ( Class < T > itemType , T ... objects ) { LinkedHashSet < T > result = new LinkedHashSet < T > ( ) ; for ( T item : objects ) { result . add ( item ) ; } return result ; }
create a collection set with initial values .
4,520
public static < E extends List < Boolean > > E asList ( boolean [ ] array , Class < E > listType ) { E result ; try { result = listType . newInstance ( ) ; for ( Object item : array ) { result . add ( ( boolean ) item ) ; } return result ; } catch ( InstantiationException | IllegalAccessException e ) { e . printStackTrace ( ) ; throw ( new KriptonRuntimeException ( e . getMessage ( ) ) ) ; } }
As list .
4,521
public static byte [ ] asByteTypeArray ( List < Byte > input ) { byte [ ] result = new byte [ input . size ( ) ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = input . get ( i ) ; } return result ; }
As byte type array .
4,522
public static char [ ] asCharacterTypeArray ( List < Character > input ) { char [ ] result = new char [ input . size ( ) ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = input . get ( i ) ; } return result ; }
As character type array .
4,523
public static short [ ] asShortTypeArray ( List < Short > input ) { short [ ] result = new short [ input . size ( ) ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = input . get ( i ) ; } return result ; }
As short type array .
4,524
public static int [ ] asIntegerTypeArray ( List < Integer > input ) { int [ ] result = new int [ input . size ( ) ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = input . get ( i ) ; } return result ; }
As integer type array .
4,525
public static long [ ] asLongTypeArray ( List < Long > input ) { long [ ] result = new long [ input . size ( ) ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = input . get ( i ) ; } return result ; }
As long type array .
4,526
public static float [ ] asFloatTypeArray ( List < Float > input ) { float [ ] result = new float [ input . size ( ) ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = input . get ( i ) ; } return result ; }
As float type array .
4,527
public static String [ ] asStringArray ( List < String > input ) { String [ ] result = new String [ input . size ( ) ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = input . get ( i ) ; } return result ; }
As string array .
4,528
public static Boolean [ ] asBooleanArray ( List < Boolean > input ) { Boolean [ ] result = new Boolean [ input . size ( ) ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = input . get ( i ) ; } return result ; }
As boolean array .
4,529
public static < E > E [ ] asArray ( List < E > input , E [ ] newArray ) { return input . toArray ( newArray ) ; }
As array .
4,530
public static Double [ ] asDoubleArray ( List < Double > input ) { Double [ ] result = new Double [ input . size ( ) ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = input . get ( i ) ; } return result ; }
As double array .
4,531
public static void trim ( List < String > value ) { if ( value == null ) return ; for ( int i = 0 ; i < value . size ( ) ; i ++ ) { value . set ( i , value . get ( i ) . trim ( ) ) ; } }
trim each element of lists .
4,532
public static String resolveFullyQualifiedColumnName ( SQLiteDatabaseSchema schema , SQLiteModelMethod method , String className , String columnName ) { Finder < SQLProperty > currentEntity = method . getEntity ( ) ; if ( StringUtils . hasText ( className ) ) { currentEntity = schema . getEntityBySimpleName ( className ) ; AssertKripton . assertTrueOrUnknownClassInJQLException ( currentEntity != null , method , className ) ; } SQLProperty currentProperty = currentEntity . findPropertyByName ( columnName ) ; AssertKripton . assertTrueOrUnknownPropertyInJQLException ( currentProperty != null , method , columnName ) ; return ( StringUtils . hasText ( className ) ? currentEntity . getTableName ( ) + "." : "" ) + currentProperty . columnName ; }
given a fully qualified property name it will be transformed in associated column name . If class or property does not exist an exception will be thrown
4,533
public static boolean isLiveData ( SQLiteModelMethod methodDefinition ) { boolean result = false ; TypeName returnTypeName = methodDefinition . getReturnClass ( ) ; if ( returnTypeName instanceof ParameterizedTypeName ) { ParameterizedTypeName returnParameterizedTypeName = ( ParameterizedTypeName ) returnTypeName ; ClassName returnParameterizedClassName = returnParameterizedTypeName . rawType ; if ( KriptonLiveDataManager . getInstance ( ) . isLiveData ( returnParameterizedClassName . toString ( ) ) ) { result = true ; } } return result ; }
Checks if is live data .
4,534
private String getJQLDeclared ( ) { ModelAnnotation inserAnnotation = this . getAnnotation ( BindSqlInsert . class ) ; ModelAnnotation updateAnnotation = this . getAnnotation ( BindSqlUpdate . class ) ; ModelAnnotation selectAnnotation = this . getAnnotation ( BindSqlSelect . class ) ; ModelAnnotation deleteAnnotation = this . getAnnotation ( BindSqlDelete . class ) ; String jql = null ; int counter = 0 ; if ( selectAnnotation != null ) { jql = selectAnnotation . getAttribute ( AnnotationAttributeType . JQL ) ; if ( StringUtils . hasText ( jql ) ) { counter ++ ; AssertKripton . assertTrue ( selectAnnotation . getAttributeCount ( ) > 1 , "Annotation %s in method %s.%s have more than one annotation with JQL attribute" , selectAnnotation . getSimpleName ( ) , this . getParent ( ) . getName ( ) , this . getName ( ) ) ; } } if ( inserAnnotation != null ) { jql = inserAnnotation . getAttribute ( AnnotationAttributeType . JQL ) ; if ( StringUtils . hasText ( jql ) ) { counter ++ ; AssertKripton . assertTrue ( inserAnnotation . getAttributeCount ( ) > 1 , "Annotation %s in method %s.%s have more than one annotation with JQL attribute" , inserAnnotation . getSimpleName ( ) , this . getParent ( ) . getName ( ) , this . getName ( ) ) ; } } if ( updateAnnotation != null ) { jql = updateAnnotation . getAttribute ( AnnotationAttributeType . JQL ) ; if ( StringUtils . hasText ( jql ) ) { counter ++ ; AssertKripton . assertTrue ( updateAnnotation . getAttributeCount ( ) > 1 , "Annotation %s in method %s.%s have more than one annotation with JQL attribute" , updateAnnotation . getSimpleName ( ) , this . getParent ( ) . getName ( ) , this . getName ( ) ) ; } } if ( deleteAnnotation != null ) { jql = deleteAnnotation . getAttribute ( AnnotationAttributeType . JQL ) ; if ( StringUtils . hasText ( jql ) ) { counter ++ ; AssertKripton . assertTrue ( deleteAnnotation . getAttributeCount ( ) > 1 , "Annotation %s in method %s.%s have more than one annotation with JQL attribute" , deleteAnnotation . getSimpleName ( ) , this . getParent ( ) . getName ( ) , this . getName ( ) ) ; } } AssertKripton . assertTrue ( counter <= 1 , "Method %s.%s have more than one annotation with JQL attribute" , this . getParent ( ) . getName ( ) , this . getName ( ) ) ; jql = StringEscapeUtils . unescapeEcmaScript ( jql ) ; return jql ; }
Gets the JQL declared .
4,535
private < A extends Annotation > void findStringDynamicStatement ( SQLiteDaoDefinition parent , Class < A > annotationClazz , List < Class < ? extends Annotation > > unsupportedQueryType , OnFoundDynamicParameter listener ) { int counter = 0 ; for ( VariableElement p : element . getParameters ( ) ) { A annotation = p . getAnnotation ( annotationClazz ) ; if ( annotation != null ) { for ( Class < ? extends Annotation > item : unsupportedQueryType ) { AssertKripton . assertTrueOrInvalidMethodSignException ( element . getAnnotation ( item ) == null , this , "in this method is not allowed to mark parameters with @%s annotation." , annotationClazz . getSimpleName ( ) ) ; } AssertKripton . assertTrueOrInvalidMethodSignException ( TypeUtility . isString ( TypeUtility . typeName ( p ) ) , this , "only String parameters can be marked with @%s annotation." , annotationClazz . getSimpleName ( ) ) ; listener . onFoundParameter ( p . getSimpleName ( ) . toString ( ) ) ; counter ++ ; } } AssertKripton . assertTrueOrInvalidMethodSignException ( counter < 2 , this , "there are %s parameters marked with @%s. Only one is allowed." , counter , annotationClazz . getSimpleName ( ) ) ; }
Look for a method parameter which is annotated with an annotationClass annotation . When it is found a client action is required through listener .
4,536
public String findParameterAliasByName ( String name ) { if ( parameterName2Alias . containsKey ( name ) ) { return parameterName2Alias . get ( name ) ; } return name ; }
Retrieve for a method s parameter its alias used to work with queries . If no alias is present typeName will be used .
4,537
public TypeName getAdapterForParam ( String paramName ) { if ( this . hasAdapterForParam ( paramName ) ) { return TypeUtility . typeName ( this . parameterName2Adapter . get ( paramName ) ) ; } else { return null ; } }
Gets the adapter for param .
4,538
public String findEntityProperty ( ) { SQLiteEntity entity = getEntity ( ) ; for ( Pair < String , TypeName > item : this . parameters ) { if ( item . value1 . equals ( TypeUtility . typeName ( entity . getElement ( ) ) ) ) { return item . value0 ; } } return null ; }
Find entity property .
4,539
public String buildPreparedStatementName ( ) { if ( ! StringUtils . hasText ( preparedStatementName ) ) { preparedStatementName = getParent ( ) . buildPreparedStatementName ( getName ( ) ) ; } return preparedStatementName ; }
Builds the prepared statement name .
4,540
public static String checkSize ( Object value , int limitSize , String defaultValue ) { if ( value != null ) { if ( byte [ ] . class . getSimpleName ( ) . equals ( value . getClass ( ) . getSimpleName ( ) ) ) { return checkSize ( ( byte [ ] ) value , limitSize / 2 ) ; } String str = value . toString ( ) ; if ( str . length ( ) > limitSize ) { return str . substring ( 0 , limitSize - 3 ) + "..." ; } else return str ; } else return defaultValue ; }
limit string size .
4,541
public static String bytesToHex ( byte [ ] bytes , int size ) { size = Math . min ( bytes . length , size ) ; char [ ] hexChars = new char [ size * 2 ] ; for ( int j = 0 ; j < size ; j ++ ) { int v = bytes [ j ] & 0xFF ; hexChars [ j * 2 ] = hexArray [ v >>> 4 ] ; hexChars [ j * 2 + 1 ] = hexArray [ v & 0x0F ] ; } return new String ( hexChars ) ; }
Bytes to hex .
4,542
public static String checkSize ( byte [ ] value , int limitSize ) { if ( value != null ) { if ( value . length > limitSize ) { return bytesToHex ( value , limitSize - 3 ) + "..." ; } else return bytesToHex ( value , value . length ) ; } else return null ; }
Check size .
4,543
public static String formatParam ( Object value , String delimiter ) { if ( value != null ) { if ( byte [ ] . class . getSimpleName ( ) . equals ( value . getClass ( ) . getSimpleName ( ) ) ) { return checkSize ( ( byte [ ] ) value , VIEW_SIZE ) ; } String str = value . toString ( ) ; if ( str . length ( ) > VIEW_SIZE ) { return delimiter + str . substring ( 0 , VIEW_SIZE - 3 ) + "..." + delimiter ; } else return delimiter + str + delimiter ; } else return "<undefined>" ; }
format as sql parameter . If value is not null method will return value . If value is not null delimiter will be used to delimit return value . Otherwise defaultValue will be returned without delimiter .
4,544
public static String checkSize ( Object value , String defaultValue ) { return checkSize ( value , VIEW_SIZE , defaultValue ) ; }
limit string size to 32 .
4,545
public static String lowercaseFirstLetter ( String value ) { if ( value == null || value . length ( ) == 0 ) return "" ; char [ ] stringArray = value . toCharArray ( ) ; stringArray [ 0 ] = Character . toLowerCase ( stringArray [ 0 ] ) ; return new String ( stringArray ) ; }
Lowercase first letter .
4,546
public static void string2Writer ( String source , Writer out ) throws IOException { char [ ] buffer = source . toCharArray ( ) ; for ( int i = 0 ; i < buffer . length ; i ++ ) { out . append ( buffer [ i ] ) ; } out . flush ( ) ; }
String 2 writer .
4,547
public static String reader2String ( Reader source ) throws IOException { char [ ] cbuf = new char [ 65535 ] ; StringBuffer stringbuf = new StringBuffer ( ) ; int count = 0 ; while ( ( count = source . read ( cbuf , 0 , 65535 ) ) != - 1 ) { stringbuf . append ( cbuf , 0 , count ) ; } return stringbuf . toString ( ) ; }
Reader 2 string .
4,548
public static byte [ ] addDouble ( byte [ ] array , double value ) { byte [ ] holder = new byte [ 4 ] ; doubleTo ( holder , 0 , value ) ; return add ( array , holder ) ; }
Adds the double .
4,549
public static byte [ ] insertDoubleInto ( byte [ ] array , int index , double value ) { byte [ ] holder = new byte [ 4 ] ; doubleTo ( holder , 0 , value ) ; return insert ( array , index , holder ) ; }
Insert double into .
4,550
public static boolean equalsOrDie ( byte [ ] expected , byte [ ] got ) { if ( expected . length != got . length ) { throw new KriptonRuntimeException ( "Lengths did not match, expected length" + expected . length + "but got" + got . length ) ; } for ( int index = 0 ; index < expected . length ; index ++ ) { if ( expected [ index ] != got [ index ] ) { throw new KriptonRuntimeException ( "value at index did not match index" + index + "expected value" + expected [ index ] + "but got" + got [ index ] ) ; } } return true ; }
Checks to see if two arrays are equals .
4,551
private void considerNotify ( ObserverWrapper observer ) { if ( ! observer . mActive ) { return ; } if ( ! observer . shouldBeActive ( ) ) { observer . activeStateChanged ( false ) ; return ; } if ( observer . mLastVersion >= mVersion ) { return ; } observer . mLastVersion = mVersion ; observer . mObserver . onChanged ( ( T ) mData ) ; }
Consider notify .
4,552
public void removeObserver ( final Observer < T > observer ) { assertMainThread ( "removeObserver" ) ; ObserverWrapper removed = mObservers . remove ( observer ) ; if ( removed == null ) { return ; } removed . detachObserver ( ) ; removed . activeStateChanged ( false ) ; }
Removes the given observer from the observers list .
4,553
public T getValue ( ) { Object data = mData ; if ( data != NOT_SET ) { return ( T ) data ; } return null ; }
Returns the current value . Note that calling this method on a background thread does not guarantee that the latest value set will be received .
4,554
public SQLProperty getPrimaryKey ( ) { for ( SQLProperty item : collection ) { if ( item . isPrimaryKey ( ) ) { return item ; } } SQLProperty id = findPropertyByName ( "id" ) ; return id ; }
True if there is a primary key .
4,555
private String buildTableName ( Elements elementUtils , SQLiteDatabaseSchema schema ) { tableName = getSimpleName ( ) ; tableName = schema . classNameConverter . convert ( tableName ) ; String temp = AnnotationUtility . extractAsString ( getElement ( ) , BindSqlType . class , AnnotationAttributeType . NAME ) ; if ( StringUtils . hasText ( temp ) ) { tableName = temp ; } return tableName ; }
Builds the table name .
4,556
public Touple < SQLProperty , String , SQLiteEntity , SQLRelationType > findRelationByParentProperty ( String parentFieldName ) { for ( Touple < SQLProperty , String , SQLiteEntity , SQLRelationType > item : relations ) { if ( item . value0 . getName ( ) . equals ( parentFieldName ) ) { return item ; } } return null ; }
find a relation specifing parent field name that is the name of the relation
4,557
static String extractWhereConditions ( boolean updateMode , SQLiteModelMethod method ) { final One < String > whereCondition = new One < String > ( "" ) ; final One < Boolean > found = new One < Boolean > ( null ) ; JQLChecker . getInstance ( ) . replaceVariableStatements ( method , method . jql . value , new JQLReplaceVariableStatementListenerImpl ( ) { public String onWhere ( String statement ) { if ( found . value0 == null ) { whereCondition . value0 = statement ; found . value0 = true ; } return null ; } } ) ; return StringUtils . ifNotEmptyAppend ( whereCondition . value0 , " " ) ; }
Extract where conditions .
4,558
static boolean isIn ( TypeName value , Class < ? > ... classes ) { for ( Class < ? > item : classes ) { if ( value . toString ( ) . equals ( TypeName . get ( item ) . toString ( ) ) ) { return true ; } } return false ; }
Checks if is in .
4,559
public static Map < String , Object > parseMap ( AbstractContext context , ParserWrapper parserWrapper , Map < String , Object > map ) { switch ( context . getSupportedFormat ( ) ) { case XML : throw ( new KriptonRuntimeException ( context . getSupportedFormat ( ) + " context does not support parse direct map parsing" ) ) ; default : JacksonWrapperParser wrapperParser = ( JacksonWrapperParser ) parserWrapper ; JsonParser parser = wrapperParser . jacksonParser ; map . clear ( ) ; return parseMap ( context , parser , map , false ) ; } }
Parse a map .
4,560
static Map < String , Object > parseMap ( AbstractContext context , JsonParser parser , Map < String , Object > map , boolean skipRead ) { try { String key ; Object value ; if ( ! skipRead ) { parser . nextToken ( ) ; } if ( parser . currentToken ( ) != JsonToken . START_OBJECT ) { throw ( new KriptonRuntimeException ( "Invalid input format" ) ) ; } skipRead = false ; do { if ( skipRead ) { key = parser . getCurrentName ( ) ; } else { key = parser . nextFieldName ( ) ; skipRead = true ; } JsonToken token = parser . nextToken ( ) ; switch ( token ) { case START_ARRAY : value = parseList ( context , parser , new ArrayList < Object > ( ) , true ) ; break ; case VALUE_EMBEDDED_OBJECT : value = parseMap ( context , parser , new LinkedHashMap < String , Object > ( ) , true ) ; break ; default : value = parser . getValueAsString ( ) ; } map . put ( key , value ) ; } while ( parser . nextToken ( ) != JsonToken . END_OBJECT ) ; return map ; } catch ( IOException e ) { e . printStackTrace ( ) ; throw ( new KriptonRuntimeException ( e ) ) ; } }
Parse map .
4,561
static List < Object > parseList ( AbstractContext context , JsonParser parser , List < Object > list , boolean skipRead ) { try { if ( ! skipRead ) { parser . nextToken ( ) ; } if ( parser . currentToken ( ) != JsonToken . START_ARRAY ) { throw ( new KriptonRuntimeException ( "Invalid input format" ) ) ; } skipRead = false ; JsonToken token ; do { if ( skipRead ) { token = parser . getCurrentToken ( ) ; } else { token = parser . nextToken ( ) ; skipRead = true ; } switch ( token ) { case VALUE_FALSE : case VALUE_TRUE : case VALUE_NUMBER_FLOAT : case VALUE_NUMBER_INT : case VALUE_STRING : list . add ( parser . getText ( ) ) ; break ; case VALUE_NULL : list . add ( null ) ; break ; case VALUE_EMBEDDED_OBJECT : list . add ( parseMap ( context , parser , new LinkedHashMap < String , Object > ( ) , true ) ) ; break ; case START_ARRAY : list . add ( parseList ( context , parser , list , true ) ) ; break ; default : break ; } } while ( parser . nextToken ( ) != JsonToken . END_ARRAY ) ; return list ; } catch ( IOException e ) { e . printStackTrace ( ) ; throw ( new KriptonRuntimeException ( e ) ) ; } }
Parse a list .
4,562
public static BinderContext bind ( BinderType format ) { BinderContext binder = binders . get ( format ) ; if ( binder == null ) throw new KriptonRuntimeException ( String . format ( "%s format is not supported" , format ) ) ; return binder ; }
retrieve binding context for specified data format .
4,563
public static String readText ( InputStream inputStream ) { BufferedReader bufferedReader = new BufferedReader ( new InputStreamReader ( inputStream ) ) ; String line ; StringBuilder stringBuilder = new StringBuilder ( ) ; try { while ( ( line = bufferedReader . readLine ( ) ) != null ) { stringBuilder . append ( line ) ; stringBuilder . append ( '\n' ) ; } } catch ( IOException e ) { Logger . error ( e . getMessage ( ) ) ; e . printStackTrace ( ) ; return null ; } finally { if ( bufferedReader != null ) { try { bufferedReader . close ( ) ; } catch ( IOException e ) { Logger . error ( e . getMessage ( ) ) ; e . printStackTrace ( ) ; } } } return stringBuilder . toString ( ) ; }
Read text .
4,564
private Class < ? > defineMapClass ( ParameterizedTypeName mapTypeName ) { if ( mapTypeName . rawType . toString ( ) . startsWith ( Map . class . getCanonicalName ( ) ) ) { return HashMap . class ; } else if ( mapTypeName . rawType . toString ( ) . startsWith ( SortedMap . class . getCanonicalName ( ) ) ) { return TreeMap . class ; } try { return Class . forName ( mapTypeName . rawType . toString ( ) ) ; } catch ( ClassNotFoundException e ) { e . printStackTrace ( ) ; return null ; } }
Define map class .
4,565
private String fillClazz ( String configClazz , String clazz ) { if ( ! clazz . equals ( configClazz ) ) { return configClazz ; } else { return null ; } }
Fill clazz .
4,566
public void addEntity ( SQLiteEntity value ) { entities . put ( value . getName ( ) , value ) ; entitiesBySimpleName . put ( value . getSimpleName ( ) . toString ( ) . toLowerCase ( ) , value ) ; Set < SQLProperty > listEntity = null ; for ( SQLProperty p : value . getCollection ( ) ) { listEntity = propertyBySimpleName . get ( p . getName ( ) ) ; if ( listEntity == null ) { listEntity = new HashSet < > ( ) ; } checkName ( listEntity , p ) ; listEntity . add ( p ) ; propertyBySimpleName . put ( p . getName ( ) . toLowerCase ( ) , listEntity ) ; } }
Adds the entity .
4,567
private void checkName ( Set < SQLProperty > listEntity , SQLProperty p ) { for ( SQLProperty item : listEntity ) { AssertKripton . assertTrueOrInvalidPropertyName ( item . columnName . equals ( p . columnName ) , item , p ) ; } }
property in different class but same name must have same column name .
4,568
public Finder < SQLProperty > getEntityBySimpleName ( String entityName ) { if ( entityName == null ) return null ; SQLiteEntity result = entitiesBySimpleName . get ( entityName . toLowerCase ( ) ) ; if ( result != null ) return result ; for ( GeneratedTypeElement item : this . generatedEntities ) { if ( item . typeSpec . name . toLowerCase ( ) . equals ( entityName . toLowerCase ( ) ) ) { return item ; } } return null ; }
Gets the entity by simple name .
4,569
public Set < SQLProperty > getPropertyBySimpleName ( String propertyName ) { if ( propertyName == null ) return null ; return this . propertyBySimpleName . get ( propertyName . toLowerCase ( ) ) ; }
Gets the property by simple name .
4,570
public String findColumnNameByPropertyName ( SQLiteModelMethod method , String propertyName ) { Set < SQLProperty > propertiesSet = getPropertyBySimpleName ( propertyName ) ; Set < String > set = new HashSet < String > ( ) ; String result = null ; for ( SQLProperty item : propertiesSet ) { result = item . columnName ; set . add ( item . columnName ) ; } AssertKripton . assertTrueOrInvalidMethodSignException ( result != null && set . size ( ) == 1 , method , "in JQL attribute can not translate property %s" , propertyName ) ; return result ; }
get a .
4,571
public ClassName getGeneratedClass ( ) { String packageName = getElement ( ) . asType ( ) . toString ( ) ; return TypeUtility . className ( packageName . substring ( 0 , packageName . lastIndexOf ( "." ) ) + "." + getGeneratedClassName ( ) ) ; }
Gets the generated class .
4,572
public static void renameTablesWithPrefix ( SQLiteDatabase db , final String prefix ) { Logger . info ( "MASSIVE TABLE RENAME OPERATION: ADD PREFIX " + prefix ) ; query ( db , null , QueryType . TABLE , new OnResultListener ( ) { public void onRow ( SQLiteDatabase db , String name , String sql ) { sql = String . format ( "ALTER TABLE %s RENAME TO %s%s;" , name , prefix , name ) ; Logger . info ( sql ) ; db . execSQL ( sql ) ; } } ) ; }
Add to all table a specifix prefix .
4,573
public static void dropTablesWithPrefix ( SQLiteDatabase db , String prefix ) { Logger . info ( "MASSIVE TABLE DROP OPERATION%s" , StringUtils . ifNotEmptyAppend ( prefix , " WITH PREFIX " ) ) ; drop ( db , QueryType . TABLE , prefix ) ; }
Drop all table with specific prefix .
4,574
public static void dropTablesAndIndices ( SQLiteDatabase db ) { drop ( db , QueryType . INDEX , null ) ; drop ( db , QueryType . TABLE , null ) ; }
Drop tables and indices .
4,575
public static String detectSourceType ( Element element , String adapterClazz ) { TypeElement a = BaseProcessor . elementUtils . getTypeElement ( adapterClazz ) ; for ( Element i : BaseProcessor . elementUtils . getAllMembers ( a ) ) { if ( i . getKind ( ) == ElementKind . METHOD && "toJava" . equals ( i . getSimpleName ( ) . toString ( ) ) ) { ExecutableElement method = ( ExecutableElement ) i ; return TypeUtility . typeName ( method . getReturnType ( ) ) . toString ( ) ; } } AssertKripton . fail ( "In '%s', class '%s' can not be used as type adapter" , element , adapterClazz ) ; return null ; }
Detect source type .
4,576
public static String detectSourceType ( SQLiteModelMethod method , TypeName adapterTypeName ) { TypeElement a = BaseProcessor . elementUtils . getTypeElement ( adapterTypeName . toString ( ) ) ; for ( Element i : BaseProcessor . elementUtils . getAllMembers ( a ) ) { if ( i . getKind ( ) == ElementKind . METHOD && "toJava" . equals ( i . getSimpleName ( ) . toString ( ) ) ) { ExecutableElement m = ( ExecutableElement ) i ; return TypeUtility . typeName ( m . getReturnType ( ) ) . toString ( ) ; } } AssertKripton . fail ( "In method '%s#%s', class '%s' can not be used as type adapter" , method . getParent ( ) , method . getName ( ) , adapterTypeName . toString ( ) ) ; return null ; }
Give a param with type adapter obtain type used to convert param
4,577
protected void ensureElementsCapacity ( ) { final int elStackSize = elName . length ; final int newSize = ( depth >= 7 ? 2 * depth : 8 ) + 2 ; if ( TRACE_SIZING ) { System . err . println ( getClass ( ) . getName ( ) + " elStackSize " + elStackSize + " ==> " + newSize ) ; } final boolean needsCopying = elStackSize > 0 ; String [ ] arr = null ; arr = new String [ newSize ] ; if ( needsCopying ) System . arraycopy ( elName , 0 , arr , 0 , elStackSize ) ; elName = arr ; arr = new String [ newSize ] ; if ( needsCopying ) System . arraycopy ( elPrefix , 0 , arr , 0 , elStackSize ) ; elPrefix = arr ; arr = new String [ newSize ] ; if ( needsCopying ) System . arraycopy ( elNamespace , 0 , arr , 0 , elStackSize ) ; elNamespace = arr ; final int [ ] iarr = new int [ newSize ] ; if ( needsCopying ) { System . arraycopy ( elNamespaceCount , 0 , iarr , 0 , elStackSize ) ; } else { iarr [ 0 ] = 0 ; } elNamespaceCount = iarr ; }
Ensure elements capacity .
4,578
protected void ensureNamespacesCapacity ( ) { final int newSize = namespaceEnd > 7 ? 2 * namespaceEnd : 8 ; if ( TRACE_SIZING ) { System . err . println ( getClass ( ) . getName ( ) + " namespaceSize " + namespacePrefix . length + " ==> " + newSize ) ; } final String [ ] newNamespacePrefix = new String [ newSize ] ; final String [ ] newNamespaceUri = new String [ newSize ] ; if ( namespacePrefix != null ) { System . arraycopy ( namespacePrefix , 0 , newNamespacePrefix , 0 , namespaceEnd ) ; System . arraycopy ( namespaceUri , 0 , newNamespaceUri , 0 , namespaceEnd ) ; } namespacePrefix = newNamespacePrefix ; namespaceUri = newNamespaceUri ; }
Ensure namespaces capacity .
4,579
public void setFeature ( String name , boolean state ) throws IllegalArgumentException , IllegalStateException { if ( name == null ) { throw new IllegalArgumentException ( "feature name can not be null" ) ; } if ( FEATURE_NAMES_INTERNED . equals ( name ) ) { namesInterned = state ; } else if ( FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE . equals ( name ) ) { attributeUseApostrophe = state ; } else { throw new IllegalStateException ( "unsupported feature " + name ) ; } }
Sets the feature .
4,580
public boolean getFeature ( String name ) throws IllegalArgumentException { if ( name == null ) { throw new IllegalArgumentException ( "feature name can not be null" ) ; } if ( FEATURE_NAMES_INTERNED . equals ( name ) ) { return namesInterned ; } else if ( FEATURE_SERIALIZER_ATTVALUE_USE_APOSTROPHE . equals ( name ) ) { return attributeUseApostrophe ; } else { return false ; } }
Gets the feature .
4,581
protected void rebuildIndentationBuf ( ) { if ( doIndent == false ) return ; final int maxIndent = 65 ; int bufSize = 0 ; offsetNewLine = 0 ; if ( writeLineSepartor ) { offsetNewLine = lineSeparator . length ( ) ; bufSize += offsetNewLine ; } maxIndentLevel = 0 ; if ( writeIndentation ) { indentationJump = indentationString . length ( ) ; maxIndentLevel = maxIndent / indentationJump ; bufSize += maxIndentLevel * indentationJump ; } if ( indentationBuf == null || indentationBuf . length < bufSize ) { indentationBuf = new char [ bufSize + 8 ] ; } int bufPos = 0 ; if ( writeLineSepartor ) { for ( int i = 0 ; i < lineSeparator . length ( ) ; i ++ ) { indentationBuf [ bufPos ++ ] = lineSeparator . charAt ( i ) ; } } if ( writeIndentation ) { for ( int i = 0 ; i < maxIndentLevel ; i ++ ) { for ( int j = 0 ; j < indentationString . length ( ) ; j ++ ) { indentationBuf [ bufPos ++ ] = indentationString . charAt ( j ) ; } } } }
For maximum efficiency when writing indents the required output is pre - computed This is internal function that recomputes buffer after user requested chnages .
4,582
public void setProperty ( String name , Object value ) throws IllegalArgumentException , IllegalStateException { if ( name == null ) { throw new IllegalArgumentException ( "property name can not be null" ) ; } if ( PROPERTY_SERIALIZER_INDENTATION . equals ( name ) ) { indentationString = ( String ) value ; } else if ( PROPERTY_SERIALIZER_LINE_SEPARATOR . equals ( name ) ) { lineSeparator = ( String ) value ; } else if ( PROPERTY_LOCATION . equals ( name ) ) { location = ( String ) value ; } else { throw new IllegalStateException ( "unsupported property " + name ) ; } writeLineSepartor = lineSeparator != null && lineSeparator . length ( ) > 0 ; writeIndentation = indentationString != null && indentationString . length ( ) > 0 ; doIndent = indentationString != null && ( writeLineSepartor || writeIndentation ) ; rebuildIndentationBuf ( ) ; seenTag = false ; }
Sets the property .
4,583
public void setOutput ( OutputStream os , String encoding ) throws IOException { if ( os == null ) throw new IllegalArgumentException ( "output stream can not be null" ) ; reset ( ) ; if ( encoding != null ) { out = new OutputStreamWriter ( os , encoding ) ; } else { out = new OutputStreamWriter ( os ) ; } }
Sets the output .
4,584
public void startDocument ( String encoding , Boolean standalone ) throws IOException { @ SuppressWarnings ( "unused" ) char apos = attributeUseApostrophe ? '\'' : '"' ; if ( attributeUseApostrophe ) { out . write ( "<?xml version='1.0'" ) ; } else { out . write ( "<?xml version=\"1.0\"" ) ; } if ( encoding != null ) { out . write ( " encoding=" ) ; out . write ( attributeUseApostrophe ? '\'' : '"' ) ; out . write ( encoding ) ; out . write ( attributeUseApostrophe ? '\'' : '"' ) ; } if ( standalone != null ) { out . write ( " standalone=" ) ; out . write ( attributeUseApostrophe ? '\'' : '"' ) ; if ( standalone . booleanValue ( ) ) { out . write ( "yes" ) ; } else { out . write ( "no" ) ; } out . write ( attributeUseApostrophe ? '\'' : '"' ) ; } out . write ( "?>" ) ; }
Start document .
4,585
@ SuppressWarnings ( "unused" ) public void setPrefix ( String prefix , String namespace ) throws IOException { if ( startTagIncomplete ) closeStartTag ( ) ; if ( prefix == null ) { prefix = "" ; } if ( ! namesInterned ) { prefix = prefix . intern ( ) ; } else if ( checkNamesInterned ) { checkInterning ( prefix ) ; } else if ( prefix == null ) { throw new IllegalArgumentException ( "prefix must be not null" + getLocation ( ) ) ; } for ( int i = elNamespaceCount [ depth ] ; i < namespaceEnd ; i ++ ) { if ( prefix == namespacePrefix [ i ] ) { throw new IllegalStateException ( "duplicated prefix " + printable ( prefix ) + getLocation ( ) ) ; } } if ( ! namesInterned ) { namespace = namespace . intern ( ) ; } else if ( checkNamesInterned ) { checkInterning ( namespace ) ; } else if ( namespace == null ) { throw new IllegalArgumentException ( "namespace must be not null" + getLocation ( ) ) ; } if ( namespaceEnd >= namespacePrefix . length ) { ensureNamespacesCapacity ( ) ; } namespacePrefix [ namespaceEnd ] = prefix ; namespaceUri [ namespaceEnd ] = namespace ; ++ namespaceEnd ; setPrefixCalled = true ; }
Sets the prefix .
4,586
protected String getPrefix ( String namespace , boolean generatePrefix , boolean nonEmpty ) { if ( ! namesInterned ) { namespace = namespace . intern ( ) ; } else if ( checkNamesInterned ) { checkInterning ( namespace ) ; } if ( namespace == null ) { throw new IllegalArgumentException ( "namespace must be not null" + getLocation ( ) ) ; } else if ( namespace . length ( ) == 0 ) { throw new IllegalArgumentException ( "default namespace cannot have prefix" + getLocation ( ) ) ; } for ( int i = namespaceEnd - 1 ; i >= 0 ; -- i ) { if ( namespace == namespaceUri [ i ] ) { final String prefix = namespacePrefix [ i ] ; if ( nonEmpty && prefix . length ( ) == 0 ) continue ; for ( int p = namespaceEnd - 1 ; p > i ; -- p ) { if ( prefix == namespacePrefix [ p ] ) continue ; } return prefix ; } } if ( ! generatePrefix ) { return null ; } return generatePrefix ( namespace ) ; }
Gets the prefix .
4,587
private String generatePrefix ( String namespace ) { while ( true ) { ++ autoDeclaredPrefixes ; final String prefix = autoDeclaredPrefixes < precomputedPrefixes . length ? precomputedPrefixes [ autoDeclaredPrefixes ] : ( "n" + autoDeclaredPrefixes ) . intern ( ) ; for ( int i = namespaceEnd - 1 ; i >= 0 ; -- i ) { if ( prefix == namespacePrefix [ i ] ) { continue ; } } if ( namespaceEnd >= namespacePrefix . length ) { ensureNamespacesCapacity ( ) ; } namespacePrefix [ namespaceEnd ] = prefix ; namespaceUri [ namespaceEnd ] = namespace ; ++ namespaceEnd ; return prefix ; } }
Generate prefix .
4,588
protected void closeStartTag ( ) throws IOException { if ( finished ) { throw new IllegalArgumentException ( "trying to write past already finished output" + getLocation ( ) ) ; } if ( seenBracket ) { seenBracket = seenBracketBracket = false ; } if ( startTagIncomplete || setPrefixCalled ) { if ( setPrefixCalled ) { throw new IllegalArgumentException ( "startTag() must be called immediately after setPrefix()" + getLocation ( ) ) ; } if ( ! startTagIncomplete ) { throw new IllegalArgumentException ( "trying to close start tag that is not opened" + getLocation ( ) ) ; } writeNamespaceDeclarations ( ) ; out . write ( '>' ) ; elNamespaceCount [ depth ] = namespaceEnd ; startTagIncomplete = false ; } }
Close start tag .
4,589
private void writeNamespaceDeclarations ( ) throws IOException { for ( int i = elNamespaceCount [ depth - 1 ] ; i < namespaceEnd ; i ++ ) { if ( doIndent && namespaceUri [ i ] . length ( ) > 40 ) { writeIndent ( ) ; out . write ( " " ) ; } if ( "" . equals ( namespacePrefix [ i ] ) ) { out . write ( " xmlns:" ) ; out . write ( namespacePrefix [ i ] ) ; out . write ( '=' ) ; } else { out . write ( " xmlns=" ) ; } out . write ( attributeUseApostrophe ? '\'' : '"' ) ; writeAttributeValue ( namespaceUri [ i ] , out ) ; out . write ( attributeUseApostrophe ? '\'' : '"' ) ; } }
Write namespace declarations .
4,590
public XMLSerializer endTag ( String namespace , String name ) throws IOException { seenBracket = seenBracketBracket = false ; if ( namespace != null ) { if ( ! namesInterned ) { namespace = namespace . intern ( ) ; } else if ( checkNamesInterned ) { checkInterning ( namespace ) ; } } if ( namespace != elNamespace [ depth ] ) { throw new IllegalArgumentException ( "expected namespace " + printable ( elNamespace [ depth ] ) + " and not " + printable ( namespace ) + getLocation ( ) ) ; } if ( name == null ) { throw new IllegalArgumentException ( "end tag name can not be null" + getLocation ( ) ) ; } if ( checkNamesInterned && namesInterned ) { checkInterning ( name ) ; } String startTagName = elName [ depth ] ; if ( ( ! name . equals ( startTagName ) ) ) { throw new IllegalArgumentException ( "expected element name " + printable ( elName [ depth ] ) + " and not " + printable ( name ) + getLocation ( ) ) ; } if ( startTagIncomplete ) { writeNamespaceDeclarations ( ) ; out . write ( "/>" ) ; -- depth ; } else { if ( doIndent && seenTag ) { writeIndent ( ) ; } out . write ( "</" ) ; String startTagPrefix = elPrefix [ depth ] ; if ( startTagPrefix . length ( ) > 0 ) { out . write ( startTagPrefix ) ; out . write ( ':' ) ; } out . write ( name ) ; out . write ( '>' ) ; -- depth ; } namespaceEnd = elNamespaceCount [ depth ] ; startTagIncomplete = false ; seenTag = true ; return this ; }
End tag .
4,591
public void entityRef ( String text ) throws IOException { if ( startTagIncomplete || setPrefixCalled || seenBracket ) closeStartTag ( ) ; if ( doIndent && seenTag ) seenTag = false ; out . write ( '&' ) ; out . write ( text ) ; out . write ( ';' ) ; }
Entity ref .
4,592
public void ignorableWhitespace ( String text ) throws IOException { if ( startTagIncomplete || setPrefixCalled || seenBracket ) closeStartTag ( ) ; if ( doIndent && seenTag ) seenTag = false ; if ( text . length ( ) == 0 ) { throw new IllegalArgumentException ( "empty string is not allowed for ignorable whitespace" + getLocation ( ) ) ; } out . write ( text ) ; }
Ignorable whitespace .
4,593
protected void writeAttributeValue ( String value , Writer out ) throws IOException { final char quot = attributeUseApostrophe ? '\'' : '"' ; final String quotEntity = attributeUseApostrophe ? "&apos;" : "&quot;" ; int pos = 0 ; for ( int i = 0 ; i < value . length ( ) ; i ++ ) { char ch = value . charAt ( i ) ; if ( ch == '&' ) { if ( i > pos ) out . write ( value . substring ( pos , i ) ) ; out . write ( "&amp;" ) ; pos = i + 1 ; } if ( ch == '<' ) { if ( i > pos ) out . write ( value . substring ( pos , i ) ) ; out . write ( "&lt;" ) ; pos = i + 1 ; } else if ( ch == quot ) { if ( i > pos ) out . write ( value . substring ( pos , i ) ) ; out . write ( quotEntity ) ; pos = i + 1 ; } else if ( ch < 32 ) { if ( ch == 13 || ch == 10 || ch == 9 ) { if ( i > pos ) out . write ( value . substring ( pos , i ) ) ; out . write ( "&#" ) ; out . write ( Integer . toString ( ch ) ) ; out . write ( ';' ) ; pos = i + 1 ; } else { if ( TRACE_ESCAPING ) System . err . println ( getClass ( ) . getName ( ) + " DEBUG ATTR value.len=" + value . length ( ) + " " + printable ( value ) ) ; throw new IllegalStateException ( "character " + printable ( ch ) + " (" + Integer . toString ( ch ) + ") is not allowed in output" + getLocation ( ) + " (attr value=" + printable ( value ) + ")" ) ; } } } if ( pos > 0 ) { out . write ( value . substring ( pos ) ) ; } else { out . write ( value ) ; } }
Write attribute value .
4,594
private static void addPrintable ( StringBuffer retval , char ch ) { switch ( ch ) { case '\b' : retval . append ( "\\b" ) ; break ; case '\t' : retval . append ( "\\t" ) ; break ; case '\n' : retval . append ( "\\n" ) ; break ; case '\f' : retval . append ( "\\f" ) ; break ; case '\r' : retval . append ( "\\r" ) ; break ; case '\"' : retval . append ( "\\\"" ) ; break ; case '\'' : retval . append ( "\\\'" ) ; break ; case '\\' : retval . append ( "\\\\" ) ; break ; default : if ( ch < 0x20 || ch > 0x7e ) { final String ss = "0000" + Integer . toString ( ch , 16 ) ; retval . append ( "\\u" + ss . substring ( ss . length ( ) - 4 , ss . length ( ) ) ) ; } else { retval . append ( ch ) ; } } }
Adds the printable .
4,595
public void writeBinary ( byte [ ] value , int start , int length ) throws IOException { text ( Base64Utils . encode ( value , start , length ) ) ; }
Write binary .
4,596
public void writeDecimalAttribute ( String prefix , String namespaceURI , String localName , BigDecimal value ) throws Exception { this . attribute ( namespaceURI , localName , value . toPlainString ( ) ) ; }
Write decimal attribute .
4,597
public void writeIntegerAttribute ( String prefix , String namespaceURI , String localName , BigInteger value ) throws Exception { this . attribute ( namespaceURI , localName , value . toString ( ) ) ; }
Write integer attribute .
4,598
public void writeDoubleAttribute ( String prefix , String namespaceURI , String localName , double value ) throws Exception { this . attribute ( namespaceURI , localName , Double . toString ( value ) ) ; }
Write double attribute .
4,599
public void writeBooleanAttribute ( String prefix , String namespaceURI , String localName , boolean value ) throws Exception { this . attribute ( namespaceURI , localName , Boolean . toString ( value ) ) ; }
Write boolean attribute .