idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
152,600
public static byte [ ] doubleFormating ( Number num , Charset charset , int fieldLength , int sizeDecimalPart ) { int sizeWholePart = fieldLength - ( sizeDecimalPart > 0 ? ( sizeDecimalPart + 1 ) : 0 ) ; StringBuilder format = new StringBuilder ( fieldLength ) ; for ( int i = 0 ; i < sizeWholePart - 1 ; i ++ ) { format . append ( "#" ) ; } if ( format . length ( ) < sizeWholePart ) { format . append ( "0" ) ; } if ( sizeDecimalPart > 0 ) { format . append ( "." ) ; for ( int i = 0 ; i < sizeDecimalPart ; i ++ ) { format . append ( "0" ) ; } } DecimalFormat df = ( DecimalFormat ) NumberFormat . getInstance ( Locale . ENGLISH ) ; df . applyPattern ( format . toString ( ) ) ; return textPadding ( df . format ( num ) . toString ( ) , charset , fieldLength , DBFAlignment . RIGHT , ( byte ) ' ' ) ; }
Format a double number to write to a dbf file
245
11
152,601
public static boolean contains ( byte [ ] array , byte value ) { if ( array != null ) { for ( byte data : array ) { if ( data == value ) { return true ; } } } return false ; }
Checks that a byte array contains some specific byte
46
10
152,602
public static boolean isPureAscii ( String stringToCheck ) { if ( stringToCheck == null || stringToCheck . length ( ) == 0 ) { return true ; } synchronized ( ASCII_ENCODER ) { return ASCII_ENCODER . canEncode ( stringToCheck ) ; } }
Checks if a string is pure Ascii
65
10
152,603
public static boolean isPureAscii ( byte [ ] data ) { if ( data == null ) { return false ; } for ( byte b : data ) { if ( b < 0x20 ) { return false ; } } return true ; }
Test if the data in the array is pure ASCII
52
10
152,604
public static byte [ ] trimRightSpaces ( byte [ ] b_array ) { if ( b_array == null || b_array . length == 0 ) { return new byte [ 0 ] ; } int pos = getRightPos ( b_array ) ; int length = pos + 1 ; byte [ ] newBytes = new byte [ length ] ; System . arraycopy ( b_array , 0 , newBytes , 0 , length ) ; return newBytes ; }
Trims right spaces from string
98
6
152,605
public void setFields ( DBFField [ ] fields ) { if ( this . closed ) { throw new IllegalStateException ( "You can not set fields to a closed DBFWriter" ) ; } if ( this . header . fieldArray != null ) { throw new DBFException ( "Fields has already been set" ) ; } if ( fields == null || fields . length == 0 ) { throw new DBFException ( "Should have at least one field" ) ; } for ( int i = 0 ; i < fields . length ; i ++ ) { if ( fields [ i ] == null ) { throw new DBFException ( "Field " + i + " is null" ) ; } } this . header . fieldArray = new DBFField [ fields . length ] ; for ( int i = 0 ; i < fields . length ; i ++ ) { this . header . fieldArray [ i ] = new DBFField ( fields [ i ] ) ; } try { if ( this . raf != null && this . raf . length ( ) == 0 ) { // this is a new/non-existent file. So write header before proceeding this . header . write ( this . raf ) ; } } catch ( IOException e ) { throw new DBFException ( "Error accesing file:" + e . getMessage ( ) , e ) ; } }
Sets fields definition
291
4
152,606
public void addRecord ( Object [ ] values ) { if ( this . closed ) { throw new IllegalStateException ( "You can add records a closed DBFWriter" ) ; } if ( this . header . fieldArray == null ) { throw new DBFException ( "Fields should be set before adding records" ) ; } if ( values == null ) { throw new DBFException ( "Null cannot be added as row" ) ; } if ( values . length != this . header . fieldArray . length ) { throw new DBFException ( "Invalid record. Invalid number of fields in row" ) ; } for ( int i = 0 ; i < this . header . fieldArray . length ; i ++ ) { Object value = values [ i ] ; if ( value == null ) { continue ; } switch ( this . header . fieldArray [ i ] . getType ( ) ) { case CHARACTER : if ( ! ( value instanceof String ) ) { throw new DBFException ( "Invalid value for field " + i + ":" + value ) ; } break ; case LOGICAL : if ( ! ( value instanceof Boolean ) ) { throw new DBFException ( "Invalid value for field " + i + ":" + value ) ; } break ; case DATE : if ( ! ( value instanceof Date ) ) { throw new DBFException ( "Invalid value for field " + i + ":" + value ) ; } break ; case NUMERIC : case FLOATING_POINT : if ( ! ( value instanceof Number ) ) { throw new DBFException ( "Invalid value for field " + i + ":" + value ) ; } break ; default : throw new DBFException ( "Unsupported writting of field type " + i + " " + this . header . fieldArray [ i ] . getType ( ) ) ; } } if ( this . raf == null ) { this . v_records . add ( values ) ; } else { try { writeRecord ( this . raf , values ) ; this . recordCount ++ ; } catch ( IOException e ) { throw new DBFException ( "Error occured while writing record. " + e . getMessage ( ) , e ) ; } } }
Add a record .
475
4
152,607
@ Override public void close ( ) { if ( this . closed ) { return ; } this . closed = true ; if ( this . raf != null ) { /* * everything is written already. just update the header for * record count and the END_OF_DATA mark */ try { this . header . numberOfRecords = this . recordCount ; this . raf . seek ( 0 ) ; this . header . write ( this . raf ) ; this . raf . seek ( this . raf . length ( ) ) ; this . raf . writeByte ( END_OF_DATA ) ; } catch ( IOException e ) { throw new DBFException ( e . getMessage ( ) , e ) ; } finally { DBFUtils . close ( this . raf ) ; } } else if ( this . outputStream != null ) { try { writeToStream ( this . outputStream ) ; } finally { DBFUtils . close ( this . outputStream ) ; } } }
In sync mode write the header and close the file
213
10
152,608
public String getString ( int columnIndex ) { if ( columnIndex < 0 || columnIndex >= data . length ) { throw new IllegalArgumentException ( "Invalid index field: (" + columnIndex + "). Valid range is 0 to " + ( data . length - 1 ) ) ; } Object fieldValue = data [ columnIndex ] ; if ( fieldValue == null ) { return null ; } if ( fieldValue instanceof String ) { return ( String ) fieldValue ; } return fieldValue . toString ( ) ; }
Reads the data as string
110
6
152,609
public BigDecimal getBigDecimal ( int columnIndex ) { Object fieldValue = data [ columnIndex ] ; if ( fieldValue == null ) { return null ; } if ( fieldValue instanceof BigDecimal ) { return ( BigDecimal ) fieldValue ; } throw new DBFException ( "Unsupported type for BigDecimal at column:" + columnIndex + " " + fieldValue . getClass ( ) . getCanonicalName ( ) ) ; }
Reads the data as BigDecimal
99
8
152,610
public boolean getBoolean ( int columnIndex ) { Object fieldValue = data [ columnIndex ] ; if ( fieldValue == null ) { return Boolean . FALSE ; } if ( fieldValue instanceof Boolean ) { return ( Boolean ) fieldValue ; } throw new DBFException ( "Unsupported type for Boolean at column:" + columnIndex + " " + fieldValue . getClass ( ) . getCanonicalName ( ) ) ; }
Reads the data as Boolean
92
6
152,611
public Date getDate ( int columnIndex ) { Object fieldValue = data [ columnIndex ] ; if ( fieldValue == null ) { return null ; } if ( fieldValue instanceof Date ) { return ( Date ) fieldValue ; } throw new DBFException ( "Unsupported type for Date at column:" + columnIndex + " " + fieldValue . getClass ( ) . getCanonicalName ( ) ) ; }
Reads the data as Date
89
6
152,612
public double getDouble ( int columnIndex ) { Object fieldValue = data [ columnIndex ] ; if ( fieldValue == null ) { return 0.0 ; } if ( fieldValue instanceof Number ) { return ( ( Number ) fieldValue ) . doubleValue ( ) ; } throw new DBFException ( "Unsupported type for Number at column:" + columnIndex + " " + fieldValue . getClass ( ) . getCanonicalName ( ) ) ; }
Reads the data as Double
98
6
152,613
public float getFloat ( int columnIndex ) { Object fieldValue = data [ columnIndex ] ; if ( fieldValue == null ) { return 0.0f ; } if ( fieldValue instanceof Number ) { return ( ( Number ) fieldValue ) . floatValue ( ) ; } throw new DBFException ( "Unsupported type for Number at column:" + columnIndex + " " + fieldValue . getClass ( ) . getCanonicalName ( ) ) ; }
Reads the data as Float
99
6
152,614
public int getInt ( int columnIndex ) { Object fieldValue = data [ columnIndex ] ; if ( fieldValue == null ) { return 0 ; } if ( fieldValue instanceof Number ) { return ( ( Number ) fieldValue ) . intValue ( ) ; } throw new DBFException ( "Unsupported type for Number at column:" + columnIndex + " " + fieldValue . getClass ( ) . getCanonicalName ( ) ) ; }
Reads the data as int
96
6
152,615
public long getLong ( int columnIndex ) { Object fieldValue = data [ columnIndex ] ; if ( fieldValue == null ) { return 0 ; } if ( fieldValue instanceof Number ) { return ( ( Number ) fieldValue ) . longValue ( ) ; } throw new DBFException ( "Unsupported type for Number at column:" + columnIndex + " " + fieldValue . getClass ( ) . getCanonicalName ( ) ) ; }
Reads the data as long
96
6
152,616
@ Deprecated public static byte [ ] textPadding ( String text , String characterSetName , int length , int alignment , byte paddingByte ) throws UnsupportedEncodingException { DBFAlignment align = DBFAlignment . RIGHT ; if ( alignment == ALIGN_LEFT ) { align = DBFAlignment . LEFT ; } return textPadding ( text , characterSetName , length , align , paddingByte ) ; }
Text is truncated if exceed field capacity . Uses spaces as padding
92
13
152,617
@ Deprecated public static byte [ ] textPadding ( String text , String characterSetName , int length , DBFAlignment alignment , byte paddingByte ) throws UnsupportedEncodingException { return textPadding ( text , Charset . forName ( characterSetName ) , length , alignment , paddingByte ) ; }
Obtais the data to store in file for a text field . Text is truncated if exceed field capacity
68
22
152,618
TomcatRuntime getTomcatRuntime ( WebResourceRoot resources ) { TomcatRuntime result = null ; if ( isUberJar ( resources ) ) { result = TomcatRuntime . UBER_JAR ; } else if ( isUberWar ( resources ) ) { result = TomcatRuntime . UBER_WAR ; } else if ( isTesting ( resources ) ) { result = TomcatRuntime . TEST ; } else if ( isUnpackagedJar ( resources ) ) { result = TomcatRuntime . UNPACKAGED_JAR ; } return result ; }
Inform tomcat runtime setup . UNPACKAGED_WAR not covered yet .
119
18
152,619
protected void writeClassList ( File file , Collection < String > classNames ) throws IOException { File baseDir = file . getParentFile ( ) ; if ( baseDir . isDirectory ( ) || baseDir . mkdirs ( ) ) { Files . write ( file . toPath ( ) , classNames , StandardCharsets . UTF_8 ) ; } else { throw new IOException ( baseDir + " does not exist and could not be created" ) ; } }
Helper method which writes a list of class names to the given file .
101
14
152,620
protected void writeClassMap ( File file , Map < String , ? extends Collection < String > > classMap ) throws IOException { File baseDir = file . getParentFile ( ) ; if ( baseDir . isDirectory ( ) || baseDir . mkdirs ( ) ) { //noinspection CharsetObjectCanBeUsed try ( PrintWriter printWriter = new PrintWriter ( file , "UTF-8" ) ) { classMap . forEach ( ( key , value ) -> { printWriter . print ( key ) ; printWriter . print ( "=" ) ; printWriter . println ( String . join ( "," , value ) ) ; } ) ; } } else { throw new IOException ( baseDir + " does not exist and could not be created" ) ; } }
Helper method which writes a map of class names to the given file .
166
14
152,621
public static boolean areAllGranted ( String authorities ) throws IOException { AuthorizeFaceletsTag authorizeTag = new AuthorizeFaceletsTag ( ) ; authorizeTag . setIfAllGranted ( authorities ) ; return authorizeTag . authorize ( ) ; }
Returns true if the user has all of of the given authorities .
53
13
152,622
public static boolean areAnyGranted ( String authorities ) throws IOException { AuthorizeFaceletsTag authorizeTag = new AuthorizeFaceletsTag ( ) ; authorizeTag . setIfAnyGranted ( authorities ) ; return authorizeTag . authorize ( ) ; }
Returns true if the user has any of the given authorities .
53
12
152,623
public static boolean areNotGranted ( String authorities ) throws IOException { AuthorizeFaceletsTag authorizeTag = new AuthorizeFaceletsTag ( ) ; authorizeTag . setIfNotGranted ( authorities ) ; return authorizeTag . authorize ( ) ; }
Returns true if the user does not have any of the given authorities .
53
14
152,624
public static boolean isAllowed ( String url , String method ) throws IOException { AuthorizeFaceletsTag authorizeTag = new AuthorizeFaceletsTag ( ) ; authorizeTag . setUrl ( url ) ; authorizeTag . setMethod ( method ) ; return authorizeTag . authorizeUsingUrlCheck ( ) ; }
Returns true if the user is allowed to access the given URL and HTTP method combination . The HTTP method is optional and case insensitive .
64
26
152,625
private void registerJsfCdiToSpring ( BeanDefinition definition ) { if ( definition instanceof AnnotatedBeanDefinition ) { AnnotatedBeanDefinition annDef = ( AnnotatedBeanDefinition ) definition ; String scopeName = null ; // firstly check whether bean is defined via configuration if ( annDef . getFactoryMethodMetadata ( ) != null ) { scopeName = deduceScopeName ( annDef . getFactoryMethodMetadata ( ) ) ; } else { // fallback to type scopeName = deduceScopeName ( annDef . getMetadata ( ) ) ; } if ( scopeName != null ) { definition . setScope ( scopeName ) ; log . debug ( "{} - Scope({})" , definition . getBeanClassName ( ) , scopeName . toUpperCase ( ) ) ; } } }
Checks how is bean defined and deduces scope name from JSF CDI annotations .
179
18
152,626
private String getPropertyPath ( Expression reference , String alias ) { if ( reference instanceof Property ) { Property property = ( Property ) reference ; if ( alias . equals ( property . getScope ( ) ) ) { return property . getPath ( ) ; } else if ( property . getSource ( ) != null ) { String subPath = getPropertyPath ( property . getSource ( ) , alias ) ; if ( subPath != null ) { return String . format ( "%s.%s" , subPath , property . getPath ( ) ) ; } } } return null ; }
Collapse a property path expression back to it s qualified form for use as the path attribute of the retrieve .
122
22
152,627
public boolean isCompatibleWith ( DataType other ) { // A type is compatible with a choice type if it is a subtype of one of the choice types if ( other instanceof ChoiceType ) { for ( DataType choice : ( ( ChoiceType ) other ) . getTypes ( ) ) { if ( this . isSubTypeOf ( choice ) ) { return true ; } } } return this . equals ( other ) ; // Any data type is compatible with itself }
literal to any other type or casting a class to an equivalent tuple .
98
15
152,628
public T visitTypeSpecifier ( TypeSpecifier elm , C context ) { if ( elm instanceof NamedTypeSpecifier ) return visitNamedTypeSpecifier ( ( NamedTypeSpecifier ) elm , context ) ; else if ( elm instanceof IntervalTypeSpecifier ) return visitIntervalTypeSpecifier ( ( IntervalTypeSpecifier ) elm , context ) ; else if ( elm instanceof ListTypeSpecifier ) return visitListTypeSpecifier ( ( ListTypeSpecifier ) elm , context ) ; else if ( elm instanceof TupleTypeSpecifier ) return visitTupleTypeSpecifier ( ( TupleTypeSpecifier ) elm , context ) ; else return null ; }
Visit a TypeSpecifier . This method will be called for every node in the tree that is a descendant of the TypeSpecifier type .
152
28
152,629
public T visitIntervalTypeSpecifier ( IntervalTypeSpecifier elm , C context ) { visitElement ( elm . getPointType ( ) , context ) ; return null ; }
Visit a IntervalTypeSpecifier . This method will be called for every node in the tree that is a IntervalTypeSpecifier .
40
28
152,630
public T visitListTypeSpecifier ( ListTypeSpecifier elm , C context ) { visitElement ( elm . getElementType ( ) , context ) ; return null ; }
Visit a ListTypeSpecifier . This method will be called for every node in the tree that is a ListTypeSpecifier .
38
26
152,631
public T visitTupleElementDefinition ( TupleElementDefinition elm , C context ) { visitElement ( elm . getType ( ) , context ) ; return null ; }
Visit a TupleElementDefinition . This method will be called for every node in the tree that is a TupleElementDefinition .
37
26
152,632
public T visitTupleTypeSpecifier ( TupleTypeSpecifier elm , C context ) { for ( TupleElementDefinition element : elm . getElement ( ) ) { visitElement ( element , context ) ; } return null ; }
Visit a TupleTypeSpecifier . This method will be called for every node in the tree that is a TupleTypeSpecifier .
51
28
152,633
public T visitTernaryExpression ( TernaryExpression elm , C context ) { for ( Expression element : elm . getOperand ( ) ) { visitElement ( element , context ) ; } return null ; }
Visit a TernaryExpression . This method will be called for every node in the tree that is a TernaryExpression .
49
28
152,634
public T visitNaryExpression ( NaryExpression elm , C context ) { if ( elm instanceof Coalesce ) return visitCoalesce ( ( Coalesce ) elm , context ) ; else if ( elm instanceof Concatenate ) return visitConcatenate ( ( Concatenate ) elm , context ) ; else if ( elm instanceof Except ) return visitExcept ( ( Except ) elm , context ) ; else if ( elm instanceof Intersect ) return visitIntersect ( ( Intersect ) elm , context ) ; else if ( elm instanceof Union ) return visitUnion ( ( Union ) elm , context ) ; else return null ; }
Visit a NaryExpression . This method will be called for every node in the tree that is a NaryExpression .
151
26
152,635
public T visitExpressionDef ( ExpressionDef elm , C context ) { visitElement ( elm . getExpression ( ) , context ) ; return null ; }
Visit a ExpressionDef . This method will be called for every node in the tree that is a ExpressionDef .
35
22
152,636
public T visitFunctionDef ( FunctionDef elm , C context ) { for ( OperandDef element : elm . getOperand ( ) ) { visitElement ( element , context ) ; } visitElement ( elm . getExpression ( ) , context ) ; return null ; }
Visit a FunctionDef . This method will be called for every node in the tree that is a FunctionDef .
60
22
152,637
public T visitFunctionRef ( FunctionRef elm , C context ) { for ( Expression element : elm . getOperand ( ) ) { visitElement ( element , context ) ; } return null ; }
Visit a FunctionRef . This method will be called for every node in the tree that is a FunctionRef .
43
22
152,638
public T visitParameterDef ( ParameterDef elm , C context ) { if ( elm . getParameterTypeSpecifier ( ) != null ) { visitElement ( elm . getParameterTypeSpecifier ( ) , context ) ; } if ( elm . getDefault ( ) != null ) { visitElement ( elm . getDefault ( ) , context ) ; } return null ; }
Visit a ParameterDef . This method will be called for every node in the tree that is a ParameterDef .
82
24
152,639
public T visitOperandDef ( OperandDef elm , C context ) { if ( elm . getOperandTypeSpecifier ( ) != null ) { visitElement ( elm . getOperandTypeSpecifier ( ) , context ) ; } return null ; }
Visit a OperandDef . This method will be called for every node in the tree that is a OperandDef .
57
24
152,640
public T visitTupleElement ( TupleElement elm , C context ) { visitElement ( elm . getValue ( ) , context ) ; return null ; }
Visit a TupleElement . This method will be called for every node in the tree that is a TupleElement .
35
24
152,641
public T visitTuple ( Tuple elm , C context ) { for ( TupleElement element : elm . getElement ( ) ) { visitTupleElement ( element , context ) ; } return null ; }
Visit a Tuple . This method will be called for every node in the tree that is a Tuple .
46
22
152,642
public T visitInstanceElement ( InstanceElement elm , C context ) { visitElement ( elm . getValue ( ) , context ) ; return null ; }
Visit a InstanceElement . This method will be called for every node in the tree that is a InstanceElement .
34
24
152,643
public T visitInstance ( Instance elm , C context ) { for ( InstanceElement element : elm . getElement ( ) ) { visitInstanceElement ( element , context ) ; } return null ; }
Visit a Instance . This method will be called for every node in the tree that is a Instance .
44
22
152,644
public T visitInterval ( Interval elm , C context ) { if ( elm . getLow ( ) != null ) { visitElement ( elm . getLow ( ) , context ) ; } if ( elm . getLowClosedExpression ( ) != null ) { visitElement ( elm . getLowClosedExpression ( ) , context ) ; } if ( elm . getHigh ( ) != null ) { visitElement ( elm . getHigh ( ) , context ) ; } if ( elm . getHighClosedExpression ( ) != null ) { visitElement ( elm . getHighClosedExpression ( ) , context ) ; } return null ; }
Visit a Interval . This method will be called for every node in the tree that is a Interval .
147
22
152,645
public T visitList ( List elm , C context ) { if ( elm . getTypeSpecifier ( ) != null ) { visitElement ( elm . getTypeSpecifier ( ) , context ) ; } for ( Expression element : elm . getElement ( ) ) { visitElement ( element , context ) ; } return null ; }
Visit a List . This method will be called for every node in the tree that is a List .
72
20
152,646
public void recordParsingException ( CqlTranslatorException e ) { addException ( e ) ; if ( shouldReport ( e . getSeverity ( ) ) ) { CqlToElmError err = af . createCqlToElmError ( ) ; err . setMessage ( e . getMessage ( ) ) ; err . setErrorType ( e instanceof CqlSyntaxException ? ErrorType . SYNTAX : ( e instanceof CqlSemanticException ? ErrorType . SEMANTIC : ErrorType . INTERNAL ) ) ; err . setErrorSeverity ( toErrorSeverity ( e . getSeverity ( ) ) ) ; if ( e . getLocator ( ) != null ) { err . setStartLine ( e . getLocator ( ) . getStartLine ( ) ) ; err . setEndLine ( e . getLocator ( ) . getEndLine ( ) ) ; err . setStartChar ( e . getLocator ( ) . getStartChar ( ) ) ; err . setEndChar ( e . getLocator ( ) . getEndChar ( ) ) ; } if ( e . getCause ( ) != null && e . getCause ( ) instanceof CqlTranslatorIncludeException ) { CqlTranslatorIncludeException incEx = ( CqlTranslatorIncludeException ) e . getCause ( ) ; err . setTargetIncludeLibraryId ( incEx . getLibraryId ( ) ) ; err . setTargetIncludeLibraryVersionId ( incEx . getVersionId ( ) ) ; err . setErrorType ( ErrorType . INCLUDE ) ; } library . getAnnotation ( ) . add ( err ) ; } }
Record any errors while parsing in both the list of errors but also in the library itself so they can be processed easily by a remote client
367
27
152,647
private CalculateAge resolveCalculateAge ( Expression e , DateTimePrecision p ) { CalculateAge operator = of . createCalculateAge ( ) . withPrecision ( p ) . withOperand ( e ) ; builder . resolveUnaryCall ( "System" , "CalculateAge" , operator ) ; return operator ; }
Age - Related Function Support
74
5
152,648
private Round resolveRound ( FunctionRef fun ) { if ( fun . getOperand ( ) . isEmpty ( ) || fun . getOperand ( ) . size ( ) > 2 ) { throw new IllegalArgumentException ( "Could not resolve call to system operator Round. Expected 1 or 2 arguments." ) ; } final Round round = of . createRound ( ) . withOperand ( fun . getOperand ( ) . get ( 0 ) ) ; if ( fun . getOperand ( ) . size ( ) == 2 ) { round . setPrecision ( fun . getOperand ( ) . get ( 1 ) ) ; } builder . resolveCall ( "System" , "Round" , new RoundInvocation ( round ) ) ; return round ; }
Arithmetic Function Support
160
4
152,649
private DateTime resolveDateTime ( FunctionRef fun ) { final DateTime dt = of . createDateTime ( ) ; DateTimeInvocation . setDateTimeFieldsFromOperands ( dt , fun . getOperand ( ) ) ; builder . resolveCall ( "System" , "DateTime" , new DateTimeInvocation ( dt ) ) ; return dt ; }
DateTime Function Support
82
4
152,650
private IndexOf resolveIndexOf ( FunctionRef fun ) { checkNumberOfOperands ( fun , 2 ) ; final IndexOf indexOf = of . createIndexOf ( ) ; indexOf . setSource ( fun . getOperand ( ) . get ( 0 ) ) ; indexOf . setElement ( fun . getOperand ( ) . get ( 1 ) ) ; builder . resolveCall ( "System" , "IndexOf" , new IndexOfInvocation ( indexOf ) ) ; return indexOf ; }
List Function Support
107
3
152,651
private Combine resolveCombine ( FunctionRef fun ) { if ( fun . getOperand ( ) . isEmpty ( ) || fun . getOperand ( ) . size ( ) > 2 ) { throw new IllegalArgumentException ( "Could not resolve call to system operator Combine. Expected 1 or 2 arguments." ) ; } final Combine combine = of . createCombine ( ) . withSource ( fun . getOperand ( ) . get ( 0 ) ) ; if ( fun . getOperand ( ) . size ( ) == 2 ) { combine . setSeparator ( fun . getOperand ( ) . get ( 1 ) ) ; } builder . resolveCall ( "System" , "Combine" , new CombineInvocation ( combine ) ) ; return combine ; }
String Function Support
163
3
152,652
private UnaryExpression resolveUnary ( FunctionRef fun ) { UnaryExpression operator = null ; try { Class clazz = Class . forName ( "org.hl7.elm.r1." + fun . getName ( ) ) ; if ( UnaryExpression . class . isAssignableFrom ( clazz ) ) { operator = ( UnaryExpression ) clazz . newInstance ( ) ; checkNumberOfOperands ( fun , 1 ) ; operator . setOperand ( fun . getOperand ( ) . get ( 0 ) ) ; builder . resolveUnaryCall ( "System" , fun . getName ( ) , operator ) ; return operator ; } } catch ( Exception e ) { // Do nothing but fall through } return null ; }
General Function Support
164
3
152,653
public void setStatusBarTintEnabled ( boolean enabled ) { mStatusBarTintEnabled = enabled ; if ( mStatusBarAvailable ) { mStatusBarTintView . setVisibility ( enabled ? View . VISIBLE : View . GONE ) ; } }
Enable tinting of the system status bar .
56
9
152,654
public void setNavigationBarTintEnabled ( boolean enabled ) { mNavBarTintEnabled = enabled ; if ( mNavBarAvailable ) { mNavBarTintView . setVisibility ( enabled ? View . VISIBLE : View . GONE ) ; } }
Enable tinting of the system navigation bar .
57
9
152,655
@ TargetApi ( 11 ) public void setStatusBarAlpha ( float alpha ) { if ( mStatusBarAvailable && Build . VERSION . SDK_INT >= Build . VERSION_CODES . HONEYCOMB ) { mStatusBarTintView . setAlpha ( alpha ) ; } }
Apply the specified alpha to the system status bar .
64
10
152,656
@ TargetApi ( 11 ) public void setNavigationBarAlpha ( float alpha ) { if ( mNavBarAvailable && Build . VERSION . SDK_INT >= Build . VERSION_CODES . HONEYCOMB ) { mNavBarTintView . setAlpha ( alpha ) ; } }
Apply the specified alpha to the system navigation bar .
65
10
152,657
public Completable addProduct ( Product product ) { List < Product > updatedShoppingCart = new ArrayList <> ( ) ; updatedShoppingCart . addAll ( itemsInShoppingCart . getValue ( ) ) ; updatedShoppingCart . add ( product ) ; itemsInShoppingCart . onNext ( updatedShoppingCart ) ; return Completable . complete ( ) ; }
Adds a product to the shopping cart
83
7
152,658
public Completable removeProduct ( Product product ) { List < Product > updatedShoppingCart = new ArrayList <> ( ) ; updatedShoppingCart . addAll ( itemsInShoppingCart . getValue ( ) ) ; updatedShoppingCart . remove ( product ) ; itemsInShoppingCart . onNext ( updatedShoppingCart ) ; return Completable . complete ( ) ; }
Remove a product to the shopping cart
83
7
152,659
public Completable removeProducts ( List < Product > products ) { List < Product > updatedShoppingCart = new ArrayList <> ( ) ; updatedShoppingCart . addAll ( itemsInShoppingCart . getValue ( ) ) ; updatedShoppingCart . removeAll ( products ) ; itemsInShoppingCart . onNext ( updatedShoppingCart ) ; return Completable . complete ( ) ; }
Remove a list of Products from the shopping cart
87
9
152,660
public void subscribe ( Observable < M > observable , final boolean pullToRefresh ) { if ( isViewAttached ( ) ) { getView ( ) . showLoading ( pullToRefresh ) ; } unsubscribe ( ) ; subscriber = new Subscriber < M > ( ) { private boolean ptr = pullToRefresh ; @ Override public void onCompleted ( ) { BaseRxLcePresenter . this . onCompleted ( ) ; } @ Override public void onError ( Throwable e ) { BaseRxLcePresenter . this . onError ( e , ptr ) ; } @ Override public void onNext ( M m ) { BaseRxLcePresenter . this . onNext ( m ) ; } } ; observable . subscribeOn ( Schedulers . io ( ) ) . observeOn ( AndroidSchedulers . mainThread ( ) ) . subscribe ( subscriber ) ; }
Subscribes the presenter himself as subscriber on the observable
194
11
152,661
@ NonNull protected ActivityMvpDelegate < V , P > getMvpDelegate ( ) { if ( mvpDelegate == null ) { mvpDelegate = new ActivityMvpDelegateImpl ( this , this , true ) ; } return mvpDelegate ; }
Get the mvp delegate . This is internally used for creating presenter attaching and detaching view from presenter .
60
21
152,662
@ MainThread private void subscribeViewStateConsumerActually ( @ NonNull final V view ) { if ( view == null ) { throw new NullPointerException ( "View is null" ) ; } if ( viewStateConsumer == null ) { throw new NullPointerException ( ViewStateConsumer . class . getSimpleName ( ) + " is null. This is a Mosby internal bug. Please file an issue at https://github.com/sockeqwe/mosby/issues" ) ; } viewRelayConsumerDisposable = viewStateBehaviorSubject . subscribe ( new Consumer < VS > ( ) { @ Override public void accept ( VS vs ) throws Exception { viewStateConsumer . accept ( view , vs ) ; } } ) ; }
Actually subscribes the view as consumer to the internally view relay .
158
13
152,663
@ Override public Observable < Account > doLogin ( AuthCredentials credentials ) { return Observable . just ( credentials ) . flatMap ( new Func1 < AuthCredentials , Observable < Account > > ( ) { @ Override public Observable < Account > call ( AuthCredentials credentials ) { try { // Simulate network delay Thread . sleep ( 3000 ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } if ( credentials . getUsername ( ) . equals ( "ted" ) && credentials . getPassword ( ) . equals ( "robin" ) ) { currentAccount = new Account ( ) ; return Observable . just ( currentAccount ) ; } return Observable . error ( new LoginException ( ) ) ; } } ) ; }
Returns the Account observable
171
4
152,664
public static void showErrorView ( @ NonNull final View loadingView , @ NonNull final View contentView , final View errorView ) { contentView . setVisibility ( View . GONE ) ; final Resources resources = loadingView . getResources ( ) ; // Not visible yet, so animate the view in AnimatorSet set = new AnimatorSet ( ) ; ObjectAnimator in = ObjectAnimator . ofFloat ( errorView , View . ALPHA , 1f ) ; ObjectAnimator loadingOut = ObjectAnimator . ofFloat ( loadingView , View . ALPHA , 0f ) ; set . playTogether ( in , loadingOut ) ; set . setDuration ( resources . getInteger ( R . integer . lce_error_view_show_animation_time ) ) ; set . addListener ( new AnimatorListenerAdapter ( ) { @ Override public void onAnimationStart ( Animator animation ) { super . onAnimationStart ( animation ) ; errorView . setVisibility ( View . VISIBLE ) ; } @ Override public void onAnimationEnd ( Animator animation ) { super . onAnimationEnd ( animation ) ; loadingView . setVisibility ( View . GONE ) ; loadingView . setAlpha ( 1f ) ; // For future showLoading calls } } ) ; set . start ( ) ; }
Shows the error view instead of the loading view
279
10
152,665
public static void showContent ( @ NonNull final View loadingView , @ NonNull final View contentView , @ NonNull final View errorView ) { if ( contentView . getVisibility ( ) == View . VISIBLE ) { // No Changing needed, because contentView is already visible errorView . setVisibility ( View . GONE ) ; loadingView . setVisibility ( View . GONE ) ; } else { errorView . setVisibility ( View . GONE ) ; final Resources resources = loadingView . getResources ( ) ; final int translateInPixels = resources . getDimensionPixelSize ( R . dimen . lce_content_view_animation_translate_y ) ; // Not visible yet, so animate the view in AnimatorSet set = new AnimatorSet ( ) ; ObjectAnimator contentFadeIn = ObjectAnimator . ofFloat ( contentView , View . ALPHA , 0f , 1f ) ; ObjectAnimator contentTranslateIn = ObjectAnimator . ofFloat ( contentView , View . TRANSLATION_Y , translateInPixels , 0 ) ; ObjectAnimator loadingFadeOut = ObjectAnimator . ofFloat ( loadingView , View . ALPHA , 1f , 0f ) ; ObjectAnimator loadingTranslateOut = ObjectAnimator . ofFloat ( loadingView , View . TRANSLATION_Y , 0 , - translateInPixels ) ; set . playTogether ( contentFadeIn , contentTranslateIn , loadingFadeOut , loadingTranslateOut ) ; set . setDuration ( resources . getInteger ( R . integer . lce_content_view_show_animation_time ) ) ; set . addListener ( new AnimatorListenerAdapter ( ) { @ Override public void onAnimationStart ( Animator animation ) { contentView . setTranslationY ( 0 ) ; loadingView . setTranslationY ( 0 ) ; contentView . setVisibility ( View . VISIBLE ) ; } @ Override public void onAnimationEnd ( Animator animation ) { loadingView . setVisibility ( View . GONE ) ; loadingView . setAlpha ( 1f ) ; // For future showLoading calls contentView . setTranslationY ( 0 ) ; loadingView . setTranslationY ( 0 ) ; } } ) ; set . start ( ) ; } }
Display the content instead of the loadingView
492
8
152,666
private boolean isSubTypeOfMvpView ( Class < ? > klass ) { if ( klass . equals ( MvpView . class ) ) { return true ; } Class [ ] superInterfaces = klass . getInterfaces ( ) ; for ( int i = 0 ; i < superInterfaces . length ; i ++ ) { if ( isSubTypeOfMvpView ( superInterfaces [ i ] ) ) { return true ; } } return false ; }
Scans the interface inheritance hierarchy and checks if on the root is MvpView . class
100
18
152,667
public static int dpToPx ( Context context , float dp ) { DisplayMetrics displayMetrics = context . getResources ( ) . getDisplayMetrics ( ) ; return ( int ) ( ( dp * displayMetrics . density ) + 0.5 ) ; }
Converts a dp value to a px value
60
11
152,668
public static int pxToDp ( Context context , int px ) { DisplayMetrics displayMetrics = context . getResources ( ) . getDisplayMetrics ( ) ; return ( int ) ( ( px / displayMetrics . density ) + 0.5 ) ; }
Converts pixel in dp
60
6
152,669
public static float pxToSp ( Context context , Float px ) { float scaledDensity = context . getResources ( ) . getDisplayMetrics ( ) . scaledDensity ; return px / scaledDensity ; }
Convertes pixels to sp
48
6
152,670
private P restorePresenterOrRecreateNewPresenterAfterProcessDeath ( ) { P presenter ; if ( keepPresenterInstanceDuringScreenOrientationChanges ) { if ( mosbyViewId != null && ( presenter = PresenterManager . getPresenter ( getActivity ( ) , mosbyViewId ) ) != null ) { // // Presenter restored from cache // if ( DEBUG ) { Log . d ( DEBUG_TAG , "Reused presenter " + presenter + " for view " + delegateCallback . getMvpView ( ) ) ; } return presenter ; } else { // // No presenter found in cache, most likely caused by process death // presenter = createViewIdAndPresenter ( ) ; if ( DEBUG ) { Log . d ( DEBUG_TAG , "No presenter found although view Id was here: " + mosbyViewId + ". Most likely this was caused by a process death. New Presenter created" + presenter + " for view " + delegateCallback . getMvpView ( ) ) ; } return presenter ; } } else { // // starting first time, so create a new presenter // presenter = createViewIdAndPresenter ( ) ; if ( DEBUG ) { Log . d ( DEBUG_TAG , "New presenter " + presenter + " for view " + delegateCallback . getMvpView ( ) ) ; } return presenter ; } }
Creates the presenter instance if not able to reuse presenter from PresenterManager
286
15
152,671
private VS createViewState ( ) { VS viewState = delegateCallback . createViewState ( ) ; if ( viewState == null ) { throw new NullPointerException ( "ViewState returned from createViewState() is null. Fragment is " + fragment ) ; } if ( keepPresenterInstanceDuringScreenOrientationChanges ) { PresenterManager . putViewState ( getActivity ( ) , mosbyViewId , viewState ) ; } return viewState ; }
Creates a new ViewState instance
99
7
152,672
public Observable < ProductDetailsViewState > getDetails ( int productId ) { return getProductWithShoppingCartInfo ( productId ) . subscribeOn ( Schedulers . io ( ) ) . map ( ProductDetailsViewState . DataState :: new ) . cast ( ProductDetailsViewState . class ) . startWith ( new ProductDetailsViewState . LoadingState ( ) ) . onErrorReturn ( ProductDetailsViewState . ErrorState :: new ) ; }
Get the details of a given product
96
7
152,673
public Observable < List < Product > > getAllProducts ( ) { return Observable . zip ( getProducts ( 0 ) , getProducts ( 1 ) , getProducts ( 2 ) , getProducts ( 3 ) , ( products0 , products1 , products2 , products3 ) -> { List < Product > productList = new ArrayList < Product > ( ) ; productList . addAll ( products0 ) ; productList . addAll ( products1 ) ; productList . addAll ( products2 ) ; productList . addAll ( products3 ) ; return productList ; } ) ; }
Get a list with all products from backend
124
8
152,674
public Observable < List < Product > > getAllProductsOfCategory ( String categoryName ) { return getAllProducts ( ) . flatMap ( Observable :: fromIterable ) . filter ( product -> product . getCategory ( ) . equals ( categoryName ) ) . toList ( ) . toObservable ( ) ; }
Get all products of a certain category
69
7
152,675
public Observable < List < String > > getAllCategories ( ) { return getAllProducts ( ) . map ( products -> { Set < String > categories = new HashSet < String > ( ) ; for ( Product p : products ) { categories . add ( p . getCategory ( ) ) ; } List < String > result = new ArrayList < String > ( categories . size ( ) ) ; result . addAll ( categories ) ; return result ; } ) ; }
Get a list with all categories
99
6
152,676
public Observable < Product > getProduct ( int productId ) { return getAllProducts ( ) . flatMap ( products -> Observable . fromIterable ( products ) ) . filter ( product -> product . getId ( ) == productId ) . take ( 1 ) ; }
Get the product with the given id
58
7
152,677
public Observable < List < Product > > loadProductsOfCategory ( String categoryName ) { return backendApi . getAllProductsOfCategory ( categoryName ) . delay ( 3 , TimeUnit . SECONDS ) ; }
Loads all items of a given category
47
8
152,678
private void runQueuedActions ( ) { V view = viewRef == null ? null : viewRef . get ( ) ; if ( view != null ) { while ( ! viewActionQueue . isEmpty ( ) ) { ViewAction < V > action = viewActionQueue . poll ( ) ; action . run ( view ) ; } } }
Runs the queued actions .
72
7
152,679
public static boolean hideKeyboard ( View view ) { if ( view == null ) { throw new NullPointerException ( "View is null!" ) ; } try { InputMethodManager imm = ( InputMethodManager ) view . getContext ( ) . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; if ( imm == null ) { return false ; } imm . hideSoftInputFromWindow ( view . getWindowToken ( ) , 0 ) ; } catch ( Exception e ) { return false ; } return true ; }
Hides the soft keyboard from screen
112
7
152,680
public Observable < SearchViewState > search ( String searchString ) { // Empty String, so no search if ( searchString . isEmpty ( ) ) { return Observable . just ( new SearchViewState . SearchNotStartedYet ( ) ) ; } // search for product return searchEngine . searchFor ( searchString ) . map ( products -> { if ( products . isEmpty ( ) ) { return new SearchViewState . EmptyResult ( searchString ) ; } else { return new SearchViewState . SearchResult ( searchString , products ) ; } } ) . startWith ( new SearchViewState . Loading ( ) ) . onErrorReturn ( error -> new SearchViewState . Error ( searchString , error ) ) ; }
Search for items
153
3
152,681
public Observable < List < Label > > getLabels ( ) { return Observable . just ( mails ) . flatMap ( new Func1 < List < Mail > , Observable < List < Label > > > ( ) { @ Override public Observable < List < Label > > call ( List < Mail > mails ) { delay ( ) ; Observable error = checkExceptions ( ) ; if ( error != null ) { return error ; } List < Label > labels = new ArrayList <> ( 4 ) ; labels . add ( INBOX_LABEL ) ; labels . add ( sentLabel ) ; labels . add ( spamLabel ) ; labels . add ( trashLabel ) ; int inbox = 0 ; int spam = 0 ; int sent = 0 ; int trash = 0 ; for ( Mail m : mails ) { if ( m . isRead ( ) ) { continue ; } switch ( m . getLabel ( ) ) { case Label . INBOX : inbox ++ ; break ; case Label . SENT : sent ++ ; break ; case Label . SPAM : spam ++ ; break ; case Label . TRASH : trash ++ ; break ; } } INBOX_LABEL . setUnreadCount ( inbox ) ; sentLabel . setUnreadCount ( sent ) ; spamLabel . setUnreadCount ( spam ) ; trashLabel . setUnreadCount ( trash ) ; return Observable . just ( labels ) ; } } ) ; }
Get the labels with the number of unread mails .
306
12
152,682
public Observable < List < Mail > > getMailsOfLabel ( final String l ) { return getFilteredMailList ( new Func1 < Mail , Boolean > ( ) { @ Override public Boolean call ( Mail mail ) { return mail . getLabel ( ) . equals ( l ) ; } } ) ; }
Get a list of mails with the given label
68
10
152,683
public Observable < Mail > starMail ( int mailId , final boolean star ) { return getMail ( mailId ) . map ( new Func1 < Mail , Mail > ( ) { @ Override public Mail call ( Mail mail ) { mail . setStarred ( star ) ; return mail ; } } ) ; }
Star or unstar a mail
68
6
152,684
public Observable < Mail > addMailWithDelay ( final Mail mail ) { return Observable . defer ( new Func0 < Observable < Mail > > ( ) { @ Override public Observable < Mail > call ( ) { delay ( ) ; Observable o = checkExceptions ( ) ; if ( o != null ) { return o ; } return Observable . just ( mail ) ; } } ) . flatMap ( new Func1 < Mail , Observable < Mail > > ( ) { @ Override public Observable < Mail > call ( Mail mail ) { return addMail ( mail ) ; } } ) ; }
Creates and saves a new mail
134
7
152,685
private Observable < List < Mail > > getFilteredMailList ( Func1 < Mail , Boolean > filterFnc , final boolean withDelayAndError ) { return Observable . defer ( new Func0 < Observable < Mail > > ( ) { @ Override public Observable < Mail > call ( ) { if ( withDelayAndError ) { delay ( ) ; Observable o = checkExceptions ( ) ; if ( o != null ) { return o ; } } return Observable . from ( mails ) ; } } ) . filter ( filterFnc ) . collect ( new Func0 < List < Mail > > ( ) { @ Override public List < Mail > call ( ) { return new ArrayList < Mail > ( ) ; } } , new Action2 < List < Mail > , Mail > ( ) { @ Override public void call ( List < Mail > mails , Mail mail ) { mails . add ( mail ) ; } } ) . map ( new Func1 < List < Mail > , List < Mail > > ( ) { @ Override public List < Mail > call ( List < Mail > mails ) { Collections . sort ( mails , MailComparator . INSTANCE ) ; return mails ; } } ) ; }
Filters the list of mails by the given criteria
271
11
152,686
public Mail findMail ( int id ) { if ( items == null ) { return null ; } for ( Mail m : items ) { if ( m . getId ( ) == id ) { return m ; } } return null ; }
Finds a mail by his id if displayed in this adapter
49
12
152,687
private boolean isProductMatchingSearchCriteria ( Product product , String searchQueryText ) { String words [ ] = searchQueryText . split ( " " ) ; for ( String w : words ) { if ( product . getName ( ) . contains ( w ) ) return true ; if ( product . getDescription ( ) . contains ( w ) ) return true ; if ( product . getCategory ( ) . contains ( w ) ) return true ; } return false ; }
Filters those items that contains the search query text in name description or category
98
15
152,688
public void addAndStartListener ( final ProcessorListener < ApiType > processorListener ) { lock . writeLock ( ) . lock ( ) ; try { addListenerLocked ( processorListener ) ; executorService . execute ( processorListener ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } }
addAndStartListener first adds the specific processorListener then starts the listener with executor .
67
18
152,689
public void addListener ( final ProcessorListener < ApiType > processorListener ) { lock . writeLock ( ) . lock ( ) ; try { addListenerLocked ( processorListener ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } }
addListener adds the specific processorListener but not start it .
55
12
152,690
public void run ( ) { lock . readLock ( ) . lock ( ) ; try { if ( Collections . isEmptyCollection ( listeners ) ) { return ; } for ( ProcessorListener listener : listeners ) { executorService . execute ( listener ) ; } } finally { lock . readLock ( ) . unlock ( ) ; } }
starts the processor listeners .
69
6
152,691
public void distribute ( ProcessorListener . Notification < ApiType > obj , boolean isSync ) { lock . readLock ( ) . lock ( ) ; try { if ( isSync ) { for ( ProcessorListener < ApiType > listener : syncingListeners ) { listener . add ( obj ) ; } } else { for ( ProcessorListener < ApiType > listener : listeners ) { listener . add ( obj ) ; } } } finally { lock . readLock ( ) . unlock ( ) ; } }
distribute the object among listeners .
106
7
152,692
public void setUsername ( String username ) { for ( Authentication auth : authentications . values ( ) ) { if ( auth instanceof HttpBasicAuth ) { ( ( HttpBasicAuth ) auth ) . setUsername ( username ) ; return ; } } throw new RuntimeException ( "No HTTP basic authentication configured!" ) ; }
Helper method to set username for the first HTTP basic authentication .
70
12
152,693
public void setPassword ( String password ) { for ( Authentication auth : authentications . values ( ) ) { if ( auth instanceof HttpBasicAuth ) { ( ( HttpBasicAuth ) auth ) . setPassword ( password ) ; return ; } } throw new RuntimeException ( "No HTTP basic authentication configured!" ) ; }
Helper method to set password for the first HTTP basic authentication .
68
12
152,694
public void setApiKey ( String apiKey ) { for ( Authentication auth : authentications . values ( ) ) { if ( auth instanceof ApiKeyAuth ) { ( ( ApiKeyAuth ) auth ) . setApiKey ( apiKey ) ; return ; } } throw new RuntimeException ( "No API key authentication configured!" ) ; }
Helper method to set API key value for the first API key authentication .
74
14
152,695
public void setApiKeyPrefix ( String apiKeyPrefix ) { for ( Authentication auth : authentications . values ( ) ) { if ( auth instanceof ApiKeyAuth ) { ( ( ApiKeyAuth ) auth ) . setApiKeyPrefix ( apiKeyPrefix ) ; return ; } } throw new RuntimeException ( "No API key authentication configured!" ) ; }
Helper method to set API key prefix for the first API key authentication .
82
14
152,696
public void setAccessToken ( String accessToken ) { for ( Authentication auth : authentications . values ( ) ) { if ( auth instanceof OAuth ) { ( ( OAuth ) auth ) . setAccessToken ( accessToken ) ; return ; } } throw new RuntimeException ( "No OAuth2 authentication configured!" ) ; }
Helper method to set access token for the first OAuth2 authentication .
69
14
152,697
@ SuppressWarnings ( "unchecked" ) public < T > T deserialize ( Response response , Type returnType ) throws ApiException { if ( response == null || returnType == null ) { return null ; } if ( "byte[]" . equals ( returnType . toString ( ) ) ) { // Handle binary response (byte array). try { return ( T ) response . body ( ) . bytes ( ) ; } catch ( IOException e ) { throw new ApiException ( e ) ; } } else if ( returnType . equals ( File . class ) ) { // Handle file downloading. return ( T ) downloadFileFromResponse ( response ) ; } String respBody ; try { if ( response . body ( ) != null ) respBody = response . body ( ) . string ( ) ; else respBody = null ; } catch ( IOException e ) { throw new ApiException ( e ) ; } if ( respBody == null || "" . equals ( respBody ) ) { return null ; } String contentType = response . headers ( ) . get ( "Content-Type" ) ; if ( contentType == null ) { // ensuring a default content type contentType = "application/json" ; } if ( isJsonMime ( contentType ) ) { return json . deserialize ( respBody , returnType ) ; } else if ( returnType . equals ( String . class ) ) { // Expecting string, return the raw response body. return ( T ) respBody ; } else { throw new ApiException ( "Content type \"" + contentType + "\" is not supported for type: " + returnType , response . code ( ) , response . headers ( ) . toMultimap ( ) , respBody ) ; } }
Deserialize response body to Java object according to the return type and the Content - Type response header .
375
21
152,698
public RequestBody serialize ( Object obj , String contentType ) throws ApiException { if ( obj instanceof byte [ ] ) { // Binary (byte array) body parameter support. return RequestBody . create ( MediaType . parse ( contentType ) , ( byte [ ] ) obj ) ; } else if ( obj instanceof File ) { // File body parameter support. return RequestBody . create ( MediaType . parse ( contentType ) , ( File ) obj ) ; } else if ( isJsonMime ( contentType ) ) { String content ; if ( obj != null ) { content = json . serialize ( obj ) ; } else { content = null ; } return RequestBody . create ( MediaType . parse ( contentType ) , content ) ; } else { throw new ApiException ( "Content type \"" + contentType + "\" is not supported" ) ; } }
Serialize the given Java object into request body according to the object s class and the request Content - Type .
187
22
152,699
public File downloadFileFromResponse ( Response response ) throws ApiException { try { File file = prepareDownloadFile ( response ) ; BufferedSink sink = Okio . buffer ( Okio . sink ( file ) ) ; sink . writeAll ( response . body ( ) . source ( ) ) ; sink . close ( ) ; return file ; } catch ( IOException e ) { throw new ApiException ( e ) ; } }
Download file from the given response .
91
7