idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
28,600
public void write ( EncryptedWorkspace workspace , Writer writer ) throws WorkspaceWriterException { if ( workspace == null ) { throw new IllegalArgumentException ( "EncryptedWorkspace cannot be null." ) ; } if ( writer == null ) { throw new IllegalArgumentException ( "Writer cannot be null." ) ; } try { ObjectMapper objectMapper = new ObjectMapper ( ) ; if ( indentOutput ) { objectMapper . enable ( SerializationFeature . INDENT_OUTPUT ) ; } objectMapper . setSerializationInclusion ( JsonInclude . Include . NON_NULL ) ; objectMapper . setSerializationInclusion ( JsonInclude . Include . NON_EMPTY ) ; objectMapper . disable ( SerializationFeature . WRITE_DATES_AS_TIMESTAMPS ) ; objectMapper . setDateFormat ( new ISO8601DateFormat ( ) ) ; writer . write ( objectMapper . writeValueAsString ( workspace ) ) ; } catch ( Exception e ) { throw new WorkspaceWriterException ( "Could not write as JSON" , e ) ; } }
Writes an encrypted workspace definition as a JSON string to the specified Writer object .
240
16
28,601
private void checkElement ( Element elementToBeAdded ) { if ( ! ( elementToBeAdded instanceof Person ) && ! ( elementToBeAdded instanceof SoftwareSystem ) && ! ( elementToBeAdded instanceof Container ) && ! ( elementToBeAdded instanceof Component ) ) { throw new IllegalArgumentException ( "Only people, software systems, containers and components can be added to dynamic views." ) ; } // people can always be added if ( elementToBeAdded instanceof Person ) { return ; } // if the scope of this dynamic view is a software system, we only want: // - containers inside that software system // - other software systems if ( element instanceof SoftwareSystem ) { if ( elementToBeAdded . equals ( element ) ) { throw new IllegalArgumentException ( elementToBeAdded . getName ( ) + " is already the scope of this view and cannot be added to it." ) ; } if ( elementToBeAdded instanceof Container && ! elementToBeAdded . getParent ( ) . equals ( element ) ) { throw new IllegalArgumentException ( "Only containers that reside inside " + element . getName ( ) + " can be added to this view." ) ; } if ( elementToBeAdded instanceof Component ) { throw new IllegalArgumentException ( "Components can't be added to a dynamic view when the scope is a software system." ) ; } } // if the scope of this dynamic view is a container, we only want other containers inside the same software system // and other components inside the container if ( element instanceof Container ) { if ( elementToBeAdded . equals ( element ) || elementToBeAdded . equals ( element . getParent ( ) ) ) { throw new IllegalArgumentException ( elementToBeAdded . getName ( ) + " is already the scope of this view and cannot be added to it." ) ; } if ( elementToBeAdded instanceof Container && ! elementToBeAdded . getParent ( ) . equals ( element . getParent ( ) ) ) { throw new IllegalArgumentException ( "Only containers that reside inside " + element . getParent ( ) . getName ( ) + " can be added to this view." ) ; } if ( elementToBeAdded instanceof Component && ! elementToBeAdded . getParent ( ) . equals ( element ) ) { throw new IllegalArgumentException ( "Only components that reside inside " + element . getName ( ) + " can be added to this view." ) ; } } if ( element == null ) { if ( ! ( elementToBeAdded instanceof SoftwareSystem ) ) { throw new IllegalArgumentException ( "Only people and software systems can be added to this dynamic view." ) ; } } }
This checks that only appropriate elements can be added to the view .
573
13
28,602
@ Override public int compare ( String file0 , String file1 ) { Matcher m0 = pattern . matcher ( file0 ) ; Matcher m1 = pattern . matcher ( file1 ) ; if ( ! m0 . matches ( ) ) { Log . w ( TAG , "could not parse upgrade script file: " + file0 ) ; throw new SQLiteAssetException ( "Invalid upgrade script file" ) ; } if ( ! m1 . matches ( ) ) { Log . w ( TAG , "could not parse upgrade script file: " + file1 ) ; throw new SQLiteAssetException ( "Invalid upgrade script file" ) ; } int v0_from = Integer . valueOf ( m0 . group ( 1 ) ) ; int v1_from = Integer . valueOf ( m1 . group ( 1 ) ) ; int v0_to = Integer . valueOf ( m0 . group ( 2 ) ) ; int v1_to = Integer . valueOf ( m1 . group ( 2 ) ) ; if ( v0_from == v1_from ) { // 'from' versions match for both; check 'to' version next if ( v0_to == v1_to ) { return 0 ; } return v0_to < v1_to ? - 1 : 1 ; } return v0_from < v1_from ? - 1 : 1 ; }
Compares the two specified upgrade script strings to determine their relative ordering considering their two version numbers . Assumes all database names used are the same as this function only compares the two version numbers .
297
38
28,603
private void init ( final Context context , final AttributeSet attrs ) { if ( isInEditMode ( ) ) return ; final TypedArray typedArray = context . obtainStyledAttributes ( attrs , R . styleable . RippleView ) ; rippleColor = typedArray . getColor ( R . styleable . RippleView_rv_color , getResources ( ) . getColor ( R . color . rippelColor ) ) ; rippleType = typedArray . getInt ( R . styleable . RippleView_rv_type , 0 ) ; hasToZoom = typedArray . getBoolean ( R . styleable . RippleView_rv_zoom , false ) ; isCentered = typedArray . getBoolean ( R . styleable . RippleView_rv_centered , false ) ; rippleDuration = typedArray . getInteger ( R . styleable . RippleView_rv_rippleDuration , rippleDuration ) ; frameRate = typedArray . getInteger ( R . styleable . RippleView_rv_framerate , frameRate ) ; rippleAlpha = typedArray . getInteger ( R . styleable . RippleView_rv_alpha , rippleAlpha ) ; ripplePadding = typedArray . getDimensionPixelSize ( R . styleable . RippleView_rv_ripplePadding , 0 ) ; canvasHandler = new Handler ( ) ; zoomScale = typedArray . getFloat ( R . styleable . RippleView_rv_zoomScale , 1.03f ) ; zoomDuration = typedArray . getInt ( R . styleable . RippleView_rv_zoomDuration , 200 ) ; typedArray . recycle ( ) ; paint = new Paint ( ) ; paint . setAntiAlias ( true ) ; paint . setStyle ( Paint . Style . FILL ) ; paint . setColor ( rippleColor ) ; paint . setAlpha ( rippleAlpha ) ; this . setWillNotDraw ( false ) ; gestureDetector = new GestureDetector ( context , new GestureDetector . SimpleOnGestureListener ( ) { @ Override public void onLongPress ( MotionEvent event ) { super . onLongPress ( event ) ; animateRipple ( event ) ; sendClickEvent ( true ) ; } @ Override public boolean onSingleTapConfirmed ( MotionEvent e ) { return true ; } @ Override public boolean onSingleTapUp ( MotionEvent e ) { return true ; } } ) ; this . setDrawingCacheEnabled ( true ) ; this . setClickable ( true ) ; }
Method that initializes all fields and sets listeners
545
9
28,604
private void createAnimation ( final float x , final float y ) { if ( this . isEnabled ( ) && ! animationRunning ) { if ( hasToZoom ) this . startAnimation ( scaleAnimation ) ; radiusMax = Math . max ( WIDTH , HEIGHT ) ; if ( rippleType != 2 ) radiusMax /= 2 ; radiusMax -= ripplePadding ; if ( isCentered || rippleType == 1 ) { this . x = getMeasuredWidth ( ) / 2 ; this . y = getMeasuredHeight ( ) / 2 ; } else { this . x = x ; this . y = y ; } animationRunning = true ; if ( rippleType == 1 && originBitmap == null ) originBitmap = getDrawingCache ( true ) ; invalidate ( ) ; } }
Create Ripple animation centered at x y
169
7
28,605
private void sendClickEvent ( final Boolean isLongClick ) { if ( getParent ( ) instanceof AdapterView ) { final AdapterView adapterView = ( AdapterView ) getParent ( ) ; final int position = adapterView . getPositionForView ( this ) ; final long id = adapterView . getItemIdAtPosition ( position ) ; if ( isLongClick ) { if ( adapterView . getOnItemLongClickListener ( ) != null ) adapterView . getOnItemLongClickListener ( ) . onItemLongClick ( adapterView , this , position , id ) ; } else { if ( adapterView . getOnItemClickListener ( ) != null ) adapterView . getOnItemClickListener ( ) . onItemClick ( adapterView , this , position , id ) ; } } }
Send a click event if parent view is a Listview instance
167
12
28,606
public static TypeAdapterFactory create ( ) { if ( geometryTypeFactory == null ) { geometryTypeFactory = RuntimeTypeAdapterFactory . of ( Geometry . class , "type" , true ) . registerSubtype ( GeometryCollection . class , "GeometryCollection" ) . registerSubtype ( Point . class , "Point" ) . registerSubtype ( MultiPoint . class , "MultiPoint" ) . registerSubtype ( LineString . class , "LineString" ) . registerSubtype ( MultiLineString . class , "MultiLineString" ) . registerSubtype ( Polygon . class , "Polygon" ) . registerSubtype ( MultiPolygon . class , "MultiPolygon" ) ; } return geometryTypeFactory ; }
Create a new instance of Geometry type adapter factory this is passed into the Gson Builder .
157
19
28,607
public List < LineString > lineStrings ( ) { List < List < Point >> coordinates = coordinates ( ) ; List < LineString > lineStrings = new ArrayList <> ( coordinates . size ( ) ) ; for ( List < Point > points : coordinates ) { lineStrings . add ( LineString . fromLngLats ( points ) ) ; } return lineStrings ; }
Returns a list of LineStrings which are currently making up this MultiLineString .
83
17
28,608
public static String formatCoordinate ( double coordinate ) { DecimalFormat decimalFormat = new DecimalFormat ( "0.######" , new DecimalFormatSymbols ( Locale . US ) ) ; return String . format ( Locale . US , "%s" , decimalFormat . format ( coordinate ) ) ; }
Useful to remove any trailing zeros and prevent a coordinate being over 7 significant figures .
68
18
28,609
public static String formatCoordinate ( double coordinate , int precision ) { String pattern = "0." + new String ( new char [ precision ] ) . replace ( "\0" , "0" ) ; DecimalFormat df = ( DecimalFormat ) DecimalFormat . getInstance ( Locale . US ) ; df . applyPattern ( pattern ) ; df . setRoundingMode ( RoundingMode . FLOOR ) ; return df . format ( coordinate ) ; }
Allows the specific adjusting of a coordinates precision .
98
9
28,610
public static String formatRadiuses ( double [ ] radiuses ) { if ( radiuses == null || radiuses . length == 0 ) { return null ; } String [ ] radiusesFormatted = new String [ radiuses . length ] ; for ( int i = 0 ; i < radiuses . length ; i ++ ) { if ( radiuses [ i ] == Double . POSITIVE_INFINITY ) { radiusesFormatted [ i ] = "unlimited" ; } else { radiusesFormatted [ i ] = String . format ( Locale . US , "%s" , TextUtils . formatCoordinate ( radiuses [ i ] ) ) ; } } return join ( ";" , radiusesFormatted ) ; }
Used in various APIs to format the user provided radiuses to a String matching the APIs format .
156
19
28,611
public static String formatBearing ( List < Double [ ] > bearings ) { if ( bearings . isEmpty ( ) ) { return null ; } String [ ] bearingFormatted = new String [ bearings . size ( ) ] ; for ( int i = 0 ; i < bearings . size ( ) ; i ++ ) { if ( bearings . get ( i ) . length == 0 ) { bearingFormatted [ i ] = "" ; } else { bearingFormatted [ i ] = String . format ( Locale . US , "%s,%s" , TextUtils . formatCoordinate ( bearings . get ( i ) [ 0 ] ) , TextUtils . formatCoordinate ( bearings . get ( i ) [ 1 ] ) ) ; } } return TextUtils . join ( ";" , bearingFormatted ) ; }
Formats the bearing variables from the raw values to a string which can than be used for the request URL .
172
22
28,612
public static String formatDistributions ( List < Integer [ ] > distributions ) { if ( distributions . isEmpty ( ) ) { return null ; } String [ ] distributionsFormatted = new String [ distributions . size ( ) ] ; for ( int i = 0 ; i < distributions . size ( ) ; i ++ ) { if ( distributions . get ( i ) . length == 0 ) { distributionsFormatted [ i ] = "" ; } else { distributionsFormatted [ i ] = String . format ( Locale . US , "%s,%s" , TextUtils . formatCoordinate ( distributions . get ( i ) [ 0 ] ) , TextUtils . formatCoordinate ( distributions . get ( i ) [ 1 ] ) ) ; } } return TextUtils . join ( ";" , distributionsFormatted ) ; }
converts the list of integer arrays to a string ready for API consumption .
173
15
28,613
public static String formatApproaches ( String [ ] approaches ) { for ( int i = 0 ; i < approaches . length ; i ++ ) { if ( approaches [ i ] == null ) { approaches [ i ] = "" ; } else if ( ! approaches [ i ] . equals ( "unrestricted" ) && ! approaches [ i ] . equals ( "curb" ) && ! approaches [ i ] . isEmpty ( ) ) { return null ; } } return TextUtils . join ( ";" , approaches ) ; }
Converts String array with approaches values to a string ready for API consumption . An approach could be unrestricted curb or null .
111
24
28,614
public static String formatWaypointNames ( String [ ] waypointNames ) { for ( int i = 0 ; i < waypointNames . length ; i ++ ) { if ( waypointNames [ i ] == null ) { waypointNames [ i ] = "" ; } } return TextUtils . join ( ";" , waypointNames ) ; }
Converts String array with waypoint_names values to a string ready for API consumption .
74
18
28,615
public static Point fromLngLat ( @ FloatRange ( from = MIN_LONGITUDE , to = MAX_LONGITUDE ) double longitude , @ FloatRange ( from = MIN_LATITUDE , to = MAX_LATITUDE ) double latitude ) { List < Double > coordinates = CoordinateShifterManager . getCoordinateShifter ( ) . shiftLonLat ( longitude , latitude ) ; return new Point ( TYPE , null , coordinates ) ; }
Create a new instance of this class defining a longitude and latitude value in that respective order . Longitude values are limited to a - 180 to 180 range and latitude s limited to - 90 to 90 as the spec defines . While no limit is placed on decimal precision for performance reasons when serializing and deserializing it is suggested to limit decimal precision to within 6 decimal places .
107
76
28,616
private static boolean isLinearRing ( LineString lineString ) { if ( lineString . coordinates ( ) . size ( ) < 4 ) { throw new GeoJsonException ( "LinearRings need to be made up of 4 or more coordinates." ) ; } if ( ! ( lineString . coordinates ( ) . get ( 0 ) . equals ( lineString . coordinates ( ) . get ( lineString . coordinates ( ) . size ( ) - 1 ) ) ) ) { throw new GeoJsonException ( "LinearRings require first and last coordinate to be identical." ) ; } return true ; }
Checks to ensure that the LineStrings defining the polygon correctly and adhering to the linear ring rules .
128
24
28,617
protected S getService ( ) { // No need to recreate it if ( service != null ) { return service ; } Retrofit . Builder retrofitBuilder = new Retrofit . Builder ( ) . baseUrl ( baseUrl ( ) ) . addConverterFactory ( GsonConverterFactory . create ( getGsonBuilder ( ) . create ( ) ) ) ; if ( getCallFactory ( ) != null ) { retrofitBuilder . callFactory ( getCallFactory ( ) ) ; } else { retrofitBuilder . client ( getOkHttpClient ( ) ) ; } retrofit = retrofitBuilder . build ( ) ; service = ( S ) retrofit . create ( serviceType ) ; return service ; }
Creates the Retrofit object and the service if they are not already created . Subclasses can override getGsonBuilder to add anything to the GsonBuilder .
149
33
28,618
protected synchronized OkHttpClient getOkHttpClient ( ) { if ( okHttpClient == null ) { if ( isEnableDebug ( ) ) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor ( ) ; logging . setLevel ( HttpLoggingInterceptor . Level . BASIC ) ; OkHttpClient . Builder httpClient = new OkHttpClient . Builder ( ) ; httpClient . addInterceptor ( logging ) ; okHttpClient = httpClient . build ( ) ; } else { okHttpClient = new OkHttpClient ( ) ; } } return okHttpClient ; }
Used Internally .
126
4
28,619
private static String formatWaypointTargets ( Point [ ] waypointTargets ) { String [ ] coordinatesFormatted = new String [ waypointTargets . length ] ; int index = 0 ; for ( Point target : waypointTargets ) { if ( target == null ) { coordinatesFormatted [ index ++ ] = "" ; } else { coordinatesFormatted [ index ++ ] = String . format ( Locale . US , "%s,%s" , TextUtils . formatCoordinate ( target . longitude ( ) ) , TextUtils . formatCoordinate ( target . latitude ( ) ) ) ; } } return TextUtils . join ( ";" , coordinatesFormatted ) ; }
Converts array of Points with waypoint_targets values to a string ready for API consumption .
150
21
28,620
public List < Polygon > polygons ( ) { List < List < List < Point >>> coordinates = coordinates ( ) ; List < Polygon > polygons = new ArrayList <> ( coordinates . size ( ) ) ; for ( List < List < Point > > points : coordinates ) { polygons . add ( Polygon . fromLngLats ( points ) ) ; } return polygons ; }
Returns a list of polygons which make up this MultiPolygon instance .
84
15
28,621
public String toJson ( ) { GsonBuilder gson = new GsonBuilder ( ) ; gson . registerTypeAdapterFactory ( DirectionsAdapterFactory . create ( ) ) ; gson . registerTypeAdapter ( Point . class , new PointAsCoordinatesTypeAdapter ( ) ) ; return gson . create ( ) . toJson ( this ) ; }
This takes the currently defined values found inside this instance and converts it to a json string .
77
18
28,622
public HttpUrl url ( ) { HttpUrl . Builder urlBuilder = HttpUrl . parse ( baseUrl ( ) ) . newBuilder ( ) . addPathSegment ( "styles" ) . addPathSegment ( "v1" ) . addPathSegment ( user ( ) ) . addPathSegment ( styleId ( ) ) . addPathSegment ( "static" ) . addQueryParameter ( "access_token" , accessToken ( ) ) ; List < String > annotations = new ArrayList <> ( ) ; if ( staticMarkerAnnotations ( ) != null ) { List < String > markerStrings = new ArrayList <> ( staticMarkerAnnotations ( ) . size ( ) ) ; for ( StaticMarkerAnnotation marker : staticMarkerAnnotations ( ) ) { markerStrings . add ( marker . url ( ) ) ; } annotations . addAll ( markerStrings ) ; } if ( staticPolylineAnnotations ( ) != null ) { String [ ] polylineStringArray = new String [ staticPolylineAnnotations ( ) . size ( ) ] ; for ( StaticPolylineAnnotation polyline : staticPolylineAnnotations ( ) ) { polylineStringArray [ staticPolylineAnnotations ( ) . indexOf ( polyline ) ] = polyline . url ( ) ; } annotations . addAll ( Arrays . asList ( polylineStringArray ) ) ; } if ( geoJson ( ) != null ) { annotations . add ( String . format ( Locale . US , "geojson(%s)" , geoJson ( ) . toJson ( ) ) ) ; } if ( ! annotations . isEmpty ( ) ) { urlBuilder . addPathSegment ( TextUtils . join ( "," , annotations . toArray ( ) ) ) ; } urlBuilder . addPathSegment ( cameraAuto ( ) ? CAMERA_AUTO : generateLocationPathSegment ( ) ) ; if ( beforeLayer ( ) != null ) { urlBuilder . addQueryParameter ( BEFORE_LAYER , beforeLayer ( ) ) ; } if ( ! attribution ( ) ) { urlBuilder . addQueryParameter ( "attribution" , "false" ) ; } if ( ! logo ( ) ) { urlBuilder . addQueryParameter ( "logo" , "false" ) ; } // Has to be last segment in URL urlBuilder . addPathSegment ( generateSizePathSegment ( ) ) ; return urlBuilder . build ( ) ; }
Returns the formatted URL string meant to be passed to your Http client for retrieval of the actual Mapbox Static Image .
532
24
28,623
private static void simpleMapboxDirectionsRequest ( ) throws IOException { MapboxDirections . Builder builder = MapboxDirections . builder ( ) ; // 1. Pass in all the required information to get a simple directions route. builder . accessToken ( BuildConfig . MAPBOX_ACCESS_TOKEN ) ; builder . origin ( Point . fromLngLat ( - 95.6332 , 29.7890 ) ) ; builder . destination ( Point . fromLngLat ( - 95.3591 , 29.7576 ) ) ; // 2. That's it! Now execute the command and get the response. Response < DirectionsResponse > response = builder . build ( ) . executeCall ( ) ; // 3. Log information from the response System . out . printf ( "Check that the GET response is successful %b" , response . isSuccessful ( ) ) ; System . out . printf ( "%nGet the first routes distance from origin to destination: %f" , response . body ( ) . routes ( ) . get ( 0 ) . distance ( ) ) ; }
Demonstrates how to make the most basic GET directions request .
226
13
28,624
private static void asyncMapboxDirectionsRequest ( ) { // 1. Pass in all the required information to get a route. MapboxDirections request = MapboxDirections . builder ( ) . accessToken ( BuildConfig . MAPBOX_ACCESS_TOKEN ) . origin ( Point . fromLngLat ( - 95.6332 , 29.7890 ) ) . destination ( Point . fromLngLat ( - 95.3591 , 29.7576 ) ) . profile ( DirectionsCriteria . PROFILE_CYCLING ) . steps ( true ) . build ( ) ; // 2. Now request the route using a async call request . enqueueCall ( new Callback < DirectionsResponse > ( ) { @ Override public void onResponse ( Call < DirectionsResponse > call , Response < DirectionsResponse > response ) { // 3. Log information from the response if ( response . isSuccessful ( ) ) { System . out . printf ( "%nGet the street name of the first step along the route: %s" , response . body ( ) . routes ( ) . get ( 0 ) . legs ( ) . get ( 0 ) . steps ( ) . get ( 0 ) . name ( ) ) ; } } @ Override public void onFailure ( Call < DirectionsResponse > call , Throwable throwable ) { System . err . println ( throwable ) ; } } ) ; }
Demonstrates how to make an asynchronous directions request .
294
11
28,625
public String getStringProperty ( String key ) { JsonElement propertyKey = properties ( ) . get ( key ) ; return propertyKey == null ? null : propertyKey . getAsString ( ) ; }
Convenience method to get a String member .
43
10
28,626
public Number getNumberProperty ( String key ) { JsonElement propertyKey = properties ( ) . get ( key ) ; return propertyKey == null ? null : propertyKey . getAsNumber ( ) ; }
Convenience method to get a Number member .
43
10
28,627
public Boolean getBooleanProperty ( String key ) { JsonElement propertyKey = properties ( ) . get ( key ) ; return propertyKey == null ? null : propertyKey . getAsBoolean ( ) ; }
Convenience method to get a Boolean member .
45
10
28,628
public Character getCharacterProperty ( String key ) { JsonElement propertyKey = properties ( ) . get ( key ) ; return propertyKey == null ? null : propertyKey . getAsCharacter ( ) ; }
Convenience method to get a Character member .
43
10
28,629
@ Override public JsonElement serialize ( Point src , Type typeOfSrc , JsonSerializationContext context ) { JsonArray rawCoordinates = new JsonArray ( ) ; // Unshift coordinates List < Double > unshiftedCoordinates = CoordinateShifterManager . getCoordinateShifter ( ) . unshiftPoint ( src ) ; rawCoordinates . add ( new JsonPrimitive ( GeoJsonUtils . trim ( unshiftedCoordinates . get ( 0 ) ) ) ) ; rawCoordinates . add ( new JsonPrimitive ( GeoJsonUtils . trim ( unshiftedCoordinates . get ( 1 ) ) ) ) ; // Includes altitude if ( src . hasAltitude ( ) ) { rawCoordinates . add ( new JsonPrimitive ( unshiftedCoordinates . get ( 2 ) ) ) ; } return rawCoordinates ; }
Required to handle the special case where the altitude might be a Double . NaN which isn t a valid double value as per JSON specification .
199
28
28,630
public static boolean isAccessTokenValid ( String accessToken ) { return ! TextUtils . isEmpty ( accessToken ) && ! ( ! accessToken . startsWith ( "pk." ) && ! accessToken . startsWith ( "sk." ) && ! accessToken . startsWith ( "tk." ) ) ; }
Checks that the provided access token is not empty or null and that it starts with the right prefixes . Note that this method does not check Mapbox servers to verify that it actually belongs to an account .
67
42
28,631
public static void geojsonType ( GeoJson value , String type , String name ) { if ( type == null || type . length ( ) == 0 || name == null || name . length ( ) == 0 ) { throw new TurfException ( "Type and name required" ) ; } if ( value == null || ! value . type ( ) . equals ( type ) ) { throw new TurfException ( "Invalid input to " + name + ": must be a " + type + ", given " + ( value != null ? value . type ( ) : " null" ) ) ; } }
Enforce expectations about types of GeoJson objects for Turf .
127
14
28,632
@ Deprecated public static BoundingBox fromCoordinates ( @ FloatRange ( from = MIN_LONGITUDE , to = GeoJsonConstants . MAX_LONGITUDE ) double west , @ FloatRange ( from = MIN_LATITUDE , to = GeoJsonConstants . MAX_LATITUDE ) double south , @ FloatRange ( from = MIN_LONGITUDE , to = GeoJsonConstants . MAX_LONGITUDE ) double east , @ FloatRange ( from = MIN_LATITUDE , to = GeoJsonConstants . MAX_LATITUDE ) double north ) { return fromLngLats ( west , south , east , north ) ; }
Define a new instance of this class by passing in four coordinates in the same order they would appear in the serialized GeoJson form . Limits are placed on the minimum and maximum coordinate values which can exist and comply with the GeoJson spec .
163
51
28,633
@ NonNull public static String encode ( @ NonNull final List < Point > path , int precision ) { long lastLat = 0 ; long lastLng = 0 ; final StringBuilder result = new StringBuilder ( ) ; // OSRM uses precision=6, the default Polyline spec divides by 1E5, capping at precision=5 double factor = Math . pow ( 10 , precision ) ; for ( final Point point : path ) { long lat = Math . round ( point . latitude ( ) * factor ) ; long lng = Math . round ( point . longitude ( ) * factor ) ; long varLat = lat - lastLat ; long varLng = lng - lastLng ; encode ( varLat , result ) ; encode ( varLng , result ) ; lastLat = lat ; lastLng = lng ; } return result . toString ( ) ; }
Encodes a sequence of Points into an encoded path string .
186
12
28,634
private static double getSqDist ( Point p1 , Point p2 ) { double dx = p1 . longitude ( ) - p2 . longitude ( ) ; double dy = p1 . latitude ( ) - p2 . latitude ( ) ; return dx * dx + dy * dy ; }
Square distance between 2 points .
63
6
28,635
private static double getSqSegDist ( Point point , Point p1 , Point p2 ) { double horizontal = p1 . longitude ( ) ; double vertical = p1 . latitude ( ) ; double diffHorizontal = p2 . longitude ( ) - horizontal ; double diffVertical = p2 . latitude ( ) - vertical ; if ( diffHorizontal != 0 || diffVertical != 0 ) { double total = ( ( point . longitude ( ) - horizontal ) * diffHorizontal + ( point . latitude ( ) - vertical ) * diffVertical ) / ( diffHorizontal * diffHorizontal + diffVertical * diffVertical ) ; if ( total > 1 ) { horizontal = p2 . longitude ( ) ; vertical = p2 . latitude ( ) ; } else if ( total > 0 ) { horizontal += diffHorizontal * total ; vertical += diffVertical * total ; } } diffHorizontal = point . longitude ( ) - horizontal ; diffVertical = point . latitude ( ) - vertical ; return diffHorizontal * diffHorizontal + diffVertical * diffVertical ; }
Square distance from a point to a segment .
234
9
28,636
private static List < Point > simplifyRadialDist ( List < Point > points , double sqTolerance ) { Point prevPoint = points . get ( 0 ) ; ArrayList < Point > newPoints = new ArrayList <> ( ) ; newPoints . add ( prevPoint ) ; Point point = null ; for ( int i = 1 , len = points . size ( ) ; i < len ; i ++ ) { point = points . get ( i ) ; if ( getSqDist ( point , prevPoint ) > sqTolerance ) { newPoints . add ( point ) ; prevPoint = point ; } } if ( ! prevPoint . equals ( point ) ) { newPoints . add ( point ) ; } return newPoints ; }
Basic distance - based simplification .
155
7
28,637
private static List < Point > simplifyDouglasPeucker ( List < Point > points , double sqTolerance ) { int last = points . size ( ) - 1 ; ArrayList < Point > simplified = new ArrayList <> ( ) ; simplified . add ( points . get ( 0 ) ) ; simplified . addAll ( simplifyDpStep ( points , 0 , last , sqTolerance , simplified ) ) ; simplified . add ( points . get ( last ) ) ; return simplified ; }
Simplification using Ramer - Douglas - Peucker algorithm .
102
13
28,638
public static double trim ( double value ) { if ( value > MAX_DOUBLE_TO_ROUND || value < - MAX_DOUBLE_TO_ROUND ) { return value ; } return Math . round ( value * ROUND_PRECISION ) / ROUND_PRECISION ; }
Trims a double value to have only 7 digits after period .
66
13
28,639
public void showHint ( ) { final int [ ] screenPos = new int [ 2 ] ; final Rect displayFrame = new Rect ( ) ; getLocationOnScreen ( screenPos ) ; getWindowVisibleDisplayFrame ( displayFrame ) ; final Context context = getContext ( ) ; final int width = getWidth ( ) ; final int height = getHeight ( ) ; final int midy = screenPos [ 1 ] + height / 2 ; int referenceX = screenPos [ 0 ] + width / 2 ; if ( ViewCompat . getLayoutDirection ( this ) == ViewCompat . LAYOUT_DIRECTION_LTR ) { final int screenWidth = context . getResources ( ) . getDisplayMetrics ( ) . widthPixels ; referenceX = screenWidth - referenceX ; // mirror } StringBuilder hint = new StringBuilder ( "#" ) ; if ( Color . alpha ( color ) != 255 ) { hint . append ( Integer . toHexString ( color ) . toUpperCase ( Locale . ENGLISH ) ) ; } else { hint . append ( String . format ( "%06X" , 0xFFFFFF & color ) . toUpperCase ( Locale . ENGLISH ) ) ; } Toast cheatSheet = Toast . makeText ( context , hint . toString ( ) , Toast . LENGTH_SHORT ) ; if ( midy < displayFrame . height ( ) ) { // Show along the top; follow action buttons cheatSheet . setGravity ( Gravity . TOP | GravityCompat . END , referenceX , screenPos [ 1 ] + height - displayFrame . top ) ; } else { // Show along the bottom center cheatSheet . setGravity ( Gravity . BOTTOM | Gravity . CENTER_HORIZONTAL , 0 , height ) ; } cheatSheet . show ( ) ; }
Show a toast message with the hex color code below the view .
394
13
28,640
View createPickerView ( ) { View contentView = View . inflate ( getActivity ( ) , R . layout . cpv_dialog_color_picker , null ) ; colorPicker = ( ColorPickerView ) contentView . findViewById ( R . id . cpv_color_picker_view ) ; ColorPanelView oldColorPanel = ( ColorPanelView ) contentView . findViewById ( R . id . cpv_color_panel_old ) ; newColorPanel = ( ColorPanelView ) contentView . findViewById ( R . id . cpv_color_panel_new ) ; ImageView arrowRight = ( ImageView ) contentView . findViewById ( R . id . cpv_arrow_right ) ; hexEditText = ( EditText ) contentView . findViewById ( R . id . cpv_hex ) ; try { final TypedValue value = new TypedValue ( ) ; TypedArray typedArray = getActivity ( ) . obtainStyledAttributes ( value . data , new int [ ] { android . R . attr . textColorPrimary } ) ; int arrowColor = typedArray . getColor ( 0 , Color . BLACK ) ; typedArray . recycle ( ) ; arrowRight . setColorFilter ( arrowColor ) ; } catch ( Exception ignored ) { } colorPicker . setAlphaSliderVisible ( showAlphaSlider ) ; oldColorPanel . setColor ( getArguments ( ) . getInt ( ARG_COLOR ) ) ; colorPicker . setColor ( color , true ) ; newColorPanel . setColor ( color ) ; setHex ( color ) ; if ( ! showAlphaSlider ) { hexEditText . setFilters ( new InputFilter [ ] { new InputFilter . LengthFilter ( 6 ) } ) ; } newColorPanel . setOnClickListener ( new View . OnClickListener ( ) { @ Override public void onClick ( View v ) { if ( newColorPanel . getColor ( ) == color ) { onColorSelected ( color ) ; dismiss ( ) ; } } } ) ; contentView . setOnTouchListener ( onPickerTouchListener ) ; colorPicker . setOnColorChangedListener ( this ) ; hexEditText . addTextChangedListener ( this ) ; hexEditText . setOnFocusChangeListener ( new View . OnFocusChangeListener ( ) { @ Override public void onFocusChange ( View v , boolean hasFocus ) { if ( hasFocus ) { InputMethodManager imm = ( InputMethodManager ) getActivity ( ) . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; imm . showSoftInput ( hexEditText , InputMethodManager . SHOW_IMPLICIT ) ; } } } ) ; return contentView ; }
region Custom Picker
594
4
28,641
View createPresetsView ( ) { View contentView = View . inflate ( getActivity ( ) , R . layout . cpv_dialog_presets , null ) ; shadesLayout = ( LinearLayout ) contentView . findViewById ( R . id . shades_layout ) ; transparencySeekBar = ( SeekBar ) contentView . findViewById ( R . id . transparency_seekbar ) ; transparencyPercText = ( TextView ) contentView . findViewById ( R . id . transparency_text ) ; GridView gridView = ( GridView ) contentView . findViewById ( R . id . gridView ) ; loadPresets ( ) ; if ( showColorShades ) { createColorShades ( color ) ; } else { shadesLayout . setVisibility ( View . GONE ) ; contentView . findViewById ( R . id . shades_divider ) . setVisibility ( View . GONE ) ; } adapter = new ColorPaletteAdapter ( new ColorPaletteAdapter . OnColorSelectedListener ( ) { @ Override public void onColorSelected ( int newColor ) { if ( color == newColor ) { // Double tab selects the color ColorPickerDialog . this . onColorSelected ( color ) ; dismiss ( ) ; return ; } color = newColor ; if ( showColorShades ) { createColorShades ( color ) ; } } } , presets , getSelectedItemPosition ( ) , colorShape ) ; gridView . setAdapter ( adapter ) ; if ( showAlphaSlider ) { setupTransparency ( ) ; } else { contentView . findViewById ( R . id . transparency_layout ) . setVisibility ( View . GONE ) ; contentView . findViewById ( R . id . transparency_title ) . setVisibility ( View . GONE ) ; } return contentView ; }
region Presets Picker
398
5
28,642
public void setColor ( int color , boolean callback ) { int alpha = Color . alpha ( color ) ; int red = Color . red ( color ) ; int blue = Color . blue ( color ) ; int green = Color . green ( color ) ; float [ ] hsv = new float [ 3 ] ; Color . RGBToHSV ( red , green , blue , hsv ) ; this . alpha = alpha ; hue = hsv [ 0 ] ; sat = hsv [ 1 ] ; val = hsv [ 2 ] ; if ( callback && onColorChangedListener != null ) { onColorChangedListener . onColorChanged ( Color . HSVToColor ( this . alpha , new float [ ] { hue , sat , val } ) ) ; } invalidate ( ) ; }
Set the color this view should show .
164
8
28,643
public void setAlphaSliderVisible ( boolean visible ) { if ( showAlphaPanel != visible ) { showAlphaPanel = visible ; /* * Force recreation. */ valShader = null ; satShader = null ; alphaShader = null ; hueBackgroundCache = null ; satValBackgroundCache = null ; requestLayout ( ) ; } }
Set if the user is allowed to adjust the alpha panel . Default is false . If it is set to false no alpha will be set .
72
28
28,644
public static UserAgent valueOf ( int id ) { OperatingSystem operatingSystem = OperatingSystem . valueOf ( ( short ) ( id >> 16 ) ) ; Browser browser = Browser . valueOf ( ( short ) ( id & 0x0FFFF ) ) ; return new UserAgent ( operatingSystem , browser ) ; }
Returns UserAgent based on specified unique id
65
8
28,645
public static UserAgent valueOf ( String name ) { if ( name == null ) throw new NullPointerException ( "Name is null" ) ; String [ ] elements = name . split ( "-" ) ; if ( elements . length == 2 ) { OperatingSystem operatingSystem = OperatingSystem . valueOf ( elements [ 0 ] ) ; Browser browser = Browser . valueOf ( elements [ 1 ] ) ; return new UserAgent ( operatingSystem , browser ) ; } throw new IllegalArgumentException ( "Invalid string for userAgent " + name ) ; }
Returns UserAgent based on combined string representation
115
8
28,646
public ByteBuffer reset ( ByteBuffer input ) { ByteBuffer old = this . input ; this . input = checkNotNull ( input , "input ByteBuffer is null" ) . slice ( ) ; isRead = false ; return old ; }
Reset buffer .
50
4
28,647
public MessagePacker packString ( String s ) throws IOException { if ( s . length ( ) <= 0 ) { packRawStringHeader ( 0 ) ; return this ; } else if ( CORRUPTED_CHARSET_ENCODER || s . length ( ) < smallStringOptimizationThreshold ) { // Using String.getBytes is generally faster for small strings. // Also, when running on a platform that has a corrupted CharsetEncoder (i.e. Android 4.x), avoid using it. packStringWithGetBytes ( s ) ; return this ; } else if ( s . length ( ) < ( 1 << 8 ) ) { // ensure capacity for 2-byte raw string header + the maximum string size (+ 1 byte for falback code) ensureCapacity ( 2 + s . length ( ) * UTF_8_MAX_CHAR_SIZE + 1 ) ; // keep 2-byte header region and write raw string int written = encodeStringToBufferAt ( position + 2 , s ) ; if ( written >= 0 ) { if ( str8FormatSupport && written < ( 1 << 8 ) ) { buffer . putByte ( position ++ , STR8 ) ; buffer . putByte ( position ++ , ( byte ) written ) ; position += written ; } else { if ( written >= ( 1 << 16 ) ) { // this must not happen because s.length() is less than 2^8 and (2^8) * UTF_8_MAX_CHAR_SIZE is less than 2^16 throw new IllegalArgumentException ( "Unexpected UTF-8 encoder state" ) ; } // move 1 byte backward to expand 3-byte header region to 3 bytes buffer . putMessageBuffer ( position + 3 , buffer , position + 2 , written ) ; // write 3-byte header buffer . putByte ( position ++ , STR16 ) ; buffer . putShort ( position , ( short ) written ) ; position += 2 ; position += written ; } return this ; } } else if ( s . length ( ) < ( 1 << 16 ) ) { // ensure capacity for 3-byte raw string header + the maximum string size (+ 2 bytes for fallback code) ensureCapacity ( 3 + s . length ( ) * UTF_8_MAX_CHAR_SIZE + 2 ) ; // keep 3-byte header region and write raw string int written = encodeStringToBufferAt ( position + 3 , s ) ; if ( written >= 0 ) { if ( written < ( 1 << 16 ) ) { buffer . putByte ( position ++ , STR16 ) ; buffer . putShort ( position , ( short ) written ) ; position += 2 ; position += written ; } else { if ( written >= ( 1L << 32 ) ) { // this check does nothing because (1L << 32) is larger than Integer.MAX_VALUE // this must not happen because s.length() is less than 2^16 and (2^16) * UTF_8_MAX_CHAR_SIZE is less than 2^32 throw new IllegalArgumentException ( "Unexpected UTF-8 encoder state" ) ; } // move 2 bytes backward to expand 3-byte header region to 5 bytes buffer . putMessageBuffer ( position + 5 , buffer , position + 3 , written ) ; // write 3-byte header header buffer . putByte ( position ++ , STR32 ) ; buffer . putInt ( position , written ) ; position += 4 ; position += written ; } return this ; } } // Here doesn't use above optimized code for s.length() < (1 << 32) so that // ensureCapacity is not called with an integer larger than (3 + ((1 << 16) * UTF_8_MAX_CHAR_SIZE) + 2). // This makes it sure that MessageBufferOutput.next won't be called a size larger than // 384KB, which is OK size to keep in memory. // fallback packStringWithGetBytes ( s ) ; return this ; }
Writes a String vlaue in UTF - 8 encoding .
835
13
28,648
private static MessageBuffer newMessageBuffer ( byte [ ] arr , int off , int len ) { checkNotNull ( arr ) ; if ( mbArrConstructor != null ) { return newInstance ( mbArrConstructor , arr , off , len ) ; } return new MessageBuffer ( arr , off , len ) ; }
Creates a new MessageBuffer instance backed by a java heap array
71
13
28,649
private static MessageBuffer newMessageBuffer ( ByteBuffer bb ) { checkNotNull ( bb ) ; if ( mbBBConstructor != null ) { return newInstance ( mbBBConstructor , bb ) ; } return new MessageBuffer ( bb ) ; }
Creates a new MessageBuffer instance backed by ByteBuffer
60
11
28,650
private static MessageBuffer newInstance ( Constructor < ? > constructor , Object ... args ) { try { // We need to use reflection to create MessageBuffer instances in order to prevent TypeProfile generation for getInt method. TypeProfile will be // generated to resolve one of the method references when two or more classes overrides the method. return ( MessageBuffer ) constructor . newInstance ( args ) ; } catch ( InstantiationException e ) { // should never happen throw new IllegalStateException ( e ) ; } catch ( IllegalAccessException e ) { // should never happen unless security manager restricts this reflection throw new IllegalStateException ( e ) ; } catch ( InvocationTargetException e ) { if ( e . getCause ( ) instanceof RuntimeException ) { // underlying constructor may throw RuntimeException throw ( RuntimeException ) e . getCause ( ) ; } else if ( e . getCause ( ) instanceof Error ) { throw ( Error ) e . getCause ( ) ; } // should never happen throw new IllegalStateException ( e . getCause ( ) ) ; } }
Creates a new MessageBuffer instance
220
7
28,651
public int getInt ( int index ) { // Reading little-endian value int i = unsafe . getInt ( base , address + index ) ; // Reversing the endian return Integer . reverseBytes ( i ) ; }
Read a big - endian int value at the specified index
48
12
28,652
public void putInt ( int index , int v ) { // Reversing the endian v = Integer . reverseBytes ( v ) ; unsafe . putInt ( base , address + index , v ) ; }
Write a big - endian integer value to the memory
44
11
28,653
public ByteBuffer sliceAsByteBuffer ( int index , int length ) { if ( hasArray ( ) ) { return ByteBuffer . wrap ( ( byte [ ] ) base , ( int ) ( ( address - ARRAY_BYTE_BASE_OFFSET ) + index ) , length ) ; } else { assert ( ! isUniversalBuffer ) ; return DirectBufferAccess . newByteBuffer ( address , index , length , reference ) ; } }
Create a ByteBuffer view of the range [ index index + length ) of this memory
93
17
28,654
public byte [ ] toByteArray ( ) { byte [ ] b = new byte [ size ( ) ] ; unsafe . copyMemory ( base , address , b , ARRAY_BYTE_BASE_OFFSET , size ( ) ) ; return b ; }
Get a copy of this buffer
55
6
28,655
public void copyTo ( int index , MessageBuffer dst , int offset , int length ) { unsafe . copyMemory ( base , address + index , dst . base , dst . address + offset , length ) ; }
Copy this buffer contents to another MessageBuffer
44
8
28,656
@ Override public JsonFormat . Value findFormat ( Annotated ann ) { // If the entity contains JsonFormat annotation, give it higher priority. JsonFormat . Value precedenceFormat = super . findFormat ( ann ) ; if ( precedenceFormat != null ) { return precedenceFormat ; } return ARRAY_FORMAT ; }
Defines array format for serialized entities with ObjectMapper without actually including the schema
70
17
28,657
@ Override public Boolean findIgnoreUnknownProperties ( AnnotatedClass ac ) { // If the entity contains JsonIgnoreProperties annotation, give it higher priority. final Boolean precedenceIgnoreUnknownProperties = super . findIgnoreUnknownProperties ( ac ) ; if ( precedenceIgnoreUnknownProperties != null ) { return precedenceIgnoreUnknownProperties ; } return true ; }
Defines that unknown properties will be ignored and won t fail the un - marshalling process . Happens in case of de - serialization of a payload that contains more properties than the actual value type
83
40
28,658
public OutputStream reset ( OutputStream out ) throws IOException { OutputStream old = this . out ; this . out = out ; return old ; }
Reset Stream . This method doesn t close the old stream .
31
13
28,659
public InputStream reset ( InputStream in ) throws IOException { InputStream old = this . in ; this . in = in ; return old ; }
Reset Stream . This method doesn t close the old resource .
31
13
28,660
public WritableByteChannel reset ( WritableByteChannel channel ) throws IOException { WritableByteChannel old = this . channel ; this . channel = channel ; return old ; }
Reset channel . This method doesn t close the old channel .
37
13
28,661
public ReadableByteChannel reset ( ReadableByteChannel channel ) throws IOException { ReadableByteChannel old = this . channel ; this . channel = channel ; return old ; }
Reset channel . This method doesn t close the old resource .
37
13
28,662
private MessageBuffer getNextBuffer ( ) throws IOException { MessageBuffer next = in . next ( ) ; if ( next == null ) { throw new MessageInsufficientBufferException ( ) ; } assert ( buffer != null ) ; totalReadBytes += buffer . size ( ) ; return next ; }
Get the next buffer without changing the position
61
8
28,663
public MessageFormat getNextFormat ( ) throws IOException { // makes sure that buffer has at least 1 byte if ( ! ensureBuffer ( ) ) { throw new MessageInsufficientBufferException ( ) ; } byte b = buffer . getByte ( position ) ; return MessageFormat . valueOf ( b ) ; }
Returns format of the next value .
64
7
28,664
private byte readByte ( ) throws IOException { if ( buffer . size ( ) > position ) { byte b = buffer . getByte ( position ) ; position ++ ; return b ; } else { nextBuffer ( ) ; if ( buffer . size ( ) > 0 ) { byte b = buffer . getByte ( 0 ) ; position = 1 ; return b ; } return readByte ( ) ; } }
Read a byte value at the cursor and proceed the cursor .
84
12
28,665
public void skipValue ( int count ) throws IOException { while ( count > 0 ) { byte b = readByte ( ) ; MessageFormat f = MessageFormat . valueOf ( b ) ; switch ( f ) { case POSFIXINT : case NEGFIXINT : case BOOLEAN : case NIL : break ; case FIXMAP : { int mapLen = b & 0x0f ; count += mapLen * 2 ; break ; } case FIXARRAY : { int arrayLen = b & 0x0f ; count += arrayLen ; break ; } case FIXSTR : { int strLen = b & 0x1f ; skipPayload ( strLen ) ; break ; } case INT8 : case UINT8 : skipPayload ( 1 ) ; break ; case INT16 : case UINT16 : skipPayload ( 2 ) ; break ; case INT32 : case UINT32 : case FLOAT32 : skipPayload ( 4 ) ; break ; case INT64 : case UINT64 : case FLOAT64 : skipPayload ( 8 ) ; break ; case BIN8 : case STR8 : skipPayload ( readNextLength8 ( ) ) ; break ; case BIN16 : case STR16 : skipPayload ( readNextLength16 ( ) ) ; break ; case BIN32 : case STR32 : skipPayload ( readNextLength32 ( ) ) ; break ; case FIXEXT1 : skipPayload ( 2 ) ; break ; case FIXEXT2 : skipPayload ( 3 ) ; break ; case FIXEXT4 : skipPayload ( 5 ) ; break ; case FIXEXT8 : skipPayload ( 9 ) ; break ; case FIXEXT16 : skipPayload ( 17 ) ; break ; case EXT8 : skipPayload ( readNextLength8 ( ) + 1 ) ; break ; case EXT16 : skipPayload ( readNextLength16 ( ) + 1 ) ; break ; case EXT32 : skipPayload ( readNextLength32 ( ) + 1 ) ; break ; case ARRAY16 : count += readNextLength16 ( ) ; break ; case ARRAY32 : count += readNextLength32 ( ) ; break ; case MAP16 : count += readNextLength16 ( ) * 2 ; break ; case MAP32 : count += readNextLength32 ( ) * 2 ; // TODO check int overflow break ; case NEVER_USED : throw new MessageNeverUsedFormatException ( "Encountered 0xC1 \"NEVER_USED\" byte" ) ; } count -- ; } }
Skip next values then move the cursor at the end of the value
540
13
28,666
private static MessagePackException unexpected ( String expected , byte b ) { MessageFormat format = MessageFormat . valueOf ( b ) ; if ( format == MessageFormat . NEVER_USED ) { return new MessageNeverUsedFormatException ( String . format ( "Expected %s, but encountered 0xC1 \"NEVER_USED\" byte" , expected ) ) ; } else { String name = format . getValueType ( ) . name ( ) ; String typeName = name . substring ( 0 , 1 ) + name . substring ( 1 ) . toLowerCase ( ) ; return new MessageTypeException ( String . format ( "Expected %s, but got %s (%02x)" , expected , typeName , b ) ) ; } }
Create an exception for the case when an unexpected byte value is read
160
13
28,667
public boolean tryUnpackNil ( ) throws IOException { // makes sure that buffer has at least 1 byte if ( ! ensureBuffer ( ) ) { throw new MessageInsufficientBufferException ( ) ; } byte b = buffer . getByte ( position ) ; if ( b == Code . NIL ) { readByte ( ) ; return true ; } return false ; }
Peeks a Nil byte and reads it if next byte is a nil value .
77
16
28,668
public boolean unpackBoolean ( ) throws IOException { byte b = readByte ( ) ; if ( b == Code . FALSE ) { return false ; } else if ( b == Code . TRUE ) { return true ; } throw unexpected ( "boolean" , b ) ; }
Reads true or false .
59
6
28,669
public short unpackShort ( ) throws IOException { byte b = readByte ( ) ; if ( Code . isFixInt ( b ) ) { return ( short ) b ; } switch ( b ) { case Code . UINT8 : // unsigned int 8 byte u8 = readByte ( ) ; return ( short ) ( u8 & 0xff ) ; case Code . UINT16 : // unsigned int 16 short u16 = readShort ( ) ; if ( u16 < ( short ) 0 ) { throw overflowU16 ( u16 ) ; } return u16 ; case Code . UINT32 : // unsigned int 32 int u32 = readInt ( ) ; if ( u32 < 0 || u32 > Short . MAX_VALUE ) { throw overflowU32 ( u32 ) ; } return ( short ) u32 ; case Code . UINT64 : // unsigned int 64 long u64 = readLong ( ) ; if ( u64 < 0L || u64 > Short . MAX_VALUE ) { throw overflowU64 ( u64 ) ; } return ( short ) u64 ; case Code . INT8 : // signed int 8 byte i8 = readByte ( ) ; return ( short ) i8 ; case Code . INT16 : // signed int 16 short i16 = readShort ( ) ; return i16 ; case Code . INT32 : // signed int 32 int i32 = readInt ( ) ; if ( i32 < Short . MIN_VALUE || i32 > Short . MAX_VALUE ) { throw overflowI32 ( i32 ) ; } return ( short ) i32 ; case Code . INT64 : // signed int 64 long i64 = readLong ( ) ; if ( i64 < Short . MIN_VALUE || i64 > Short . MAX_VALUE ) { throw overflowI64 ( i64 ) ; } return ( short ) i64 ; } throw unexpected ( "Integer" , b ) ; }
Reads a short .
404
5
28,670
public long unpackLong ( ) throws IOException { byte b = readByte ( ) ; if ( Code . isFixInt ( b ) ) { return ( long ) b ; } switch ( b ) { case Code . UINT8 : // unsigned int 8 byte u8 = readByte ( ) ; return ( long ) ( u8 & 0xff ) ; case Code . UINT16 : // unsigned int 16 short u16 = readShort ( ) ; return ( long ) ( u16 & 0xffff ) ; case Code . UINT32 : // unsigned int 32 int u32 = readInt ( ) ; if ( u32 < 0 ) { return ( long ) ( u32 & 0x7fffffff ) + 0x80000000 L ; } else { return ( long ) u32 ; } case Code . UINT64 : // unsigned int 64 long u64 = readLong ( ) ; if ( u64 < 0L ) { throw overflowU64 ( u64 ) ; } return u64 ; case Code . INT8 : // signed int 8 byte i8 = readByte ( ) ; return ( long ) i8 ; case Code . INT16 : // signed int 16 short i16 = readShort ( ) ; return ( long ) i16 ; case Code . INT32 : // signed int 32 int i32 = readInt ( ) ; return ( long ) i32 ; case Code . INT64 : // signed int 64 long i64 = readLong ( ) ; return i64 ; } throw unexpected ( "Integer" , b ) ; }
Reads a long .
324
5
28,671
public BigInteger unpackBigInteger ( ) throws IOException { byte b = readByte ( ) ; if ( Code . isFixInt ( b ) ) { return BigInteger . valueOf ( ( long ) b ) ; } switch ( b ) { case Code . UINT8 : // unsigned int 8 byte u8 = readByte ( ) ; return BigInteger . valueOf ( ( long ) ( u8 & 0xff ) ) ; case Code . UINT16 : // unsigned int 16 short u16 = readShort ( ) ; return BigInteger . valueOf ( ( long ) ( u16 & 0xffff ) ) ; case Code . UINT32 : // unsigned int 32 int u32 = readInt ( ) ; if ( u32 < 0 ) { return BigInteger . valueOf ( ( long ) ( u32 & 0x7fffffff ) + 0x80000000 L ) ; } else { return BigInteger . valueOf ( ( long ) u32 ) ; } case Code . UINT64 : // unsigned int 64 long u64 = readLong ( ) ; if ( u64 < 0L ) { BigInteger bi = BigInteger . valueOf ( u64 + Long . MAX_VALUE + 1L ) . setBit ( 63 ) ; return bi ; } else { return BigInteger . valueOf ( u64 ) ; } case Code . INT8 : // signed int 8 byte i8 = readByte ( ) ; return BigInteger . valueOf ( ( long ) i8 ) ; case Code . INT16 : // signed int 16 short i16 = readShort ( ) ; return BigInteger . valueOf ( ( long ) i16 ) ; case Code . INT32 : // signed int 32 int i32 = readInt ( ) ; return BigInteger . valueOf ( ( long ) i32 ) ; case Code . INT64 : // signed int 64 long i64 = readLong ( ) ; return BigInteger . valueOf ( i64 ) ; } throw unexpected ( "Integer" , b ) ; }
Reads a BigInteger .
422
6
28,672
public float unpackFloat ( ) throws IOException { byte b = readByte ( ) ; switch ( b ) { case Code . FLOAT32 : // float float fv = readFloat ( ) ; return fv ; case Code . FLOAT64 : // double double dv = readDouble ( ) ; return ( float ) dv ; } throw unexpected ( "Float" , b ) ; }
Reads a float .
85
5
28,673
public int unpackArrayHeader ( ) throws IOException { byte b = readByte ( ) ; if ( Code . isFixedArray ( b ) ) { // fixarray return b & 0x0f ; } switch ( b ) { case Code . ARRAY16 : { // array 16 int len = readNextLength16 ( ) ; return len ; } case Code . ARRAY32 : { // array 32 int len = readNextLength32 ( ) ; return len ; } } throw unexpected ( "Array" , b ) ; }
Reads header of an array .
111
7
28,674
public int unpackMapHeader ( ) throws IOException { byte b = readByte ( ) ; if ( Code . isFixedMap ( b ) ) { // fixmap return b & 0x0f ; } switch ( b ) { case Code . MAP16 : { // map 16 int len = readNextLength16 ( ) ; return len ; } case Code . MAP32 : { // map 32 int len = readNextLength32 ( ) ; return len ; } } throw unexpected ( "Map" , b ) ; }
Reads header of a map .
109
7
28,675
public int unpackBinaryHeader ( ) throws IOException { byte b = readByte ( ) ; if ( Code . isFixedRaw ( b ) ) { // FixRaw return b & 0x1f ; } int len = tryReadBinaryHeader ( b ) ; if ( len >= 0 ) { return len ; } if ( allowReadingStringAsBinary ) { len = tryReadStringHeader ( b ) ; if ( len >= 0 ) { return len ; } } throw unexpected ( "Binary" , b ) ; }
Reads header of a binary .
112
7
28,676
public MessageBuffer readPayloadAsReference ( int length ) throws IOException { int bufferRemaining = buffer . size ( ) - position ; if ( bufferRemaining >= length ) { MessageBuffer slice = buffer . slice ( position , length ) ; position += length ; return slice ; } MessageBuffer dst = MessageBuffer . allocate ( length ) ; readPayload ( dst , 0 , length ) ; return dst ; }
Reads payload bytes of binary extension or raw string types as a reference to internal buffer .
86
18
28,677
public MessageBuffer reset ( MessageBuffer buf ) { MessageBuffer old = this . buffer ; this . buffer = buf ; if ( buf == null ) { isEmpty = true ; } else { isEmpty = false ; } return old ; }
Reset buffer . This method returns the old buffer .
49
11
28,678
public ModbusRequest buildDiagnostics ( DiagnosticsSubFunctionCode subFunctionCode , int serverAddress , int data ) throws ModbusNumberException { DiagnosticsRequest request = new DiagnosticsRequest ( ) ; request . setServerAddress ( serverAddress ) ; request . setSubFunctionCode ( subFunctionCode ) ; request . setSubFunctionData ( data ) ; return request ; }
The function uses a sub - function code field in the query to define the type of test to be performed . The server echoes both the function code and sub - function code in a normal response . Some of the diagnostics cause data to be returned from the remote device in the data field of a normal response .
79
62
28,679
synchronized public ModbusResponse processRequest ( ModbusRequest request ) throws ModbusProtocolException , ModbusIOException { try { sendRequest ( request ) ; if ( request . getServerAddress ( ) != Modbus . BROADCAST_ID ) { do { try { ModbusResponse msg = ( ModbusResponse ) readResponse ( request ) ; request . validateResponse ( msg ) ; /* * if you have received an ACKNOWLEDGE, * it means that operation is in processing and you should be waiting for the answer */ if ( msg . getModbusExceptionCode ( ) != ModbusExceptionCode . ACKNOWLEDGE ) { if ( msg . isException ( ) ) throw new ModbusProtocolException ( msg . getModbusExceptionCode ( ) ) ; return msg ; } } catch ( ModbusNumberException mne ) { Modbus . log ( ) . warning ( mne . getLocalizedMessage ( ) ) ; } } while ( System . currentTimeMillis ( ) - requestTime < getConnection ( ) . getReadTimeout ( ) ) ; /* * throw an exception if there is a response timeout */ throw new ModbusIOException ( "Response timeout." ) ; } else { /* return because slaves do not respond broadcast requests */ broadcastResponse . setFunction ( request . getFunction ( ) ) ; return broadcastResponse ; } } catch ( ModbusIOException mioe ) { disconnect ( ) ; throw mioe ; } }
this function allows you to process your own ModbusRequest . Each request class has a compliant response class for instance ReadHoldingRegistersRequest and ReadHoldingRegistersResponse . If you process an instance of ReadHoldingRegistersRequest this function exactly either returns a ReadHoldingRegistersResponse instance or throws an exception .
308
66
28,680
public void setResponseTimeout ( int timeout ) { try { getConnection ( ) . setReadTimeout ( timeout ) ; } catch ( Exception e ) { Modbus . log ( ) . warning ( e . getLocalizedMessage ( ) ) ; } }
ModbusMaster will block for only this amount of time . If the timeout expires a ModbusTransportException is raised though the ModbusMaster is still valid .
52
33
28,681
final public int [ ] readHoldingRegisters ( int serverAddress , int startAddress , int quantity ) throws ModbusProtocolException , ModbusNumberException , ModbusIOException { ModbusRequest request = ModbusRequestBuilder . getInstance ( ) . buildReadHoldingRegisters ( serverAddress , startAddress , quantity ) ; ReadHoldingRegistersResponse response = ( ReadHoldingRegistersResponse ) processRequest ( request ) ; return response . getRegisters ( ) ; }
This function code is used to read the contents of a contiguous block of holding registers in a remote device . The Request PDU specifies the starting register address and the number of registers . In the PDU Registers are addressed starting at zero . Therefore registers numbered 1 - 16 are addressed as 0 - 15 .
102
61
28,682
final public int [ ] readInputRegisters ( int serverAddress , int startAddress , int quantity ) throws ModbusProtocolException , ModbusNumberException , ModbusIOException { ModbusRequest request = ModbusRequestBuilder . getInstance ( ) . buildReadInputRegisters ( serverAddress , startAddress , quantity ) ; ReadHoldingRegistersResponse response = ( ReadInputRegistersResponse ) processRequest ( request ) ; return response . getRegisters ( ) ; }
This function code is used to read from 1 to 125 contiguous input registers in a remote device . The Request PDU specifies the starting register address and the number of registers . In the PDU Registers are addressed starting at zero . Therefore input registers numbered 1 - 16 are addressed as 0 - 15 .
99
60
28,683
final synchronized public boolean [ ] readCoils ( int serverAddress , int startAddress , int quantity ) throws ModbusProtocolException , ModbusNumberException , ModbusIOException { ModbusRequest request = ModbusRequestBuilder . getInstance ( ) . buildReadCoils ( serverAddress , startAddress , quantity ) ; ReadCoilsResponse response = ( ReadCoilsResponse ) processRequest ( request ) ; return response . getCoils ( ) ; }
This function code is used to read from 1 to 2000 contiguous status of coils in a remote device . The Request PDU specifies the starting address i . e . the address of the first coil specified and the number of coils . In the PDU Coils are addressed starting at zero . Therefore coils numbered 1 - 16 are addressed as 0 - 15 . If the returned output quantity is not a multiple of eight the remaining coils in the final boolean array will be padded with FALSE .
95
95
28,684
final public boolean [ ] readDiscreteInputs ( int serverAddress , int startAddress , int quantity ) throws ModbusProtocolException , ModbusNumberException , ModbusIOException { ModbusRequest request = ModbusRequestBuilder . getInstance ( ) . buildReadDiscreteInputs ( serverAddress , startAddress , quantity ) ; ReadDiscreteInputsResponse response = ( ReadDiscreteInputsResponse ) processRequest ( request ) ; return response . getCoils ( ) ; }
This function code is used to read from 1 to 2000 contiguous status of discrete inputs in a remote device . The Request PDU specifies the starting address i . e . the address of the first input specified and the number of inputs . In the PDU Discrete Inputs are addressed starting at zero . Therefore Discrete inputs numbered 1 - 16 are addressed as 0 - 15 . If the returned input quantity is not a multiple of eight the remaining inputs in the final boolean array will be padded with FALSE .
102
100
28,685
final public void writeSingleRegister ( int serverAddress , int startAddress , int register ) throws ModbusProtocolException , ModbusNumberException , ModbusIOException { processRequest ( ModbusRequestBuilder . getInstance ( ) . buildWriteSingleRegister ( serverAddress , startAddress , register ) ) ; }
This function code is used to write a single holding register in a remote device . The Request PDU specifies the address of the register to be written . Registers are addressed starting at zero . Therefore register numbered 1 is addressed as 0 .
64
47
28,686
final public int [ ] readWriteMultipleRegisters ( int serverAddress , int readAddress , int readQuantity , int writeAddress , int [ ] registers ) throws ModbusProtocolException , ModbusNumberException , ModbusIOException { ModbusRequest request = ModbusRequestBuilder . getInstance ( ) . buildReadWriteMultipleRegisters ( serverAddress , readAddress , readQuantity , writeAddress , registers ) ; ReadWriteMultipleRegistersResponse response = ( ReadWriteMultipleRegistersResponse ) processRequest ( request ) ; return response . getRegisters ( ) ; }
This function code performs a combination of one read operation and one write operation in a single MODBUS transaction . The write operation is performed before the read . Holding registers are addressed starting at zero . Therefore holding registers 1 - 16 are addressed in the PDU as 0 - 15 . The request specifies the starting address and number of holding registers to be read as well as the starting address number of holding registers and the data to be written .
118
86
28,687
final public ModbusFileRecord [ ] readFileRecord ( int serverAddress , ModbusFileRecord [ ] records ) throws ModbusProtocolException , ModbusNumberException , ModbusIOException { ModbusRequest request = ModbusRequestBuilder . getInstance ( ) . buildReadFileRecord ( serverAddress , records ) ; ReadFileRecordResponse response = ( ReadFileRecordResponse ) processRequest ( request ) ; return response . getFileRecords ( ) ; }
This function code is used to perform a file record read . A file is an organization of records . Each file contains 10000 records addressed 0000 to 9999 decimal or 0X0000 to 0X270F . For example record 12 is addressed as 12 . The function can read multiple groups of references .
96
59
28,688
final public void writeFileRecord ( int serverAddress , ModbusFileRecord record ) throws ModbusProtocolException , ModbusNumberException , ModbusIOException { processRequest ( ModbusRequestBuilder . getInstance ( ) . buildWriteFileRecord ( serverAddress , record ) ) ; }
This function code is used to perform a file record write . All Request Data Lengths are provided in terms of number of bytes and all Record Lengths are provided in terms of the number of 16 - bit words . A file is an organization of records . Each file contains 10000 records addressed 0000 to 9999 decimal or 0X0000 to 0X270F . For example record 12 is addressed as 12 . The function can write multiple groups of references .
60
90
28,689
static public void setLogLevel ( LogLevel level ) { logLevel = level ; log . setLevel ( level . value ( ) ) ; for ( Handler handler : log . getHandlers ( ) ) { handler . setLevel ( level . value ( ) ) ; } }
changes the log level for all loggers used
57
9
28,690
static public boolean checkServerAddress ( int serverAddress ) { /* * hook for server address is equals zero: * some of modbus tcp slaves sets the UnitId value to zero, not ignoring value in this field. */ switch ( serverAddress ) { case 0x00 : //Modbus.log().info("Broadcast message"); return true ; case 0xFF : //Modbus.log().info("Using 0xFF ModbusTCP default slave id"); return true ; default : return ! ( serverAddress < Modbus . MIN_SERVER_ADDRESS || serverAddress > Modbus . MAX_SERVER_ADDRESS ) ; } }
validates address of server
137
5
28,691
public int readShortBE ( ) throws IOException { int h = read ( ) ; int l = read ( ) ; if ( - 1 == h || - 1 == l ) return - 1 ; return DataUtils . toShort ( h , l ) ; }
read two bytes in Big Endian Byte Order
55
9
28,692
public int readShortLE ( ) throws IOException { int l = read ( ) ; int h = read ( ) ; if ( - 1 == h || - 1 == l ) return - 1 ; return DataUtils . toShort ( h , l ) ; }
read two bytes in Little Endian Byte Order
55
9
28,693
public Future < AuthenticationResult > acquireToken ( final String resource , final UserAssertion userAssertion , final ClientCredential credential , final AuthenticationCallback callback ) { this . validateOnBehalfOfRequestInput ( resource , userAssertion , credential , true ) ; final ClientAuthentication clientAuth = new ClientSecretPost ( new ClientID ( credential . getClientId ( ) ) , new Secret ( credential . getClientSecret ( ) ) ) ; return acquireTokenOnBehalfOf ( resource , userAssertion , clientAuth , callback ) ; }
Acquires an access token from the authority on behalf of a user . It requires using a user token previously received .
118
24
28,694
public Future < AuthenticationResult > acquireToken ( final String resource , final UserAssertion userAssertion , final AsymmetricKeyCredential credential , final AuthenticationCallback callback ) { this . validateOnBehalfOfRequestInput ( resource , userAssertion , credential , true ) ; ClientAssertion clientAssertion = JwtHelper . buildJwt ( credential , this . authenticationAuthority . getSelfSignedJwtAudience ( ) ) ; final ClientAuthentication clientAuth = createClientAuthFromClientAssertion ( clientAssertion ) ; return acquireTokenOnBehalfOf ( resource , userAssertion , clientAuth , callback ) ; }
Acquires an access token from the authority on behalf of a user . It requires using a user token previously received . Uses certificate to authenticate client .
142
31
28,695
public Future < DeviceCode > acquireDeviceCode ( final String clientId , final String resource , final AuthenticationCallback < DeviceCode > callback ) { validateDeviceCodeRequestInput ( clientId , resource ) ; return service . submit ( new AcquireDeviceCodeCallable ( this , clientId , resource , callback ) ) ; }
Acquires a device code from the authority
66
9
28,696
public Future < AuthenticationResult > acquireTokenByDeviceCode ( final DeviceCode deviceCode , final AuthenticationCallback callback ) throws AuthenticationException { final ClientAuthentication clientAuth = new ClientAuthenticationPost ( ClientAuthenticationMethod . NONE , new ClientID ( deviceCode . getClientId ( ) ) ) ; this . validateDeviceCodeRequestInput ( deviceCode , clientAuth , deviceCode . getResource ( ) ) ; final AdalDeviceCodeAuthorizationGrant deviceCodeGrant = new AdalDeviceCodeAuthorizationGrant ( deviceCode , deviceCode . getResource ( ) ) ; return this . acquireToken ( deviceCodeGrant , clientAuth , callback ) ; }
Acquires security token from the authority using an device code previously received .
136
15
28,697
public Future < AuthenticationResult > acquireTokenByRefreshToken ( final String refreshToken , final String clientId , final String resource , final AuthenticationCallback callback ) { final ClientAuthentication clientAuth = new ClientAuthenticationPost ( ClientAuthenticationMethod . NONE , new ClientID ( clientId ) ) ; final AdalOAuthAuthorizationGrant authGrant = new AdalOAuthAuthorizationGrant ( new RefreshTokenGrant ( new RefreshToken ( refreshToken ) ) , resource ) ; return this . acquireToken ( authGrant , clientAuth , callback ) ; }
Acquires a security token from the authority using a Refresh Token previously received . This method is suitable for the daemon OAuth2 flow when a client secret is not possible .
116
35
28,698
@ Override public Map < String , List < String > > toParameters ( ) { final Map < String , List < String > > outParams = new LinkedHashMap <> ( ) ; outParams . put ( "resource" , Collections . singletonList ( resource ) ) ; outParams . put ( "grant_type" , Collections . singletonList ( GRANT_TYPE ) ) ; outParams . put ( "code" , Collections . singletonList ( deviceCode . getDeviceCode ( ) ) ) ; return outParams ; }
Converts the device code grant to a map of HTTP paramters .
121
14
28,699
public static JSONObject processBadRespStr ( int responseCode , String responseMsg ) throws JSONException { JSONObject response = new JSONObject ( ) ; response . put ( "responseCode" , responseCode ) ; if ( responseMsg . equalsIgnoreCase ( "" ) ) { // good response is empty string response . put ( "responseMsg" , "" ) ; } else { // bad response is json string JSONObject errorObject = new JSONObject ( responseMsg ) . optJSONObject ( "odata.error" ) ; String errorCode = errorObject . optString ( "code" ) ; String errorMsg = errorObject . optJSONObject ( "message" ) . optString ( "value" ) ; response . put ( "responseCode" , responseCode ) ; response . put ( "errorCode" , errorCode ) ; response . put ( "errorMsg" , errorMsg ) ; } return response ; }
for good response
193
3