idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
21,800
private static Set < String > getPackages ( List < CodeDependent > cds ) { Set < String > ret = new HashSet < String > ( ) ; if ( cds == null ) { return ret ; } for ( CodeDependent cd : cds ) { ret . add ( cd . pkg ) ; } return ret ; }
Gets the packages .
21,801
public static Object newInstance ( String name ) { try { return forName ( name ) . newInstance ( ) ; } catch ( InstantiationException e ) { throw new IllegalStateException ( e . getMessage ( ) , e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e . getMessage ( ) , e ) ; } }
To new instance by class name
21,802
public static Class < ? > doFormName ( String className ) throws ClassNotFoundException { if ( "boolean" . equals ( className ) ) return boolean . class ; if ( "byte" . equals ( className ) ) return byte . class ; if ( "char" . equals ( className ) ) return char . class ; if ( "short" . equals ( className ) ) return short . class ; if ( "int" . equals ( className ) ) return int . class ; if ( "long" . equals ( className ) ) return long . class ; if ( "float" . equals ( className ) ) return float . class ; if ( "double" . equals ( className ) ) return double . class ; if ( "boolean[]" . equals ( className ) ) return boolean [ ] . class ; if ( "byte[]" . equals ( className ) ) return byte [ ] . class ; if ( "char[]" . equals ( className ) ) return char [ ] . class ; if ( "short[]" . equals ( className ) ) return short [ ] . class ; if ( "int[]" . equals ( className ) ) return int [ ] . class ; if ( "long[]" . equals ( className ) ) return long [ ] . class ; if ( "float[]" . equals ( className ) ) return float [ ] . class ; if ( "double[]" . equals ( className ) ) return double [ ] . class ; try { return arrayForName ( className ) ; } catch ( ClassNotFoundException e ) { if ( className . indexOf ( '.' ) == - 1 ) { try { return arrayForName ( "java.lang." + className ) ; } catch ( ClassNotFoundException e2 ) { } } throw e ; } }
Use Class . forname to initialize class .
21,803
public static Class < ? > getBoxedClass ( Class < ? > type ) { if ( type == boolean . class ) { return Boolean . class ; } else if ( type == char . class ) { return Character . class ; } else if ( type == byte . class ) { return Byte . class ; } else if ( type == short . class ) { return Short . class ; } else if ( type == int . class ) { return Integer . class ; } else if ( type == long . class ) { return Long . class ; } else if ( type == float . class ) { return Float . class ; } else if ( type == double . class ) { return Double . class ; } else { return type ; } }
Get boxed class for primitive type
21,804
public static boolean hasDefaultConstructor ( Class < ? > cls ) { if ( cls == null ) { return false ; } try { cls . getConstructor ( new Class < ? > [ 0 ] ) ; } catch ( NoSuchMethodException e2 ) { return false ; } catch ( SecurityException e2 ) { throw new IllegalArgumentException ( e2 . getMessage ( ) , e2 ) ; } return true ; }
To test class if has default constructor method
21,805
private String getMismatchTypeErroMessage ( FieldType type , Field field ) { return "Type mismatch. @Protobuf required type '" + type . getJavaType ( ) + "' but field type is '" + field . getType ( ) . getSimpleName ( ) + "' of field name '" + field . getName ( ) + "' on class " + field . getDeclaringClass ( ) . getCanonicalName ( ) ; }
get error message info by type not matched .
21,806
public static List < FieldInfo > fetchFieldInfos ( Class cls , boolean ignoreNoAnnotation ) { Annotation annotation = cls . getAnnotation ( ProtobufClass . class ) ; Annotation zipZap = cls . getAnnotation ( EnableZigZap . class ) ; boolean isZipZap = false ; if ( zipZap != null ) { isZipZap = true ; } boolean typeDefined = false ; List < Field > fields = null ; if ( annotation == null ) { fields = FieldUtils . findMatchedFields ( cls , Protobuf . class ) ; if ( fields . isEmpty ( ) && ignoreNoAnnotation ) { throw new IllegalArgumentException ( "Invalid class [" + cls . getName ( ) + "] no field use annotation @" + Protobuf . class . getName ( ) + " at class " + cls . getName ( ) ) ; } } else { typeDefined = true ; fields = FieldUtils . findMatchedFields ( cls , null ) ; } List < FieldInfo > fieldInfos = ProtobufProxyUtils . processDefaultValue ( fields , typeDefined , isZipZap ) ; return fieldInfos ; }
Fetch field infos .
21,807
public static boolean isObjectType ( Class < ? > cls ) { FieldType fieldType = TYPE_MAPPING . get ( cls ) ; if ( fieldType != null ) { return false ; } return true ; }
Checks if is object type .
21,808
public static String processProtobufType ( Class < ? > cls ) { FieldType fieldType = TYPE_MAPPING . get ( cls ) ; if ( fieldType != null ) { return fieldType . getType ( ) ; } return cls . getSimpleName ( ) ; }
Process protobuf type .
21,809
public static String getFiledType ( FieldType type , boolean isList ) { if ( ( type == FieldType . STRING || type == FieldType . BYTES ) && ! isList ) { return "com.google.protobuf.ByteString" ; } String defineType = type . getJavaType ( ) ; if ( isList ) { defineType = "List" ; } return defineType ; }
Gets the filed type .
21,810
public static String getMappedTypeSize ( FieldInfo field , int order , FieldType type , boolean isList , boolean isMap , boolean debug , File path ) { String fieldName = getFieldName ( order ) ; String spath = "null" ; if ( path != null ) { spath = "new java.io.File(\"" + path . getAbsolutePath ( ) . replace ( '\\' , '/' ) + "\")" ; } String typeString = type . getType ( ) . toUpperCase ( ) ; if ( isList ) { return "CodedConstant.computeListSize(" + order + ", " + fieldName + ", FieldType." + typeString + ", " + Boolean . valueOf ( debug ) + ", " + spath + "," + Boolean . valueOf ( field . isPacked ( ) ) + ")" + CodeGenerator . JAVA_LINE_BREAK ; } else if ( isMap ) { String joinedSentence = getMapFieldGenericParameterString ( field ) ; return "CodedConstant.computeMapSize(" + order + ", " + fieldName + ", " + joinedSentence + ")" + CodeGenerator . JAVA_LINE_BREAK ; } if ( type == FieldType . OBJECT ) { return "CodedConstant.computeSize(" + order + "," + fieldName + ", FieldType." + typeString + "," + Boolean . valueOf ( debug ) + "," + spath + ")" + CodeGenerator . JAVA_LINE_BREAK ; } String t = type . getType ( ) ; if ( type == FieldType . STRING || type == FieldType . BYTES ) { t = "bytes" ; } t = capitalize ( t ) ; boolean enumSpecial = false ; if ( type == FieldType . ENUM ) { if ( EnumReadable . class . isAssignableFrom ( field . getField ( ) . getType ( ) ) ) { String clsName = ClassHelper . getInternalName ( field . getField ( ) . getType ( ) . getCanonicalName ( ) ) ; fieldName = "((" + clsName + ") " + fieldName + ").value()" ; enumSpecial = true ; } } if ( ! enumSpecial ) { fieldName = fieldName + type . getToPrimitiveType ( ) ; } return "com.google.protobuf.CodedOutputStream.compute" + t + "Size(" + order + "," + fieldName + ")" + CodeGenerator . JAVA_LINE_BREAK ; }
Gets the mapped type size .
21,811
public static String getMapFieldGenericParameterString ( FieldInfo field ) { FieldType fieldType = ProtobufProxyUtils . TYPE_MAPPING . get ( field . getGenericKeyType ( ) ) ; String keyClass ; String defaultKeyValue ; if ( fieldType == null ) { if ( Enum . class . isAssignableFrom ( field . getGenericKeyType ( ) ) ) { keyClass = WIREFORMAT_CLSNAME + ".ENUM" ; Class < ? > declaringClass = field . getGenericKeyType ( ) ; Field [ ] fields = declaringClass . getFields ( ) ; if ( fields != null && fields . length > 0 ) { defaultKeyValue = ClassHelper . getInternalName ( field . getGenericKeyType ( ) . getCanonicalName ( ) ) + "." + fields [ 0 ] . getName ( ) ; } else { defaultKeyValue = "0" ; } } else { keyClass = WIREFORMAT_CLSNAME + ".MESSAGE" ; boolean hasDefaultConstructor = ClassHelper . hasDefaultConstructor ( field . getGenericKeyType ( ) ) ; if ( ! hasDefaultConstructor ) { throw new IllegalArgumentException ( "Class '" + field . getGenericKeyType ( ) . getCanonicalName ( ) + "' must has default constructor method with no parameters." ) ; } defaultKeyValue = "new " + ClassHelper . getInternalName ( field . getGenericKeyType ( ) . getCanonicalName ( ) ) + "()" ; } } else { keyClass = WIREFORMAT_CLSNAME + "." + fieldType . toString ( ) ; defaultKeyValue = fieldType . getDefaultValue ( ) ; } fieldType = ProtobufProxyUtils . TYPE_MAPPING . get ( field . getGenericeValueType ( ) ) ; String valueClass ; String defaultValueValue ; if ( fieldType == null ) { if ( Enum . class . isAssignableFrom ( field . getGenericeValueType ( ) ) ) { valueClass = WIREFORMAT_CLSNAME + ".ENUM" ; Class < ? > declaringClass = field . getGenericeValueType ( ) ; Field [ ] fields = declaringClass . getFields ( ) ; if ( fields != null && fields . length > 0 ) { defaultValueValue = ClassHelper . getInternalName ( field . getGenericeValueType ( ) . getCanonicalName ( ) ) + "." + fields [ 0 ] . getName ( ) ; } else { defaultValueValue = "0" ; } } else { valueClass = WIREFORMAT_CLSNAME + ".MESSAGE" ; boolean hasDefaultConstructor = ClassHelper . hasDefaultConstructor ( field . getGenericeValueType ( ) ) ; if ( ! hasDefaultConstructor ) { throw new IllegalArgumentException ( "Class '" + field . getGenericeValueType ( ) . getCanonicalName ( ) + "' must has default constructor method with no parameters." ) ; } defaultValueValue = "new " + ClassHelper . getInternalName ( field . getGenericeValueType ( ) . getCanonicalName ( ) ) + "()" ; } } else { valueClass = WIREFORMAT_CLSNAME + "." + fieldType . toString ( ) ; defaultValueValue = fieldType . getDefaultValue ( ) ; } String joinedSentence = keyClass + "," + defaultKeyValue + "," + valueClass + "," + defaultValueValue ; return joinedSentence ; }
Gets the map field generic parameter string .
21,812
public static < K , V > int computeMapSize ( int order , Map < K , V > map , com . google . protobuf . WireFormat . FieldType keyType , K defaultKey , com . google . protobuf . WireFormat . FieldType valueType , V defalutValue ) { int size = 0 ; for ( java . util . Map . Entry < K , V > entry : map . entrySet ( ) ) { com . baidu . bjf . remoting . protobuf . MapEntry < K , V > valuesDefaultEntry = com . baidu . bjf . remoting . protobuf . MapEntry . < K , V > newDefaultInstance ( null , keyType , defaultKey , valueType , defalutValue ) ; com . baidu . bjf . remoting . protobuf . MapEntry < K , V > values = valuesDefaultEntry . newBuilderForType ( ) . setKey ( entry . getKey ( ) ) . setValue ( entry . getValue ( ) ) . build ( ) ; size += com . google . protobuf . CodedOutputStream . computeMessageSize ( order , values ) ; } return size ; }
Compute map size .
21,813
public static < K , V > void putMapValue ( CodedInputStream input , Map < K , V > map , com . google . protobuf . WireFormat . FieldType keyType , K defaultKey , com . google . protobuf . WireFormat . FieldType valueType , V defalutValue ) throws IOException { putMapValue ( input , map , keyType , defaultKey , valueType , defalutValue , null ) ; }
Put map value .
21,814
public static int computeObjectSizeNoTag ( Object o ) { int size = 0 ; if ( o == null ) { return size ; } Class cls = o . getClass ( ) ; Codec target = ProtobufProxy . create ( cls ) ; try { size = target . size ( o ) ; size = size + CodedOutputStream . computeRawVarint32Size ( size ) ; return size ; } catch ( IOException e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } }
Compute object size no tag .
21,815
public static void writeToList ( CodedOutputStream out , int order , FieldType type , List list ) throws IOException { writeToList ( out , order , type , list , false ) ; }
Write to list .
21,816
public static void writeObject ( CodedOutputStream out , int order , FieldType type , Object o , boolean list ) throws IOException { writeObject ( out , order , type , o , list , true ) ; }
Write object .
21,817
public static int getEnumValue ( Enum en ) { if ( en != null ) { int toCompareValue ; if ( en instanceof EnumReadable ) { toCompareValue = ( ( EnumReadable ) en ) . value ( ) ; } else { toCompareValue = en . ordinal ( ) ; } return toCompareValue ; } return - 1 ; }
Gets the enum value .
21,818
public static Object readPrimitiveField ( CodedInputStream input , final WireFormat . FieldType type , boolean checkUtf8 ) throws IOException { switch ( type ) { case DOUBLE : return input . readDouble ( ) ; case FLOAT : return input . readFloat ( ) ; case INT64 : return input . readInt64 ( ) ; case UINT64 : return input . readUInt64 ( ) ; case INT32 : return input . readInt32 ( ) ; case FIXED64 : return input . readFixed64 ( ) ; case FIXED32 : return input . readFixed32 ( ) ; case BOOL : return input . readBool ( ) ; case STRING : if ( checkUtf8 ) { return input . readStringRequireUtf8 ( ) ; } else { return input . readString ( ) ; } case BYTES : return input . readBytes ( ) ; case UINT32 : return input . readUInt32 ( ) ; case SFIXED32 : return input . readSFixed32 ( ) ; case SFIXED64 : return input . readSFixed64 ( ) ; case SINT32 : return input . readSInt32 ( ) ; case SINT64 : return input . readSInt64 ( ) ; case GROUP : throw new IllegalArgumentException ( "readPrimitiveField() cannot handle nested groups." ) ; case MESSAGE : throw new IllegalArgumentException ( "readPrimitiveField() cannot handle embedded messages." ) ; case ENUM : throw new IllegalArgumentException ( "readPrimitiveField() cannot handle enums." ) ; } throw new RuntimeException ( "There is no way to get here, but the compiler thinks otherwise." ) ; }
Read a field of any primitive type for immutable messages from a CodedInputStream . Enums groups and embedded messages are not handled by this method .
21,819
public static void writeElement ( final CodedOutputStream output , final WireFormat . FieldType type , final int number , final Object value ) throws IOException { if ( type == WireFormat . FieldType . GROUP ) { output . writeGroup ( number , ( MessageLite ) value ) ; } else { output . writeTag ( number , getWireFormatForFieldType ( type , false ) ) ; writeElementNoTag ( output , type , value ) ; } }
Write a single tag - value pair to the stream .
21,820
static int getWireFormatForFieldType ( final WireFormat . FieldType type , boolean isPacked ) { if ( isPacked ) { return WireFormat . WIRETYPE_LENGTH_DELIMITED ; } else { return type . getWireType ( ) ; } }
Given a field type return the wire type .
21,821
public static int computeElementSizeNoTag ( final WireFormat . FieldType type , final Object value ) { switch ( type ) { case DOUBLE : return CodedOutputStream . computeDoubleSizeNoTag ( ( Double ) value ) ; case FLOAT : return CodedOutputStream . computeFloatSizeNoTag ( ( Float ) value ) ; case INT64 : return CodedOutputStream . computeInt64SizeNoTag ( ( Long ) value ) ; case UINT64 : return CodedOutputStream . computeUInt64SizeNoTag ( ( Long ) value ) ; case INT32 : return CodedOutputStream . computeInt32SizeNoTag ( ( Integer ) value ) ; case FIXED64 : return CodedOutputStream . computeFixed64SizeNoTag ( ( Long ) value ) ; case FIXED32 : return CodedOutputStream . computeFixed32SizeNoTag ( ( Integer ) value ) ; case BOOL : return CodedOutputStream . computeBoolSizeNoTag ( ( Boolean ) value ) ; case STRING : return CodedOutputStream . computeStringSizeNoTag ( ( String ) value ) ; case GROUP : return CodedOutputStream . computeGroupSizeNoTag ( ( MessageLite ) value ) ; case BYTES : if ( value instanceof ByteString ) { return CodedOutputStream . computeBytesSizeNoTag ( ( ByteString ) value ) ; } else { return CodedOutputStream . computeByteArraySizeNoTag ( ( byte [ ] ) value ) ; } case UINT32 : return CodedOutputStream . computeUInt32SizeNoTag ( ( Integer ) value ) ; case SFIXED32 : return CodedOutputStream . computeSFixed32SizeNoTag ( ( Integer ) value ) ; case SFIXED64 : return CodedOutputStream . computeSFixed64SizeNoTag ( ( Long ) value ) ; case SINT32 : return CodedOutputStream . computeSInt32SizeNoTag ( ( Integer ) value ) ; case SINT64 : return CodedOutputStream . computeSInt64SizeNoTag ( ( Long ) value ) ; case MESSAGE : if ( value instanceof LazyField ) { return CodedOutputStream . computeLazyFieldSizeNoTag ( ( LazyField ) value ) ; } else { return computeObjectSizeNoTag ( value ) ; } case ENUM : if ( value instanceof Internal . EnumLite ) { return CodedOutputStream . computeEnumSizeNoTag ( ( ( Internal . EnumLite ) value ) . getNumber ( ) ) ; } else { if ( value instanceof EnumReadable ) { return CodedOutputStream . computeEnumSizeNoTag ( ( ( EnumReadable ) value ) . value ( ) ) ; } else if ( value instanceof Enum ) { return CodedOutputStream . computeEnumSizeNoTag ( ( ( Enum ) value ) . ordinal ( ) ) ; } return CodedOutputStream . computeEnumSizeNoTag ( ( Integer ) value ) ; } } throw new RuntimeException ( "There is no way to get here, but the compiler thinks otherwise." ) ; }
Compute the number of bytes that would be needed to encode a particular value of arbitrary type excluding tag .
21,822
private static MessageElement getMapKVMessageElements ( String name , MapType mapType ) { MessageElement . Builder ret = MessageElement . builder ( ) ; ret . name ( name ) ; DataType keyType = mapType . keyType ( ) ; Builder fieldBuilder = FieldElement . builder ( ) . name ( "key" ) . tag ( 1 ) ; fieldBuilder . type ( keyType ) . label ( FieldElement . Label . OPTIONAL ) ; ret . addField ( fieldBuilder . build ( ) ) ; DataType valueType = mapType . valueType ( ) ; fieldBuilder = FieldElement . builder ( ) . name ( "value" ) . tag ( 2 ) ; fieldBuilder . type ( valueType ) . label ( FieldElement . Label . OPTIONAL ) ; ret . addField ( fieldBuilder . build ( ) ) ; return ret . build ( ) ; }
Gets the map kv message elements .
21,823
private Object doGetFieldValue ( String fullField , String field , Object object , boolean useCache , Map < String , ReflectInfo > cachedFields ) { Field f ; if ( useCache ) { ReflectInfo info = cachedFields . get ( fullField ) ; if ( info != null ) { return getField ( info . target , info . field ) ; } } int index = field . indexOf ( '.' ) ; if ( index != - 1 ) { String parent = field . substring ( 0 , index ) ; String sub = field . substring ( index + 1 ) ; try { f = FieldUtils . findField ( object . getClass ( ) , parent ) ; if ( f == null ) { throw new RuntimeException ( "No field '" + parent + "' found at class " + object . getClass ( ) . getName ( ) ) ; } f . setAccessible ( true ) ; Object o = f . get ( object ) ; if ( o == null ) { return null ; } return get ( fullField , sub , o ) ; } catch ( Exception e ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } } f = FieldUtils . findField ( object . getClass ( ) , field ) ; if ( f == null ) { throw new RuntimeException ( "No field '" + field + "' found at class " + object . getClass ( ) . getName ( ) ) ; } if ( useCache && ! cachedFields . containsKey ( fullField ) ) { cachedFields . put ( fullField , new ReflectInfo ( f , object ) ) ; } return getField ( object , f ) ; }
Do get field value .
21,824
public static boolean isDebugEnabled ( ) { String debugEnv = System . getenv ( DEBUG_CONTROL ) ; if ( debugEnv != null && Boolean . parseBoolean ( debugEnv ) ) { return true ; } Boolean debug = DEBUG_CONTROLLER . get ( ) ; if ( debug == null ) { debug = false ; } return debug ; }
Checks if is debug enabled .
21,825
private static ICodeGenerator getCodeGenerator ( Class cls ) { if ( ! cls . isMemberClass ( ) ) { try { cls . getConstructor ( new Class < ? > [ 0 ] ) ; } catch ( NoSuchMethodException e2 ) { throw new IllegalArgumentException ( "Class '" + cls . getName ( ) + "' must has default constructor method with no parameters." , e2 ) ; } catch ( SecurityException e2 ) { throw new IllegalArgumentException ( e2 . getMessage ( ) , e2 ) ; } } ICodeGenerator cg = new TemplateCodeGenerator ( cls ) ; return cg ; }
Gets the code generator .
21,826
public static ClassLoader getClassLoader ( Class < ? > cls ) { ClassLoader cl = null ; try { cl = Thread . currentThread ( ) . getContextClassLoader ( ) ; } catch ( Throwable ex ) { } if ( cl == null ) { cl = cls . getClassLoader ( ) ; } return cl ; }
get class loader
21,827
public static < K , V > MapEntry < K , V > newDefaultInstance ( Descriptor descriptor , WireFormat . FieldType keyType , K defaultKey , WireFormat . FieldType valueType , V defaultValue ) { return new MapEntry < K , V > ( descriptor , keyType , defaultKey , valueType , defaultValue ) ; }
Create a default MapEntry instance . A default MapEntry instance should be created only once for each map entry message type . Generated code should store the created default instance and use it later to create new MapEntry messages of the same type .
21,828
private void checkFieldDescriptor ( FieldDescriptor field ) { if ( field . getContainingType ( ) != metadata . descriptor ) { throw new RuntimeException ( "Wrong FieldDescriptor \"" + field . getFullName ( ) + "\" used in message \"" + metadata . descriptor . getFullName ( ) ) ; } }
Check field descriptor .
21,829
public static < K , V > MapField < K , V > emptyMapField ( MapEntry < K , V > defaultEntry ) { return new MapField < K , V > ( defaultEntry , StorageMode . MAP , Collections . < K , V > emptyMap ( ) , null ) ; }
Returns an immutable empty MapField .
21,830
public static < K , V > MapField < K , V > newMapField ( MapEntry < K , V > defaultEntry ) { return new MapField < K , V > ( defaultEntry , StorageMode . MAP , new HashMap < K , V > ( ) , null ) ; }
Creates a new mutable empty MapField .
21,831
public Map < K , V > getMap ( ) { if ( mode == StorageMode . LIST ) { synchronized ( this ) { if ( mode == StorageMode . LIST ) { mapData = convertListToMap ( listData ) ; mode = StorageMode . BOTH ; } } } return Collections . unmodifiableMap ( mapData ) ; }
Returns the content of this MapField as a read - only Map .
21,832
public Map < K , V > getMutableMap ( ) { if ( mode != StorageMode . MAP ) { if ( mode == StorageMode . LIST ) { mapData = convertListToMap ( listData ) ; } listData = null ; mode = StorageMode . MAP ; } return mapData ; }
Gets a mutable Map view of this MapField .
21,833
public MapField < K , V > copy ( ) { return new MapField < K , V > ( converter , StorageMode . MAP , MapFieldLite . copy ( getMap ( ) ) , null ) ; }
Returns a deep copy of this MapField .
21,834
List < Message > getList ( ) { if ( mode == StorageMode . MAP ) { synchronized ( this ) { if ( mode == StorageMode . MAP ) { listData = convertMapToList ( mapData ) ; mode = StorageMode . BOTH ; } } } return Collections . unmodifiableList ( listData ) ; }
Gets the content of this MapField as a read - only List .
21,835
List < Message > getMutableList ( ) { if ( mode != StorageMode . LIST ) { if ( mode == StorageMode . MAP ) { listData = convertMapToList ( mapData ) ; } mapData = null ; mode = StorageMode . LIST ; } return listData ; }
Gets a mutable List view of this MapField .
21,836
private void genImportCode ( StringBuilder code ) { code . append ( "import com.google.protobuf.*" ) . append ( JAVA_LINE_BREAK ) ; code . append ( "import java.io.IOException" ) . append ( JAVA_LINE_BREAK ) ; code . append ( "import com.baidu.bjf.remoting.protobuf.utils.*" ) . append ( JAVA_LINE_BREAK ) ; code . append ( "import com.baidu.bjf.remoting.protobuf.code.*" ) . append ( JAVA_LINE_BREAK ) ; code . append ( "import java.lang.reflect.*" ) . append ( JAVA_LINE_BREAK ) ; code . append ( "import com.baidu.bjf.remoting.protobuf.*" ) . append ( JAVA_LINE_BREAK ) ; code . append ( "import java.util.*" ) . append ( JAVA_LINE_BREAK ) ; if ( ! StringUtils . isEmpty ( getPackage ( ) ) ) { code . append ( "import " ) . append ( ClassHelper . getInternalName ( cls . getCanonicalName ( ) ) ) . append ( JAVA_LINE_BREAK ) ; } }
generate import code
21,837
public static String descriptorMethodSource ( Class cls ) { String descriptorClsName = ClassHelper . getInternalName ( Descriptor . class . getCanonicalName ( ) ) ; String code = "if (this.descriptor != null) {" + ClassCode . LINE_BREAK + "return this.descriptor;" + ClassCode . LINE_BREAK + "}" + ClassCode . LINE_BREAK + "%s descriptor = CodedConstant.getDescriptor(%s);" + ClassCode . LINE_BREAK + "return (this.descriptor = descriptor);" ; return String . format ( code , descriptorClsName , ClassHelper . getInternalName ( cls . getCanonicalName ( ) ) + CodeGenerator . JAVA_CLASS_FILE_SUFFIX ) ; }
Get getDescriptor method source by template .
21,838
private static List < Class < ? > > createEnumClasses ( Map < String , EnumElement > enumTypes , Map < String , String > packageMapping , boolean generateSouceOnly , File sourceOutputDir , Set < String > compiledClass , Map < String , String > mappedUniName , boolean isUniName ) { List < Class < ? > > ret = new ArrayList < Class < ? > > ( ) ; Set < String > enumNames = new HashSet < String > ( ) ; Collection < EnumElement > enums = enumTypes . values ( ) ; for ( EnumElement enumType : enums ) { String name = enumType . name ( ) ; if ( enumNames . contains ( name ) ) { continue ; } enumNames . add ( name ) ; String packageName = packageMapping . get ( name ) ; Class cls = checkClass ( packageName , enumType , mappedUniName , isUniName ) ; if ( cls != null ) { ret . add ( cls ) ; continue ; } CodeDependent codeDependent = createCodeByType ( enumType , true , packageName , mappedUniName , isUniName ) ; compiledClass . add ( codeDependent . name ) ; compiledClass . add ( packageName + PACKAGE_SPLIT_CHAR + codeDependent . name ) ; if ( ! generateSouceOnly ) { Class < ? > newClass = JDKCompilerHelper . getJdkCompiler ( ) . compile ( codeDependent . getClassName ( ) , codeDependent . code , ProtobufIDLProxy . class . getClassLoader ( ) , null , - 1 ) ; ret . add ( newClass ) ; } else { writeSourceCode ( codeDependent , sourceOutputDir ) ; } } return ret ; }
Creates the enum classes .
21,839
private static String getTypeName ( FieldElement field ) { DataType type = field . type ( ) ; return type . toString ( ) ; }
Gets the type name .
21,840
@ SuppressWarnings ( { "unchecked" , "cast" } ) public static < K , V > MapFieldLite < K , V > emptyMapField ( ) { return ( MapFieldLite < K , V > ) EMPTY_MAP_FIELD ; }
Returns an singleton immutable empty MapFieldLite instance .
21,841
public void mergeFrom ( MapFieldLite < K , V > other ) { ensureMutable ( ) ; if ( ! other . isEmpty ( ) ) { putAll ( other ) ; } }
Merge from .
21,842
private void genImportCode ( ClassCode code ) { code . importClass ( "java.util.*" ) ; code . importClass ( "java.io.IOException" ) ; code . importClass ( "java.lang.reflect.*" ) ; code . importClass ( "com.baidu.bjf.remoting.protobuf.code.*" ) ; code . importClass ( "com.baidu.bjf.remoting.protobuf.utils.*" ) ; code . importClass ( "com.baidu.bjf.remoting.protobuf.*" ) ; code . importClass ( "com.google.protobuf.*" ) ; if ( ! StringUtils . isEmpty ( getPackage ( ) ) ) { code . importClass ( ClassHelper . getInternalName ( cls . getCanonicalName ( ) ) ) ; } }
generate import code .
21,843
private MethodCode getDecodeMethodCode ( ) { MethodCode mc = new MethodCode ( ) ; mc . setName ( "decode" ) ; mc . setScope ( ClassCode . SCOPE_PUBLIC ) ; mc . setReturnType ( ClassHelper . getInternalName ( cls . getCanonicalName ( ) ) ) ; mc . addParameter ( "byte[]" , "bb" ) ; mc . addException ( "IOException" ) ; mc . appendLineCode1 ( "CodedInputStream input = CodedInputStream.newInstance(bb, 0, bb.length)" ) ; getParseBytesMethodCode ( mc ) ; return mc ; }
Gets the decode method code .
21,844
private MethodCode getGetDescriptorMethodCode ( ) { String descriptorClsName = ClassHelper . getInternalName ( Descriptor . class . getCanonicalName ( ) ) ; MethodCode mc = new MethodCode ( ) ; mc . setName ( "getDescriptor" ) ; mc . setReturnType ( descriptorClsName ) ; mc . setScope ( ClassCode . SCOPE_PUBLIC ) ; mc . addException ( "IOException" ) ; String methodSource = CodeTemplate . descriptorMethodSource ( cls ) ; mc . appendLineCode0 ( methodSource ) ; return mc ; }
Gets the gets the descriptor method code .
21,845
private MethodCode getWriteToMethodCode ( ) { MethodCode mc = new MethodCode ( ) ; mc . setName ( "writeTo" ) ; mc . setReturnType ( "void" ) ; mc . setScope ( ClassCode . SCOPE_PUBLIC ) ; mc . addParameter ( ClassHelper . getInternalName ( cls . getCanonicalName ( ) ) , "t" ) ; mc . addParameter ( "CodedOutputStream" , "output" ) ; mc . addException ( "IOException" ) ; Set < Integer > orders = new HashSet < Integer > ( ) ; for ( FieldInfo field : fields ) { boolean isList = field . isList ( ) ; if ( ! isList ) { checkType ( field . getFieldType ( ) , field . getField ( ) ) ; } if ( orders . contains ( field . getOrder ( ) ) ) { throw new IllegalArgumentException ( "Field order '" + field . getOrder ( ) + "' on field" + field . getField ( ) . getName ( ) + " already exsit." ) ; } mc . appendLineCode0 ( CodedConstant . getMappedTypeDefined ( field . getOrder ( ) , field . getFieldType ( ) , getAccessByField ( "t" , field . getField ( ) , cls ) , isList ) ) ; if ( field . isRequired ( ) ) { mc . appendLineCode0 ( CodedConstant . getRequiredCheck ( field . getOrder ( ) , field . getField ( ) ) ) ; } } for ( FieldInfo field : fields ) { boolean isList = field . isList ( ) ; mc . appendLineCode0 ( CodedConstant . getMappedWriteCode ( field , "output" , field . getOrder ( ) , field . getFieldType ( ) , isList ) ) ; } mc . appendLineCode1 ( "output.flush()" ) ; return mc ; }
Gets the write to method code .
21,846
private MethodCode getSizeMethodCode ( ) { MethodCode mc = new MethodCode ( ) ; mc . setName ( "size" ) ; mc . setScope ( ClassCode . SCOPE_PUBLIC ) ; mc . setReturnType ( "int" ) ; mc . addParameter ( ClassHelper . getInternalName ( cls . getCanonicalName ( ) ) , "t" ) ; mc . addException ( "IOException" ) ; mc . appendLineCode1 ( "int size = 0" ) ; Set < Integer > orders = new HashSet < Integer > ( ) ; for ( FieldInfo field : fields ) { boolean isList = field . isList ( ) ; if ( ! isList ) { checkType ( field . getFieldType ( ) , field . getField ( ) ) ; } if ( orders . contains ( field . getOrder ( ) ) ) { throw new IllegalArgumentException ( "Field order '" + field . getOrder ( ) + "' on field" + field . getField ( ) . getName ( ) + " already exsit." ) ; } mc . appendLineCode0 ( CodedConstant . getMappedTypeDefined ( field . getOrder ( ) , field . getFieldType ( ) , getAccessByField ( "t" , field . getField ( ) , cls ) , isList ) ) ; StringBuilder code = new StringBuilder ( ) ; code . append ( "if (!CodedConstant.isNull(" ) . append ( getAccessByField ( "t" , field . getField ( ) , cls ) ) . append ( "))" ) . append ( "{" ) ; mc . appendLineCode0 ( code . toString ( ) ) ; code . setLength ( 0 ) ; code . append ( "size += " ) ; code . append ( CodedConstant . getMappedTypeSize ( field , field . getOrder ( ) , field . getFieldType ( ) , isList , debug , outputPath ) ) ; code . append ( "}" ) ; mc . appendLineCode0 ( code . toString ( ) ) ; if ( field . isRequired ( ) ) { mc . appendLineCode0 ( CodedConstant . getRequiredCheck ( field . getOrder ( ) , field . getField ( ) ) ) ; } } mc . appendLineCode1 ( "return size" ) ; return mc ; }
Gets the size method code .
21,847
protected String getAccessByField ( String target , Field field , Class < ? > cls ) { if ( field . getModifiers ( ) == Modifier . PUBLIC ) { return target + ClassHelper . PACKAGE_SEPARATOR + field . getName ( ) ; } String getter ; if ( "boolean" . equalsIgnoreCase ( field . getType ( ) . getCanonicalName ( ) ) ) { getter = "is" + CodedConstant . capitalize ( field . getName ( ) ) ; } else { getter = "get" + CodedConstant . capitalize ( field . getName ( ) ) ; } try { cls . getMethod ( getter , new Class < ? > [ 0 ] ) ; return target + ClassHelper . PACKAGE_SEPARATOR + getter + "()" ; } catch ( Exception e ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( e . getMessage ( ) , e ) ; } } String type = field . getType ( ) . getCanonicalName ( ) ; if ( "[B" . equals ( type ) || "[Ljava.lang.Byte;" . equals ( type ) || "java.lang.Byte[]" . equals ( type ) ) { type = "byte[]" ; } String code = "(" + FieldUtils . toObjectType ( type ) + ") " ; code += "FieldUtils.getField(" + target + ", \"" + field . getName ( ) + "\")" ; return code ; }
get field access code .
21,848
public static void printCode ( String code , String desc ) { System . out . println ( "--------------------------" + desc + " begin--------------------------" ) ; System . out . println ( code ) ; System . out . println ( "--------------------------" + desc + " end--------------------------" ) ; }
print code to console
21,849
public static PrivateKeyEntry getFirstPrivateKeyEntryFromP12InputStream ( final InputStream p12InputStream , final String password ) throws KeyStoreException , IOException { Objects . requireNonNull ( password , "Password may be blank, but must not be null." ) ; final KeyStore keyStore = KeyStore . getInstance ( "PKCS12" ) ; try { keyStore . load ( p12InputStream , password . toCharArray ( ) ) ; } catch ( NoSuchAlgorithmException | CertificateException e ) { throw new KeyStoreException ( e ) ; } final Enumeration < String > aliases = keyStore . aliases ( ) ; final KeyStore . PasswordProtection passwordProtection = new KeyStore . PasswordProtection ( password . toCharArray ( ) ) ; while ( aliases . hasMoreElements ( ) ) { final String alias = aliases . nextElement ( ) ; KeyStore . Entry entry ; try { try { entry = keyStore . getEntry ( alias , passwordProtection ) ; } catch ( final UnsupportedOperationException e ) { entry = keyStore . getEntry ( alias , null ) ; } } catch ( final UnrecoverableEntryException | NoSuchAlgorithmException e ) { throw new KeyStoreException ( e ) ; } if ( entry instanceof KeyStore . PrivateKeyEntry ) { return ( PrivateKeyEntry ) entry ; } } throw new KeyStoreException ( "Key store did not contain any private key entries." ) ; }
Returns the first private key entry found in the given keystore . If more than one private key is present the key that is returned is undefined .
21,850
public Future < Void > start ( final int port ) { final ChannelFuture channelFuture = this . bootstrap . bind ( port ) ; this . allChannels . add ( channelFuture . channel ( ) ) ; return channelFuture ; }
Starts this mock server and listens for traffic on the given port .
21,851
@ SuppressWarnings ( "unchecked" ) static Class < ? extends ServerChannel > getServerSocketChannelClass ( final EventLoopGroup eventLoopGroup ) { Objects . requireNonNull ( eventLoopGroup ) ; final String serverSocketChannelClassName = SERVER_SOCKET_CHANNEL_CLASSES . get ( eventLoopGroup . getClass ( ) . getName ( ) ) ; if ( serverSocketChannelClassName == null ) { throw new IllegalArgumentException ( "No server socket channel class found for event loop group type: " + eventLoopGroup . getClass ( ) . getName ( ) ) ; } try { return Class . forName ( serverSocketChannelClassName ) . asSubclass ( ServerChannel . class ) ; } catch ( final ClassNotFoundException e ) { throw new IllegalArgumentException ( e ) ; } }
Returns a server socket channel class suitable for specified event loop group .
21,852
public Future < Channel > create ( final Promise < Channel > channelReadyPromise ) { final long delay = this . currentDelaySeconds . get ( ) ; channelReadyPromise . addListener ( new GenericFutureListener < Future < Channel > > ( ) { public void operationComplete ( final Future < Channel > future ) { final long updatedDelay = future . isSuccess ( ) ? 0 : Math . max ( Math . min ( delay * 2 , MAX_CONNECT_DELAY_SECONDS ) , MIN_CONNECT_DELAY_SECONDS ) ; ApnsChannelFactory . this . currentDelaySeconds . compareAndSet ( delay , updatedDelay ) ; } } ) ; this . bootstrapTemplate . config ( ) . group ( ) . schedule ( new Runnable ( ) { public void run ( ) { final Bootstrap bootstrap = ApnsChannelFactory . this . bootstrapTemplate . clone ( ) . channelFactory ( new AugmentingReflectiveChannelFactory < > ( ClientChannelClassUtil . getSocketChannelClass ( ApnsChannelFactory . this . bootstrapTemplate . config ( ) . group ( ) ) , CHANNEL_READY_PROMISE_ATTRIBUTE_KEY , channelReadyPromise ) ) ; final ChannelFuture connectFuture = bootstrap . connect ( ) ; connectFuture . addListener ( new GenericFutureListener < ChannelFuture > ( ) { public void operationComplete ( final ChannelFuture future ) { if ( ! future . isSuccess ( ) ) { tryFailureAndLogRejectedCause ( channelReadyPromise , future . cause ( ) ) ; } } } ) ; connectFuture . channel ( ) . closeFuture ( ) . addListener ( new GenericFutureListener < ChannelFuture > ( ) { public void operationComplete ( final ChannelFuture future ) { channelReadyPromise . tryFailure ( new IllegalStateException ( "Channel closed before HTTP/2 preface completed." ) ) ; } } ) ; } } , delay , TimeUnit . SECONDS ) ; return channelReadyPromise ; }
Creates and connects a new channel . The initial connection attempt may be delayed to accommodate exponential back - off requirements .
21,853
public Future < Void > destroy ( final Channel channel , final Promise < Void > promise ) { channel . close ( ) . addListener ( new PromiseNotifier < > ( promise ) ) ; return promise ; }
Destroys a channel by closing it .
21,854
public boolean verifySignature ( final ApnsVerificationKey verificationKey ) throws NoSuchAlgorithmException , InvalidKeyException , SignatureException { if ( ! this . header . getKeyId ( ) . equals ( verificationKey . getKeyId ( ) ) ) { return false ; } if ( ! this . claims . getIssuer ( ) . equals ( verificationKey . getTeamId ( ) ) ) { return false ; } final byte [ ] headerAndClaimsBytes ; final String headerJson = GSON . toJson ( this . header ) ; final String claimsJson = GSON . toJson ( this . claims ) ; final String encodedHeaderAndClaims = encodeUnpaddedBase64UrlString ( headerJson . getBytes ( StandardCharsets . US_ASCII ) ) + '.' + encodeUnpaddedBase64UrlString ( claimsJson . getBytes ( StandardCharsets . US_ASCII ) ) ; headerAndClaimsBytes = encodedHeaderAndClaims . getBytes ( StandardCharsets . US_ASCII ) ; final Signature signature = Signature . getInstance ( ApnsKey . APNS_SIGNATURE_ALGORITHM ) ; signature . initVerify ( verificationKey ) ; signature . update ( headerAndClaimsBytes ) ; return signature . verify ( this . signatureBytes ) ; }
Verifies the cryptographic signature of this authentication token .
21,855
public void handleWriteFailure ( final ApnsClient apnsClient , final long notificationId ) { this . notificationStartTimes . remove ( notificationId ) ; this . writeFailures . increment ( ) ; }
Records a failed attempt to send a notification and updates metrics accordingly .
21,856
public static ApnsVerificationKey loadFromInputStream ( final InputStream inputStream , final String teamId , final String keyId ) throws IOException , NoSuchAlgorithmException , InvalidKeyException { final ECPublicKey verificationKey ; { final String base64EncodedPublicKey ; { final StringBuilder publicKeyBuilder = new StringBuilder ( ) ; final BufferedReader reader = new BufferedReader ( new InputStreamReader ( inputStream ) ) ; boolean haveReadHeader = false ; boolean haveReadFooter = false ; for ( String line ; ( line = reader . readLine ( ) ) != null ; ) { if ( ! haveReadHeader ) { if ( line . contains ( "BEGIN PUBLIC KEY" ) ) { haveReadHeader = true ; } } else { if ( line . contains ( "END PUBLIC KEY" ) ) { haveReadFooter = true ; break ; } else { publicKeyBuilder . append ( line ) ; } } } if ( ! ( haveReadHeader && haveReadFooter ) ) { throw new IOException ( "Could not find public key header/footer" ) ; } base64EncodedPublicKey = publicKeyBuilder . toString ( ) ; } final byte [ ] keyBytes = decodeBase64EncodedString ( base64EncodedPublicKey ) ; final X509EncodedKeySpec keySpec = new X509EncodedKeySpec ( keyBytes ) ; final KeyFactory keyFactory = KeyFactory . getInstance ( "EC" ) ; try { verificationKey = ( ECPublicKey ) keyFactory . generatePublic ( keySpec ) ; } catch ( InvalidKeySpecException e ) { throw new InvalidKeyException ( e ) ; } } return new ApnsVerificationKey ( keyId , teamId , verificationKey ) ; }
Loads a verification key from the given input stream .
21,857
public static ApnsSigningKey loadFromInputStream ( final InputStream inputStream , final String teamId , final String keyId ) throws IOException , NoSuchAlgorithmException , InvalidKeyException { final ECPrivateKey signingKey ; { final String base64EncodedPrivateKey ; { final StringBuilder privateKeyBuilder = new StringBuilder ( ) ; final BufferedReader reader = new BufferedReader ( new InputStreamReader ( inputStream ) ) ; boolean haveReadHeader = false ; boolean haveReadFooter = false ; for ( String line ; ( line = reader . readLine ( ) ) != null ; ) { if ( ! haveReadHeader ) { if ( line . contains ( "BEGIN PRIVATE KEY" ) ) { haveReadHeader = true ; } } else { if ( line . contains ( "END PRIVATE KEY" ) ) { haveReadFooter = true ; break ; } else { privateKeyBuilder . append ( line ) ; } } } if ( ! ( haveReadHeader && haveReadFooter ) ) { throw new IOException ( "Could not find private key header/footer" ) ; } base64EncodedPrivateKey = privateKeyBuilder . toString ( ) ; } final byte [ ] keyBytes = decodeBase64EncodedString ( base64EncodedPrivateKey ) ; final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec ( keyBytes ) ; final KeyFactory keyFactory = KeyFactory . getInstance ( "EC" ) ; try { signingKey = ( ECPrivateKey ) keyFactory . generatePrivate ( keySpec ) ; } catch ( InvalidKeySpecException e ) { throw new InvalidKeyException ( e ) ; } } return new ApnsSigningKey ( keyId , teamId , signingKey ) ; }
Loads a signing key from the given input stream .
21,858
public PushNotificationHandler buildHandler ( final SSLSession sslSession ) { return new PushNotificationHandler ( ) { public void handlePushNotification ( final Http2Headers headers , final ByteBuf payload ) { } } ; }
Constructs a new push notification handler that unconditionally accepts all push notifications .
21,859
void release ( final Channel channel ) { if ( this . executor . inEventLoop ( ) ) { this . releaseWithinEventExecutor ( channel ) ; } else { this . executor . submit ( new Runnable ( ) { public void run ( ) { ApnsChannelPool . this . releaseWithinEventExecutor ( channel ) ; } } ) ; } }
Returns a previously - acquired channel to the pool .
21,860
public Future < Void > close ( ) { return this . allChannels . close ( ) . addListener ( new GenericFutureListener < Future < Void > > ( ) { public void operationComplete ( final Future < Void > future ) throws Exception { ApnsChannelPool . this . isClosed = true ; if ( ApnsChannelPool . this . channelFactory instanceof Closeable ) { ( ( Closeable ) ApnsChannelPool . this . channelFactory ) . close ( ) ; } for ( final Promise < Channel > acquisitionPromise : ApnsChannelPool . this . pendingAcquisitionPromises ) { acquisitionPromise . tryFailure ( POOL_CLOSED_EXCEPTION ) ; } } } ) ; }
Shuts down this channel pool and releases all retained resources .
21,861
public T build ( ) throws SSLException { final SslContext sslContext ; { final SslProvider sslProvider ; if ( OpenSsl . isAvailable ( ) ) { log . info ( "Native SSL provider is available; will use native provider." ) ; sslProvider = SslProvider . OPENSSL ; } else { log . info ( "Native SSL provider not available; will use JDK SSL provider." ) ; sslProvider = SslProvider . JDK ; } final SslContextBuilder sslContextBuilder ; if ( this . certificateChain != null && this . privateKey != null ) { sslContextBuilder = SslContextBuilder . forServer ( this . privateKey , this . privateKeyPassword , this . certificateChain ) ; } else if ( this . certificateChainPemFile != null && this . privateKeyPkcs8File != null ) { sslContextBuilder = SslContextBuilder . forServer ( this . certificateChainPemFile , this . privateKeyPkcs8File , this . privateKeyPassword ) ; } else if ( this . certificateChainInputStream != null && this . privateKeyPkcs8InputStream != null ) { sslContextBuilder = SslContextBuilder . forServer ( this . certificateChainInputStream , this . privateKeyPkcs8InputStream , this . privateKeyPassword ) ; } else { throw new IllegalStateException ( "Must specify server credentials before building a mock server." ) ; } sslContextBuilder . sslProvider ( sslProvider ) . ciphers ( Http2SecurityUtil . CIPHERS , SupportedCipherSuiteFilter . INSTANCE ) . clientAuth ( ClientAuth . OPTIONAL ) ; if ( this . trustedClientCertificatePemFile != null ) { sslContextBuilder . trustManager ( this . trustedClientCertificatePemFile ) ; } else if ( this . trustedClientCertificateInputStream != null ) { sslContextBuilder . trustManager ( this . trustedClientCertificateInputStream ) ; } else if ( this . trustedClientCertificates != null ) { sslContextBuilder . trustManager ( this . trustedClientCertificates ) ; } if ( this . useAlpn ) { sslContextBuilder . applicationProtocolConfig ( new ApplicationProtocolConfig ( ApplicationProtocolConfig . Protocol . ALPN , ApplicationProtocolConfig . SelectorFailureBehavior . NO_ADVERTISE , ApplicationProtocolConfig . SelectedListenerFailureBehavior . ACCEPT , ApplicationProtocolNames . HTTP_2 ) ) ; } sslContext = sslContextBuilder . build ( ) ; } final T server = this . constructServer ( sslContext ) ; if ( sslContext instanceof ReferenceCounted ) { ( ( ReferenceCounted ) sslContext ) . release ( ) ; } return server ; }
Constructs a new server with the previously - set configuration .
21,862
static Class < ? extends SocketChannel > getSocketChannelClass ( final EventLoopGroup eventLoopGroup ) { Objects . requireNonNull ( eventLoopGroup ) ; final String socketChannelClassName = SOCKET_CHANNEL_CLASSES . get ( eventLoopGroup . getClass ( ) . getName ( ) ) ; if ( socketChannelClassName == null ) { throw new IllegalArgumentException ( "No socket channel class found for event loop group type: " + eventLoopGroup . getClass ( ) . getName ( ) ) ; } try { return Class . forName ( socketChannelClassName ) . asSubclass ( SocketChannel . class ) ; } catch ( final ClassNotFoundException e ) { throw new IllegalArgumentException ( e ) ; } }
Returns a socket channel class suitable for specified event loop group .
21,863
static Class < ? extends DatagramChannel > getDatagramChannelClass ( final EventLoopGroup eventLoopGroup ) { Objects . requireNonNull ( eventLoopGroup ) ; final String datagramChannelClassName = DATAGRAM_CHANNEL_CLASSES . get ( eventLoopGroup . getClass ( ) . getName ( ) ) ; if ( datagramChannelClassName == null ) { throw new IllegalArgumentException ( "No datagram channel class found for event loop group type: " + eventLoopGroup . getClass ( ) . getName ( ) ) ; } try { return Class . forName ( datagramChannelClassName ) . asSubclass ( DatagramChannel . class ) ; } catch ( final ClassNotFoundException e ) { throw new IllegalArgumentException ( e ) ; } }
Returns a datagram channel class suitable for specified event loop group .
21,864
public void setCursorPosition ( TerminalPosition position ) { if ( position == null ) { this . cursorPosition = null ; return ; } if ( position . getColumn ( ) < 0 ) { position = position . withColumn ( 0 ) ; } if ( position . getRow ( ) < 0 ) { position = position . withRow ( 0 ) ; } if ( position . getColumn ( ) >= terminalSize . getColumns ( ) ) { position = position . withColumn ( terminalSize . getColumns ( ) - 1 ) ; } if ( position . getRow ( ) >= terminalSize . getRows ( ) ) { position = position . withRow ( terminalSize . getRows ( ) - 1 ) ; } this . cursorPosition = position ; }
Moves the current cursor position or hides it . If the cursor is hidden and given a new position it will be visible after this method call .
21,865
public void scrollLines ( int firstLine , int lastLine , int distance ) { getBackBuffer ( ) . scrollLines ( firstLine , lastLine , distance ) ; }
Performs the scrolling on its back - buffer .
21,866
synchronized TerminalPosition waitForCursorPositionReport ( ) throws IOException { long startTime = System . currentTimeMillis ( ) ; TerminalPosition cursorPosition = lastReportedCursorPosition ; while ( cursorPosition == null ) { if ( System . currentTimeMillis ( ) - startTime > 5000 ) { return null ; } KeyStroke keyStroke = readInput ( false , false ) ; if ( keyStroke != null ) { keyQueue . add ( keyStroke ) ; } else { try { Thread . sleep ( 1 ) ; } catch ( InterruptedException ignored ) { } } cursorPosition = lastReportedCursorPosition ; } return cursorPosition ; }
Waits for up to 5 seconds for a terminal cursor position report to appear in the input stream . If the timeout expires it will return null . You should have sent the cursor position query already before calling this method .
21,867
public MessageDialogBuilder setExtraWindowHints ( Collection < Window . Hint > extraWindowHints ) { this . extraWindowHints . clear ( ) ; this . extraWindowHints . addAll ( extraWindowHints ) ; return this ; }
Assigns a set of extra window hints that you want the built dialog to have
21,868
public static WaitingDialog showDialog ( WindowBasedTextGUI textGUI , String title , String text ) { WaitingDialog waitingDialog = createDialog ( title , text ) ; waitingDialog . showDialog ( textGUI , false ) ; return waitingDialog ; }
Creates and displays a waiting dialog without blocking for it to finish
21,869
public static LayoutData createHorizontallyFilledLayoutData ( int horizontalSpan ) { return createLayoutData ( Alignment . FILL , Alignment . CENTER , true , false , horizontalSpan , 1 ) ; }
This is a shortcut method that will create a grid layout data object that will expand its cell as much as is can horizontally and make the component occupy the whole area horizontally and center it vertically
21,870
public static LayoutData createHorizontallyEndAlignedLayoutData ( int horizontalSpan ) { return createLayoutData ( Alignment . END , Alignment . CENTER , true , false , horizontalSpan , 1 ) ; }
This is a shortcut method that will create a grid layout data object that will expand its cell as much as is can vertically and make the component occupy the whole area vertically and center it horizontally
21,871
public synchronized CheckBox setChecked ( final boolean checked ) { this . checked = checked ; runOnGUIThreadIfExistsOtherwiseRunDirect ( new Runnable ( ) { public void run ( ) { for ( Listener listener : listeners ) { listener . onStatusChanged ( checked ) ; } } } ) ; invalidate ( ) ; return this ; }
Programmatically updated the check box to a particular checked state
21,872
public synchronized CheckBox setLabel ( String label ) { if ( label == null ) { throw new IllegalArgumentException ( "Cannot set CheckBox label to null" ) ; } this . label = label ; invalidate ( ) ; return this ; }
Updates the label of the checkbox
21,873
public CheckBox addListener ( Listener listener ) { if ( listener != null && ! listeners . contains ( listener ) ) { listeners . add ( listener ) ; } return this ; }
Adds a listener to this check box so that it will be notificed on certain user actions
21,874
synchronized void startBlinkTimer ( ) { if ( blinkTimer != null ) { return ; } blinkTimer = new Timer ( "LanternaTerminalBlinkTimer" , true ) ; blinkTimer . schedule ( new TimerTask ( ) { public void run ( ) { blinkOn = ! blinkOn ; if ( hasBlinkingText ) { repaint ( ) ; } } } , deviceConfiguration . getBlinkLengthInMilliSeconds ( ) , deviceConfiguration . getBlinkLengthInMilliSeconds ( ) ) ; }
Start the timer that triggers blinking
21,875
synchronized Dimension getPreferredSize ( ) { return new Dimension ( getFontWidth ( ) * virtualTerminal . getTerminalSize ( ) . getColumns ( ) , getFontHeight ( ) * virtualTerminal . getTerminalSize ( ) . getRows ( ) ) ; }
Calculates the preferred size of this terminal
21,876
private void clearBackBuffer ( ) { if ( backbuffer != null ) { Graphics2D graphics = backbuffer . createGraphics ( ) ; Color backgroundColor = colorConfiguration . toAWTColor ( TextColor . ANSI . DEFAULT , false , false ) ; graphics . setColor ( backgroundColor ) ; graphics . fillRect ( 0 , 0 , getWidth ( ) , getHeight ( ) ) ; graphics . dispose ( ) ; } }
Clears out the back buffer and the resets the visual state so next paint operation will do a full repaint of everything
21,877
public static SimpleTheme makeTheme ( boolean activeIsBold , TextColor baseForeground , TextColor baseBackground , TextColor editableForeground , TextColor editableBackground , TextColor selectedForeground , TextColor selectedBackground , TextColor guiBackground ) { SGR [ ] activeStyle = activeIsBold ? new SGR [ ] { SGR . BOLD } : new SGR [ 0 ] ; SimpleTheme theme = new SimpleTheme ( baseForeground , baseBackground ) ; theme . getDefaultDefinition ( ) . setSelected ( baseBackground , baseForeground , activeStyle ) ; theme . getDefaultDefinition ( ) . setActive ( selectedForeground , selectedBackground , activeStyle ) ; theme . addOverride ( AbstractBorder . class , baseForeground , baseBackground ) . setSelected ( baseForeground , baseBackground , activeStyle ) ; theme . addOverride ( AbstractListBox . class , baseForeground , baseBackground ) . setSelected ( selectedForeground , selectedBackground , activeStyle ) ; theme . addOverride ( Button . class , baseForeground , baseBackground ) . setActive ( selectedForeground , selectedBackground , activeStyle ) . setSelected ( selectedForeground , selectedBackground , activeStyle ) ; theme . addOverride ( CheckBox . class , baseForeground , baseBackground ) . setActive ( selectedForeground , selectedBackground , activeStyle ) . setPreLight ( selectedForeground , selectedBackground , activeStyle ) . setSelected ( selectedForeground , selectedBackground , activeStyle ) ; theme . addOverride ( CheckBoxList . class , baseForeground , baseBackground ) . setActive ( selectedForeground , selectedBackground , activeStyle ) ; theme . addOverride ( ComboBox . class , baseForeground , baseBackground ) . setActive ( editableForeground , editableBackground , activeStyle ) . setPreLight ( editableForeground , editableBackground ) ; theme . addOverride ( DefaultWindowDecorationRenderer . class , baseForeground , baseBackground ) . setActive ( baseForeground , baseBackground , activeStyle ) ; theme . addOverride ( GUIBackdrop . class , baseForeground , guiBackground ) ; theme . addOverride ( RadioBoxList . class , baseForeground , baseBackground ) . setActive ( selectedForeground , selectedBackground , activeStyle ) ; theme . addOverride ( Table . class , baseForeground , baseBackground ) . setActive ( editableForeground , editableBackground , activeStyle ) . setSelected ( baseForeground , baseBackground ) ; theme . addOverride ( TextBox . class , editableForeground , editableBackground ) . setActive ( editableForeground , editableBackground , activeStyle ) . setSelected ( editableForeground , editableBackground , activeStyle ) ; theme . setWindowPostRenderer ( new WindowShadowRenderer ( ) ) ; return theme ; }
Helper method that will quickly setup a new theme with some sensible component overrides .
21,878
public synchronized Definition addOverride ( Class < ? > clazz , TextColor foreground , TextColor background , SGR ... styles ) { Definition definition = new Definition ( new Style ( foreground , background , styles ) ) ; overrideDefinitions . put ( clazz , definition ) ; return definition ; }
Adds an override for a particular class or overwrites a previously defined override .
21,879
public synchronized List < List < V > > getRows ( ) { List < List < V > > copy = new ArrayList < List < V > > ( ) ; for ( List < V > row : rows ) { copy . add ( new ArrayList < V > ( row ) ) ; } return copy ; }
Returns all rows in the model as a list of lists containing the data as elements
21,880
public synchronized TableModel < V > insertRow ( int index , Collection < V > values ) { ArrayList < V > list = new ArrayList < V > ( values ) ; rows . add ( index , list ) ; for ( Listener < V > listener : listeners ) { listener . onRowAdded ( this , index ) ; } return this ; }
Inserts a new row to the table model at a particular index
21,881
public synchronized TableModel < V > removeRow ( int index ) { List < V > removedRow = rows . remove ( index ) ; for ( Listener < V > listener : listeners ) { listener . onRowRemoved ( this , index , removedRow ) ; } return this ; }
Removes a row at a particular index from the table model
21,882
public synchronized TableModel < V > setColumnLabel ( int index , String newLabel ) { columns . set ( index , newLabel ) ; return this ; }
Updates the label of a column header
21,883
public synchronized TableModel < V > removeColumn ( int index ) { String removedColumnHeader = columns . remove ( index ) ; List < V > removedColumn = new ArrayList < V > ( ) ; for ( List < V > row : rows ) { removedColumn . add ( row . remove ( index ) ) ; } for ( Listener < V > listener : listeners ) { listener . onColumnRemoved ( this , index , removedColumnHeader , removedColumn ) ; } return this ; }
Removes a column from the table model
21,884
public Color get ( TextColor . ANSI color , boolean isForeground , boolean useBrightTones ) { if ( useBrightTones ) { switch ( color ) { case BLACK : return brightBlack ; case BLUE : return brightBlue ; case CYAN : return brightCyan ; case DEFAULT : return isForeground ? defaultBrightColor : defaultBackgroundColor ; case GREEN : return brightGreen ; case MAGENTA : return brightMagenta ; case RED : return brightRed ; case WHITE : return brightWhite ; case YELLOW : return brightYellow ; } } else { switch ( color ) { case BLACK : return normalBlack ; case BLUE : return normalBlue ; case CYAN : return normalCyan ; case DEFAULT : return isForeground ? defaultColor : defaultBackgroundColor ; case GREEN : return normalGreen ; case MAGENTA : return normalMagenta ; case RED : return normalRed ; case WHITE : return normalWhite ; case YELLOW : return normalYellow ; } } throw new IllegalArgumentException ( "Unknown text color " + color ) ; }
Returns the AWT color from this palette given an ANSI color and two hints for if we are looking for a background color and if we want to use the bright version .
21,885
@ SuppressWarnings ( "ConstantConditions" ) public synchronized void add ( Interactable interactable ) { TerminalPosition topLeft = interactable . toBasePane ( TerminalPosition . TOP_LEFT_CORNER ) ; TerminalSize size = interactable . getSize ( ) ; interactables . add ( interactable ) ; int index = interactables . size ( ) - 1 ; for ( int y = topLeft . getRow ( ) ; y < topLeft . getRow ( ) + size . getRows ( ) ; y ++ ) { for ( int x = topLeft . getColumn ( ) ; x < topLeft . getColumn ( ) + size . getColumns ( ) ; x ++ ) { if ( y >= 0 && y < lookupMap . length && x >= 0 && x < lookupMap [ y ] . length ) { lookupMap [ y ] [ x ] = index ; } } } }
Adds an interactable component to the lookup map
21,886
public synchronized Interactable getInteractableAt ( TerminalPosition position ) { if ( position . getRow ( ) < 0 || position . getColumn ( ) < 0 ) { return null ; } if ( position . getRow ( ) >= lookupMap . length ) { return null ; } else if ( position . getColumn ( ) >= lookupMap [ 0 ] . length ) { return null ; } else if ( lookupMap [ position . getRow ( ) ] [ position . getColumn ( ) ] == - 1 ) { return null ; } return interactables . get ( lookupMap [ position . getRow ( ) ] [ position . getColumn ( ) ] ) ; }
Looks up what interactable component is as a particular location in the map
21,887
public ListSelectDialogBuilder < T > addListItems ( T ... items ) { this . content . addAll ( Arrays . asList ( items ) ) ; return this ; }
Adds a list of items to the list box at the end in the order they are passed in
21,888
public synchronized CheckBoxList < V > addItem ( V object , boolean checkedState ) { itemStatus . add ( checkedState ) ; return super . addItem ( object ) ; }
Adds an item to the checkbox list with an explicit checked status
21,889
public synchronized CheckBoxList < V > setChecked ( V object , boolean checked ) { int index = indexOf ( object ) ; if ( index != - 1 ) { setChecked ( index , checked ) ; } return self ( ) ; }
Programmatically sets the checked state of an item in the list box
21,890
public synchronized List < V > getCheckedItems ( ) { List < V > result = new ArrayList < V > ( ) ; for ( int i = 0 ; i < itemStatus . size ( ) ; i ++ ) { if ( itemStatus . get ( i ) ) { result . add ( getItemAt ( i ) ) ; } } return result ; }
Returns all the items in the list box that have checked state as a list
21,891
public void addProfile ( KeyDecodingProfile profile ) { for ( CharacterPattern pattern : profile . getPatterns ( ) ) { synchronized ( bytePatterns ) { bytePatterns . remove ( pattern ) ; bytePatterns . add ( pattern ) ; } } }
Adds another key decoding profile to this InputDecoder which means all patterns from the profile will be used when decoding input .
21,892
public synchronized KeyStroke getNextCharacter ( boolean blockingIO ) throws IOException { KeyStroke bestMatch = null ; int bestLen = 0 ; int curLen = 0 ; while ( true ) { if ( curLen < currentMatching . size ( ) ) { curLen ++ ; } else { if ( bestMatch != null ) { int timeout = getTimeoutUnits ( ) ; while ( timeout > 0 && ! source . ready ( ) ) { try { timeout -- ; Thread . sleep ( 250 ) ; } catch ( InterruptedException e ) { timeout = 0 ; } } } if ( source . ready ( ) || ( blockingIO && bestMatch == null ) ) { int readChar = source . read ( ) ; if ( readChar == - 1 ) { seenEOF = true ; if ( currentMatching . isEmpty ( ) ) { return new KeyStroke ( KeyType . EOF ) ; } break ; } currentMatching . add ( ( char ) readChar ) ; curLen ++ ; } else { if ( bestMatch != null ) { break ; } return null ; } } List < Character > curSub = currentMatching . subList ( 0 , curLen ) ; Matching matching = getBestMatch ( curSub ) ; if ( matching . fullMatch != null ) { bestMatch = matching . fullMatch ; bestLen = curLen ; if ( ! matching . partialMatch ) { break ; } else { continue ; } } else if ( matching . partialMatch ) { continue ; } else { if ( bestMatch != null ) { break ; } else { curSub . clear ( ) ; curLen = 0 ; continue ; } } } if ( bestMatch == null ) { if ( seenEOF ) { currentMatching . clear ( ) ; return new KeyStroke ( KeyType . EOF ) ; } return null ; } List < Character > bestSub = currentMatching . subList ( 0 , bestLen ) ; bestSub . clear ( ) ; return bestMatch ; }
Reads and decodes the next key stroke from the input stream
21,893
public static MessageDialogButton showMessageDialog ( WindowBasedTextGUI textGUI , String title , String text , MessageDialogButton ... buttons ) { MessageDialogBuilder builder = new MessageDialogBuilder ( ) . setTitle ( title ) . setText ( text ) ; if ( buttons . length == 0 ) { builder . addButton ( MessageDialogButton . OK ) ; } for ( MessageDialogButton button : buttons ) { builder . addButton ( button ) ; } return builder . build ( ) . showDialog ( textGUI ) ; }
Shortcut for quickly displaying a message box
21,894
public Panel addComponent ( int index , Component component ) { if ( component == null ) { throw new IllegalArgumentException ( "Cannot add null component" ) ; } synchronized ( components ) { if ( components . contains ( component ) ) { return this ; } if ( component . getParent ( ) != null ) { component . getParent ( ) . removeComponent ( component ) ; } if ( index > components . size ( ) ) { index = components . size ( ) ; } else if ( index < 0 ) { index = 0 ; } components . add ( index , component ) ; } component . onAdded ( this ) ; invalidate ( ) ; return this ; }
Adds a new child component to the panel . Where within the panel the child will be displayed is up to the layout manager assigned to this panel . If the component has already been added to another panel it will first be removed from that panel before added to this one .
21,895
public Panel removeAllComponents ( ) { synchronized ( components ) { for ( Component component : new ArrayList < Component > ( components ) ) { removeComponent ( component ) ; } } return this ; }
Removes all child components from this panel
21,896
public synchronized Panel setLayoutManager ( LayoutManager layoutManager ) { if ( layoutManager == null ) { layoutManager = new AbsoluteLayout ( ) ; } this . layoutManager = layoutManager ; invalidate ( ) ; return this ; }
Assigns a new layout manager to this panel replacing the previous layout manager assigned . Please note that if the panel is not empty at the time you assign a new layout manager the existing components might not show up where you expect them and their layout data property might need to be re - assigned .
21,897
public synchronized ComboBox < V > addItem ( V item ) { if ( item == null ) { throw new IllegalArgumentException ( "Cannot add null elements to a ComboBox" ) ; } items . add ( item ) ; if ( selectedIndex == - 1 && items . size ( ) == 1 ) { setSelectedIndex ( 0 ) ; } invalidate ( ) ; return this ; }
Adds a new item to the combo box at the end
21,898
public synchronized ComboBox < V > removeItem ( V item ) { int index = items . indexOf ( item ) ; if ( index == - 1 ) { return this ; } return remoteItem ( index ) ; }
Removes a particular item from the combo box if it is present otherwise does nothing
21,899
public synchronized ComboBox < V > remoteItem ( int index ) { items . remove ( index ) ; if ( index < selectedIndex ) { setSelectedIndex ( selectedIndex - 1 ) ; } else if ( index == selectedIndex ) { setSelectedIndex ( - 1 ) ; } invalidate ( ) ; return this ; }
Removes an item from the combo box at a particular index