idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
23,900 | private void drawEvents ( Calendar date , float startFromPixel , Canvas canvas ) { if ( mEventRects != null && mEventRects . size ( ) > 0 ) { for ( int i = 0 ; i < mEventRects . size ( ) ; i ++ ) { if ( isSameDay ( mEventRects . get ( i ) . event . getStartTime ( ) , date ) && ! mEventRects . get ( i ) . event . isAllDay ( ) ) { float top = mHourHeight * 24 * mEventRects . get ( i ) . top / 1440 + mCurrentOrigin . y + mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight / 2 + mEventMarginVertical ; float bottom = mEventRects . get ( i ) . bottom ; bottom = mHourHeight * 24 * bottom / 1440 + mCurrentOrigin . y + mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight / 2 - mEventMarginVertical ; float left = startFromPixel + mEventRects . get ( i ) . left * mWidthPerDay ; if ( left < startFromPixel ) left += mOverlappingEventGap ; float right = left + mEventRects . get ( i ) . width * mWidthPerDay ; if ( right < startFromPixel + mWidthPerDay ) right -= mOverlappingEventGap ; if ( left < right && left < getWidth ( ) && top < getHeight ( ) && right > mHeaderColumnWidth && bottom > mHeaderHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom ) { mEventRects . get ( i ) . rectF = new RectF ( left , top , right , bottom ) ; mEventBackgroundPaint . setColor ( mEventRects . get ( i ) . event . getColor ( ) == 0 ? mDefaultEventColor : mEventRects . get ( i ) . event . getColor ( ) ) ; canvas . drawRoundRect ( mEventRects . get ( i ) . rectF , mEventCornerRadius , mEventCornerRadius , mEventBackgroundPaint ) ; drawEventTitle ( mEventRects . get ( i ) . event , mEventRects . get ( i ) . rectF , canvas , top , left ) ; } else mEventRects . get ( i ) . rectF = null ; } } } } | Draw all the events of a particular day . |
23,901 | private void drawEventTitle ( WeekViewEvent event , RectF rect , Canvas canvas , float originalTop , float originalLeft ) { if ( rect . right - rect . left - mEventPadding * 2 < 0 ) return ; if ( rect . bottom - rect . top - mEventPadding * 2 < 0 ) return ; SpannableStringBuilder bob = new SpannableStringBuilder ( ) ; if ( event . getName ( ) != null ) { bob . append ( event . getName ( ) ) ; bob . setSpan ( new StyleSpan ( android . graphics . Typeface . BOLD ) , 0 , bob . length ( ) , 0 ) ; bob . append ( ' ' ) ; } if ( event . getLocation ( ) != null ) { bob . append ( event . getLocation ( ) ) ; } int availableHeight = ( int ) ( rect . bottom - originalTop - mEventPadding * 2 ) ; int availableWidth = ( int ) ( rect . right - originalLeft - mEventPadding * 2 ) ; StaticLayout textLayout = new StaticLayout ( bob , mEventTextPaint , availableWidth , Layout . Alignment . ALIGN_NORMAL , 1.0f , 0.0f , false ) ; int lineHeight = textLayout . getHeight ( ) / textLayout . getLineCount ( ) ; if ( availableHeight >= lineHeight ) { int availableLineCount = availableHeight / lineHeight ; do { textLayout = new StaticLayout ( TextUtils . ellipsize ( bob , mEventTextPaint , availableLineCount * availableWidth , TextUtils . TruncateAt . END ) , mEventTextPaint , ( int ) ( rect . right - originalLeft - mEventPadding * 2 ) , Layout . Alignment . ALIGN_NORMAL , 1.0f , 0.0f , false ) ; availableLineCount -- ; } while ( textLayout . getHeight ( ) > availableHeight ) ; canvas . save ( ) ; canvas . translate ( originalLeft + mEventPadding , originalTop + mEventPadding ) ; textLayout . draw ( canvas ) ; canvas . restore ( ) ; } } | Draw the name of the event on top of the event rectangle . |
23,902 | private void cacheEvent ( WeekViewEvent event ) { if ( event . getStartTime ( ) . compareTo ( event . getEndTime ( ) ) >= 0 ) return ; List < WeekViewEvent > splitedEvents = event . splitWeekViewEvents ( ) ; for ( WeekViewEvent splitedEvent : splitedEvents ) { mEventRects . add ( new EventRect ( splitedEvent , event , null ) ) ; } } | Cache the event for smooth scrolling functionality . |
23,903 | private void sortAndCacheEvents ( List < ? extends WeekViewEvent > events ) { sortEvents ( events ) ; for ( WeekViewEvent event : events ) { cacheEvent ( event ) ; } } | Sort and cache events . |
23,904 | private void sortEvents ( List < ? extends WeekViewEvent > events ) { Collections . sort ( events , new Comparator < WeekViewEvent > ( ) { public int compare ( WeekViewEvent event1 , WeekViewEvent event2 ) { long start1 = event1 . getStartTime ( ) . getTimeInMillis ( ) ; long start2 = event2 . getStartTime ( ) . getTimeInMillis ( ) ; int comparator = start1 > start2 ? 1 : ( start1 < start2 ? - 1 : 0 ) ; if ( comparator == 0 ) { long end1 = event1 . getEndTime ( ) . getTimeInMillis ( ) ; long end2 = event2 . getEndTime ( ) . getTimeInMillis ( ) ; comparator = end1 > end2 ? 1 : ( end1 < end2 ? - 1 : 0 ) ; } return comparator ; } } ) ; } | Sorts the events in ascending order . |
23,905 | private void computePositionOfEvents ( List < EventRect > eventRects ) { List < List < EventRect > > collisionGroups = new ArrayList < List < EventRect > > ( ) ; for ( EventRect eventRect : eventRects ) { boolean isPlaced = false ; outerLoop : for ( List < EventRect > collisionGroup : collisionGroups ) { for ( EventRect groupEvent : collisionGroup ) { if ( isEventsCollide ( groupEvent . event , eventRect . event ) && groupEvent . event . isAllDay ( ) == eventRect . event . isAllDay ( ) ) { collisionGroup . add ( eventRect ) ; isPlaced = true ; break outerLoop ; } } } if ( ! isPlaced ) { List < EventRect > newGroup = new ArrayList < EventRect > ( ) ; newGroup . add ( eventRect ) ; collisionGroups . add ( newGroup ) ; } } for ( List < EventRect > collisionGroup : collisionGroups ) { expandEventsToMaxWidth ( collisionGroup ) ; } } | Calculates the left and right positions of each events . This comes handy specially if events are overlapping . |
23,906 | private void expandEventsToMaxWidth ( List < EventRect > collisionGroup ) { List < List < EventRect > > columns = new ArrayList < List < EventRect > > ( ) ; columns . add ( new ArrayList < EventRect > ( ) ) ; for ( EventRect eventRect : collisionGroup ) { boolean isPlaced = false ; for ( List < EventRect > column : columns ) { if ( column . size ( ) == 0 ) { column . add ( eventRect ) ; isPlaced = true ; } else if ( ! isEventsCollide ( eventRect . event , column . get ( column . size ( ) - 1 ) . event ) ) { column . add ( eventRect ) ; isPlaced = true ; break ; } } if ( ! isPlaced ) { List < EventRect > newColumn = new ArrayList < EventRect > ( ) ; newColumn . add ( eventRect ) ; columns . add ( newColumn ) ; } } int maxRowCount = 0 ; for ( List < EventRect > column : columns ) { maxRowCount = Math . max ( maxRowCount , column . size ( ) ) ; } for ( int i = 0 ; i < maxRowCount ; i ++ ) { float j = 0 ; for ( List < EventRect > column : columns ) { if ( column . size ( ) >= i + 1 ) { EventRect eventRect = column . get ( i ) ; eventRect . width = 1f / columns . size ( ) ; eventRect . left = j / columns . size ( ) ; if ( ! eventRect . event . isAllDay ( ) ) { eventRect . top = eventRect . event . getStartTime ( ) . get ( Calendar . HOUR_OF_DAY ) * 60 + eventRect . event . getStartTime ( ) . get ( Calendar . MINUTE ) ; eventRect . bottom = eventRect . event . getEndTime ( ) . get ( Calendar . HOUR_OF_DAY ) * 60 + eventRect . event . getEndTime ( ) . get ( Calendar . MINUTE ) ; } else { eventRect . top = 0 ; eventRect . bottom = mAllDayEventHeight ; } mEventRects . add ( eventRect ) ; } j ++ ; } } } | Expands all the events to maximum possible width . The events will try to occupy maximum space available horizontally . |
23,907 | private boolean isEventsCollide ( WeekViewEvent event1 , WeekViewEvent event2 ) { long start1 = event1 . getStartTime ( ) . getTimeInMillis ( ) ; long end1 = event1 . getEndTime ( ) . getTimeInMillis ( ) ; long start2 = event2 . getStartTime ( ) . getTimeInMillis ( ) ; long end2 = event2 . getEndTime ( ) . getTimeInMillis ( ) ; return ! ( ( start1 >= end2 ) || ( end1 <= start2 ) ) ; } | Checks if two events overlap . |
23,908 | public DateTimeInterpreter getDateTimeInterpreter ( ) { if ( mDateTimeInterpreter == null ) { mDateTimeInterpreter = new DateTimeInterpreter ( ) { public String interpretDate ( Calendar date ) { try { SimpleDateFormat sdf = mDayNameLength == LENGTH_SHORT ? new SimpleDateFormat ( "EEEEE M/dd" , Locale . getDefault ( ) ) : new SimpleDateFormat ( "EEE M/dd" , Locale . getDefault ( ) ) ; return sdf . format ( date . getTime ( ) ) . toUpperCase ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return "" ; } } public String interpretTime ( int hour ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . set ( Calendar . HOUR_OF_DAY , hour ) ; calendar . set ( Calendar . MINUTE , 0 ) ; try { SimpleDateFormat sdf = DateFormat . is24HourFormat ( getContext ( ) ) ? new SimpleDateFormat ( "HH:mm" , Locale . getDefault ( ) ) : new SimpleDateFormat ( "hh a" , Locale . getDefault ( ) ) ; return sdf . format ( calendar . getTime ( ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return "" ; } } } ; } return mDateTimeInterpreter ; } | Get the interpreter which provides the text to show in the header column and the header row . |
23,909 | private boolean forceFinishScroll ( ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . ICE_CREAM_SANDWICH ) { return mScroller . getCurrVelocity ( ) <= mMinimumFlingVelocity ; } else { return false ; } } | Check if scrolling should be stopped . |
23,910 | public void goToDate ( Calendar date ) { mScroller . forceFinished ( true ) ; mCurrentScrollDirection = mCurrentFlingDirection = Direction . NONE ; date . set ( Calendar . HOUR_OF_DAY , 0 ) ; date . set ( Calendar . MINUTE , 0 ) ; date . set ( Calendar . SECOND , 0 ) ; date . set ( Calendar . MILLISECOND , 0 ) ; if ( mAreDimensionsInvalid ) { mScrollToDay = date ; return ; } mRefreshEvents = true ; Calendar today = Calendar . getInstance ( ) ; today . set ( Calendar . HOUR_OF_DAY , 0 ) ; today . set ( Calendar . MINUTE , 0 ) ; today . set ( Calendar . SECOND , 0 ) ; today . set ( Calendar . MILLISECOND , 0 ) ; long day = 1000L * 60L * 60L * 24L ; long dateInMillis = date . getTimeInMillis ( ) + date . getTimeZone ( ) . getOffset ( date . getTimeInMillis ( ) ) ; long todayInMillis = today . getTimeInMillis ( ) + today . getTimeZone ( ) . getOffset ( today . getTimeInMillis ( ) ) ; long dateDifference = ( dateInMillis / day ) - ( todayInMillis / day ) ; mCurrentOrigin . x = - dateDifference * ( mWidthPerDay + mColumnGap ) ; invalidate ( ) ; } | Show a specific day on the week view . |
23,911 | public void goToHour ( double hour ) { if ( mAreDimensionsInvalid ) { mScrollToHour = hour ; return ; } int verticalOffset = 0 ; if ( hour > 24 ) verticalOffset = mHourHeight * 24 ; else if ( hour > 0 ) verticalOffset = ( int ) ( mHourHeight * hour ) ; if ( verticalOffset > mHourHeight * 24 - getHeight ( ) + mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom ) verticalOffset = ( int ) ( mHourHeight * 24 - getHeight ( ) + mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom ) ; mCurrentOrigin . y = - verticalOffset ; invalidate ( ) ; } | Vertically scroll to a specific hour in the week view . |
23,912 | private boolean eventMatches ( WeekViewEvent event , int year , int month ) { return ( event . getStartTime ( ) . get ( Calendar . YEAR ) == year && event . getStartTime ( ) . get ( Calendar . MONTH ) == month - 1 ) || ( event . getEndTime ( ) . get ( Calendar . YEAR ) == year && event . getEndTime ( ) . get ( Calendar . MONTH ) == month - 1 ) ; } | Checks if an event falls into a specific year and month . |
23,913 | public static boolean isSameDay ( Calendar dayOne , Calendar dayTwo ) { return dayOne . get ( Calendar . YEAR ) == dayTwo . get ( Calendar . YEAR ) && dayOne . get ( Calendar . DAY_OF_YEAR ) == dayTwo . get ( Calendar . DAY_OF_YEAR ) ; } | Checks if two times are on the same day . |
23,914 | private void setupDateTimeInterpreter ( final boolean shortDate ) { mWeekView . setDateTimeInterpreter ( new DateTimeInterpreter ( ) { public String interpretDate ( Calendar date ) { SimpleDateFormat weekdayNameFormat = new SimpleDateFormat ( "EEE" , Locale . getDefault ( ) ) ; String weekday = weekdayNameFormat . format ( date . getTime ( ) ) ; SimpleDateFormat format = new SimpleDateFormat ( " M/d" , Locale . getDefault ( ) ) ; if ( shortDate ) weekday = String . valueOf ( weekday . charAt ( 0 ) ) ; return weekday . toUpperCase ( ) + format . format ( date . getTime ( ) ) ; } public String interpretTime ( int hour ) { return hour > 11 ? ( hour - 12 ) + " PM" : ( hour == 0 ? "12 AM" : hour + " AM" ) ; } } ) ; } | Set up a date time interpreter which will show short date values when in week view and long date values otherwise . |
23,915 | public DialogPlusBuilder setOutMostMargin ( int left , int top , int right , int bottom ) { this . outMostMargin [ 0 ] = left ; this . outMostMargin [ 1 ] = top ; this . outMostMargin [ 2 ] = right ; this . outMostMargin [ 3 ] = bottom ; return this ; } | Add margins to your outmost view which contains everything . As default they are 0 are applied |
23,916 | public DialogPlusBuilder setMargin ( int left , int top , int right , int bottom ) { this . margin [ 0 ] = left ; this . margin [ 1 ] = top ; this . margin [ 2 ] = right ; this . margin [ 3 ] = bottom ; return this ; } | Add margins to your dialog . They are set to 0 except when gravity is center . In that case basic margins are applied |
23,917 | public DialogPlusBuilder setPadding ( int left , int top , int right , int bottom ) { this . padding [ 0 ] = left ; this . padding [ 1 ] = top ; this . padding [ 2 ] = right ; this . padding [ 3 ] = bottom ; return this ; } | Set paddings for the dialog content |
23,918 | private int getMargin ( int gravity , int margin , int minimumMargin ) { switch ( gravity ) { case Gravity . CENTER : return ( margin == INVALID ) ? minimumMargin : margin ; default : return ( margin == INVALID ) ? 0 : margin ; } } | Get margins if provided or assign default values based on gravity |
23,919 | public boolean isShowing ( ) { View view = decorView . findViewById ( R . id . dialogplus_outmost_container ) ; return view != null ; } | Checks if the dialog is shown |
23,920 | public void dismiss ( ) { if ( isDismissing ) { return ; } outAnim . setAnimationListener ( new Animation . AnimationListener ( ) { public void onAnimationStart ( Animation animation ) { } public void onAnimationEnd ( Animation animation ) { decorView . post ( new Runnable ( ) { public void run ( ) { decorView . removeView ( rootView ) ; isDismissing = false ; if ( onDismissListener != null ) { onDismissListener . onDismiss ( DialogPlus . this ) ; } } } ) ; } public void onAnimationRepeat ( Animation animation ) { } } ) ; contentContainer . startAnimation ( outAnim ) ; isDismissing = true ; } | Dismisses the displayed dialog . |
23,921 | private void initContentView ( LayoutInflater inflater , View header , boolean fixedHeader , View footer , boolean fixedFooter , BaseAdapter adapter , int [ ] padding , int [ ] margin ) { View contentView = createView ( inflater , header , fixedHeader , footer , fixedFooter , adapter ) ; FrameLayout . LayoutParams params = new FrameLayout . LayoutParams ( ViewGroup . LayoutParams . MATCH_PARENT , ViewGroup . LayoutParams . MATCH_PARENT ) ; params . setMargins ( margin [ 0 ] , margin [ 1 ] , margin [ 2 ] , margin [ 3 ] ) ; contentView . setLayoutParams ( params ) ; getHolderView ( ) . setPadding ( padding [ 0 ] , padding [ 1 ] , padding [ 2 ] , padding [ 3 ] ) ; contentContainer . addView ( contentView ) ; } | It is called in order to create content |
23,922 | private void initCancelable ( ) { if ( ! isCancelable ) { return ; } View view = rootView . findViewById ( R . id . dialogplus_outmost_container ) ; view . setOnTouchListener ( onCancelableTouchListener ) ; } | It is called to set whether the dialog is cancellable by pressing back button or touching the black overlay |
23,923 | private void assignClickListenerRecursively ( View parent ) { if ( parent == null ) { return ; } if ( parent instanceof ViewGroup ) { ViewGroup viewGroup = ( ViewGroup ) parent ; int childCount = viewGroup . getChildCount ( ) ; for ( int i = childCount - 1 ; i >= 0 ; i -- ) { View child = viewGroup . getChildAt ( i ) ; assignClickListenerRecursively ( child ) ; } } setClickListener ( parent ) ; } | Loop among the views in the hierarchy and assign listener to them |
23,924 | private void setClickListener ( View view ) { if ( view . getId ( ) == INVALID ) { return ; } if ( view instanceof AdapterView ) { return ; } view . setOnClickListener ( new View . OnClickListener ( ) { public void onClick ( View v ) { if ( onClickListener == null ) { return ; } onClickListener . onClick ( DialogPlus . this , v ) ; } } ) ; } | It is used to setListener on view that have a valid id associated |
23,925 | static View getView ( Context context , int resourceId , View view ) { LayoutInflater inflater = LayoutInflater . from ( context ) ; if ( view != null ) { return view ; } if ( resourceId != INVALID ) { view = inflater . inflate ( resourceId , null ) ; } return view ; } | This will be called in order to create view if the given view is not null it will be used directly otherwise it will check the resourceId |
23,926 | static int getAnimationResource ( int gravity , boolean isInAnimation ) { if ( ( gravity & Gravity . TOP ) == Gravity . TOP ) { return isInAnimation ? R . anim . slide_in_top : R . anim . slide_out_top ; } if ( ( gravity & Gravity . BOTTOM ) == Gravity . BOTTOM ) { return isInAnimation ? R . anim . slide_in_bottom : R . anim . slide_out_bottom ; } if ( ( gravity & Gravity . CENTER ) == Gravity . CENTER ) { return isInAnimation ? R . anim . fade_in_center : R . anim . fade_out_center ; } return INVALID ; } | Get default animation resource when not defined by the user |
23,927 | public static void install ( final EmojiProvider provider ) { INSTANCE . categories = checkNotNull ( provider . getCategories ( ) , "categories == null" ) ; INSTANCE . emojiMap . clear ( ) ; INSTANCE . emojiReplacer = provider instanceof EmojiReplacer ? ( EmojiReplacer ) provider : DEFAULT_EMOJI_REPLACER ; final List < String > unicodesForPattern = new ArrayList < > ( GUESSED_UNICODE_AMOUNT ) ; final int categoriesSize = INSTANCE . categories . length ; for ( int i = 0 ; i < categoriesSize ; i ++ ) { final Emoji [ ] emojis = checkNotNull ( INSTANCE . categories [ i ] . getEmojis ( ) , "emojies == null" ) ; final int emojisSize = emojis . length ; for ( int j = 0 ; j < emojisSize ; j ++ ) { final Emoji emoji = emojis [ j ] ; final String unicode = emoji . getUnicode ( ) ; final List < Emoji > variants = emoji . getVariants ( ) ; INSTANCE . emojiMap . put ( unicode , emoji ) ; unicodesForPattern . add ( unicode ) ; for ( int k = 0 ; k < variants . size ( ) ; k ++ ) { final Emoji variant = variants . get ( k ) ; final String variantUnicode = variant . getUnicode ( ) ; INSTANCE . emojiMap . put ( variantUnicode , variant ) ; unicodesForPattern . add ( variantUnicode ) ; } } } if ( unicodesForPattern . isEmpty ( ) ) { throw new IllegalArgumentException ( "Your EmojiProvider must at least have one category with at least one emoji." ) ; } Collections . sort ( unicodesForPattern , STRING_LENGTH_COMPARATOR ) ; final StringBuilder patternBuilder = new StringBuilder ( GUESSED_TOTAL_PATTERN_LENGTH ) ; final int unicodesForPatternSize = unicodesForPattern . size ( ) ; for ( int i = 0 ; i < unicodesForPatternSize ; i ++ ) { patternBuilder . append ( Pattern . quote ( unicodesForPattern . get ( i ) ) ) . append ( '|' ) ; } final String regex = patternBuilder . deleteCharAt ( patternBuilder . length ( ) - 1 ) . toString ( ) ; INSTANCE . emojiPattern = Pattern . compile ( regex ) ; INSTANCE . emojiRepetitivePattern = Pattern . compile ( '(' + regex + ")+" ) ; } | Installs the given EmojiProvider . |
23,928 | public static boolean isOnlyEmojis ( final String text ) { if ( ! TextUtils . isEmpty ( text ) ) { final String inputWithoutSpaces = SPACE_REMOVAL . matcher ( text ) . replaceAll ( Matcher . quoteReplacement ( "" ) ) ; return EmojiManager . getInstance ( ) . getEmojiRepetitivePattern ( ) . matcher ( inputWithoutSpaces ) . matches ( ) ; } return false ; } | returns true when the string contains only emojis . Note that whitespace will be filtered out . |
23,929 | public static List < EmojiRange > emojis ( final String text ) { return EmojiManager . getInstance ( ) . findAllEmojis ( text ) ; } | returns the emojis that were found in the given text |
23,930 | public static EmojiInformation emojiInformation ( final String text ) { final List < EmojiRange > emojis = EmojiManager . getInstance ( ) . findAllEmojis ( text ) ; final boolean isOnlyEmojis = isOnlyEmojis ( text ) ; return new EmojiInformation ( isOnlyEmojis , emojis ) ; } | returns a class that contains all of the emoji information that was found in the given text |
23,931 | public static PendingResult < ElevationResult [ ] > getByPoints ( GeoApiContext context , LatLng ... points ) { return context . get ( API_CONFIG , MultiResponse . class , "locations" , shortestParam ( points ) ) ; } | Gets a list of elevations for a list of points . |
23,932 | public static PendingResult < ElevationResult > getByPoint ( GeoApiContext context , LatLng location ) { return context . get ( API_CONFIG , SingularResponse . class , "locations" , location . toString ( ) ) ; } | Retrieves the elevation of a single location . |
23,933 | public static PendingResult < ElevationResult [ ] > getByPoints ( GeoApiContext context , EncodedPolyline encodedPolyline ) { return context . get ( API_CONFIG , MultiResponse . class , "locations" , "enc:" + encodedPolyline . getEncodedPath ( ) ) ; } | Retrieves the elevations of an encoded polyline path . |
23,934 | public GeocodingApiRequest bounds ( LatLng southWestBound , LatLng northEastBound ) { return param ( "bounds" , join ( '|' , southWestBound , northEastBound ) ) ; } | Sets the bounding box of the viewport within which to bias geocode results more prominently . This parameter will only influence not fully restrict results from the geocoder . |
23,935 | public DistanceMatrixApiRequest mode ( TravelMode mode ) { if ( TravelMode . DRIVING . equals ( mode ) || TravelMode . WALKING . equals ( mode ) || TravelMode . BICYCLING . equals ( mode ) || TravelMode . TRANSIT . equals ( mode ) ) { return param ( "mode" , mode ) ; } throw new IllegalArgumentException ( "Distance Matrix API travel modes must be Driving, Transit, Walking or Bicycling" ) ; } | Specifies the mode of transport to use when calculating directions . |
23,936 | public DirectionsApiRequest waypointsFromPlaceIds ( String ... waypoints ) { Waypoint [ ] objWaypoints = new Waypoint [ waypoints . length ] ; for ( int i = 0 ; i < waypoints . length ; i ++ ) { objWaypoints [ i ] = new Waypoint ( prefixPlaceId ( waypoints [ i ] ) ) ; } return waypoints ( objWaypoints ) ; } | Specifies the list of waypoints as Plade ID Strings prefixing them as required by the API . |
23,937 | public LatLng read ( JsonReader reader ) throws IOException { if ( reader . peek ( ) == JsonToken . NULL ) { reader . nextNull ( ) ; return null ; } double lat = 0 ; double lng = 0 ; boolean hasLat = false ; boolean hasLng = false ; reader . beginObject ( ) ; while ( reader . hasNext ( ) ) { String name = reader . nextName ( ) ; if ( "lat" . equals ( name ) || "latitude" . equals ( name ) ) { lat = reader . nextDouble ( ) ; hasLat = true ; } else if ( "lng" . equals ( name ) || "longitude" . equals ( name ) ) { lng = reader . nextDouble ( ) ; hasLng = true ; } } reader . endObject ( ) ; if ( hasLat && hasLng ) { return new LatLng ( lat , lng ) ; } else { return null ; } } | Reads in a JSON object and try to create a LatLng in one of the following formats . |
23,938 | public static DirectionsApiRequest getDirections ( GeoApiContext context , String origin , String destination ) { return new DirectionsApiRequest ( context ) . origin ( origin ) . destination ( destination ) ; } | Creates a new DirectionsApiRequest between the given origin and destination using the defaults for all other options . |
23,939 | public static ApiException from ( String status , String errorMessage ) { if ( "OK" . equals ( status ) ) { return null ; } else if ( "INVALID_REQUEST" . equals ( status ) ) { return new InvalidRequestException ( errorMessage ) ; } else if ( "MAX_ELEMENTS_EXCEEDED" . equals ( status ) ) { return new MaxElementsExceededException ( errorMessage ) ; } else if ( "NOT_FOUND" . equals ( status ) ) { return new NotFoundException ( errorMessage ) ; } else if ( "OVER_QUERY_LIMIT" . equals ( status ) ) { if ( "You have exceeded your daily request quota for this API." . equalsIgnoreCase ( errorMessage ) ) { return new OverDailyLimitException ( errorMessage ) ; } return new OverQueryLimitException ( errorMessage ) ; } else if ( "REQUEST_DENIED" . equals ( status ) ) { return new RequestDeniedException ( errorMessage ) ; } else if ( "UNKNOWN_ERROR" . equals ( status ) ) { return new UnknownErrorException ( errorMessage ) ; } else if ( "ZERO_RESULTS" . equals ( status ) ) { return new ZeroResultsException ( errorMessage ) ; } if ( "ACCESS_NOT_CONFIGURED" . equals ( status ) ) { return new AccessNotConfiguredException ( errorMessage ) ; } else if ( "INVALID_ARGUMENT" . equals ( status ) ) { return new InvalidRequestException ( errorMessage ) ; } else if ( "RESOURCE_EXHAUSTED" . equals ( status ) ) { return new OverQueryLimitException ( errorMessage ) ; } else if ( "PERMISSION_DENIED" . equals ( status ) ) { return new RequestDeniedException ( errorMessage ) ; } if ( "keyInvalid" . equals ( status ) ) { return new AccessNotConfiguredException ( errorMessage ) ; } else if ( "dailyLimitExceeded" . equals ( status ) ) { return new OverDailyLimitException ( errorMessage ) ; } else if ( "userRateLimitExceeded" . equals ( status ) ) { return new OverQueryLimitException ( errorMessage ) ; } else if ( "notFound" . equals ( status ) ) { return new NotFoundException ( errorMessage ) ; } else if ( "parseError" . equals ( status ) ) { return new InvalidRequestException ( errorMessage ) ; } else if ( "invalid" . equals ( status ) ) { return new InvalidRequestException ( errorMessage ) ; } return new UnknownErrorException ( "An unexpected error occurred. Status: " + status + ", Message: " + errorMessage ) ; } | Construct the appropriate ApiException from the response . If the response was successful this method will return null . |
23,940 | public static List < LatLng > decode ( final String encodedPath ) { int len = encodedPath . length ( ) ; final List < LatLng > path = new ArrayList < > ( len / 2 ) ; int index = 0 ; int lat = 0 ; int lng = 0 ; while ( index < len ) { int result = 1 ; int shift = 0 ; int b ; do { b = encodedPath . charAt ( index ++ ) - 63 - 1 ; result += b << shift ; shift += 5 ; } while ( b >= 0x1f ) ; lat += ( result & 1 ) != 0 ? ~ ( result >> 1 ) : ( result >> 1 ) ; result = 1 ; shift = 0 ; do { b = encodedPath . charAt ( index ++ ) - 63 - 1 ; result += b << shift ; shift += 5 ; } while ( b >= 0x1f ) ; lng += ( result & 1 ) != 0 ? ~ ( result >> 1 ) : ( result >> 1 ) ; path . add ( new LatLng ( lat * 1e-5 , lng * 1e-5 ) ) ; } return path ; } | Decodes an encoded path string into a sequence of LatLngs . |
23,941 | public static String encode ( final List < LatLng > path ) { long lastLat = 0 ; long lastLng = 0 ; final StringBuilder result = new StringBuilder ( ) ; for ( final LatLng point : path ) { long lat = Math . round ( point . lat * 1e5 ) ; long lng = Math . round ( point . lng * 1e5 ) ; long dLat = lat - lastLat ; long dLng = lng - lastLng ; encode ( dLat , result ) ; encode ( dLng , result ) ; lastLat = lat ; lastLng = lng ; } return result . toString ( ) ; } | Encodes a sequence of LatLngs into an encoded path string . |
23,942 | public static NearbySearchRequest nearbySearchQuery ( GeoApiContext context , LatLng location ) { NearbySearchRequest request = new NearbySearchRequest ( context ) ; request . location ( location ) ; return request ; } | Performs a search for nearby Places . |
23,943 | public static NearbySearchRequest nearbySearchNextPage ( GeoApiContext context , String nextPageToken ) { NearbySearchRequest request = new NearbySearchRequest ( context ) ; request . pageToken ( nextPageToken ) ; return request ; } | Retrieves the next page of Nearby Search results . The nextPageToken returned in a PlacesSearchResponse when there are more pages of results encodes all of the original Nearby Search Request parameters which are thus not required on this call . |
23,944 | public static TextSearchRequest textSearchQuery ( GeoApiContext context , String query ) { TextSearchRequest request = new TextSearchRequest ( context ) ; request . query ( query ) ; return request ; } | Performs a search for Places using a text query ; for example pizza in New York or shoe stores near Ottawa . |
23,945 | public static TextSearchRequest textSearchNextPage ( GeoApiContext context , String nextPageToken ) { TextSearchRequest request = new TextSearchRequest ( context ) ; request . pageToken ( nextPageToken ) ; return request ; } | Retrieves the next page of Text Search results . The nextPageToken returned in a PlacesSearchResponse when there are more pages of results encodes all of the original Text Search Request parameters which are thus not required on this call . |
23,946 | public static PhotoRequest photo ( GeoApiContext context , String photoReference ) { PhotoRequest request = new PhotoRequest ( context ) ; request . photoReference ( photoReference ) ; return request ; } | Requests a Photo from a PhotoReference . |
23,947 | public static PlaceAutocompleteRequest placeAutocomplete ( GeoApiContext context , String input , PlaceAutocompleteRequest . SessionToken sessionToken ) { PlaceAutocompleteRequest request = new PlaceAutocompleteRequest ( context ) ; request . input ( input ) ; request . sessionToken ( sessionToken ) ; return request ; } | Creates a new Places Autocomplete request for a given input . The Place Autocomplete service can match on full words as well as substrings . Applications can therefore send queries as the user types to provide on - the - fly place predictions . |
23,948 | public static QueryAutocompleteRequest queryAutocomplete ( GeoApiContext context , String input ) { QueryAutocompleteRequest request = new QueryAutocompleteRequest ( context ) ; request . input ( input ) ; return request ; } | Allows you to add on - the - fly geographic query predictions to your application . |
23,949 | public static FindPlaceFromTextRequest findPlaceFromText ( GeoApiContext context , String input , FindPlaceFromTextRequest . InputType inputType ) { FindPlaceFromTextRequest request = new FindPlaceFromTextRequest ( context ) ; request . input ( input ) . inputType ( inputType ) ; return request ; } | Find places using either search text or a phone number . |
23,950 | public List < Runnable > shutdownNow ( ) { List < Runnable > tasks = delegate . shutdownNow ( ) ; execute ( new Runnable ( ) { public void run ( ) { } } ) ; return tasks ; } | Everything below here is straight delegation . |
23,951 | public String getSignature ( String path ) { byte [ ] digest = getMac ( ) . doFinal ( path . getBytes ( UTF_8 ) ) ; return ByteString . of ( digest ) . base64 ( ) . replace ( '+' , '-' ) . replace ( '/' , '_' ) ; } | Generate url safe HmacSHA1 of a path . |
23,952 | public static PendingResult < SnappedPoint [ ] > snapToRoads ( GeoApiContext context , LatLng ... path ) { return context . get ( SNAP_TO_ROADS_API_CONFIG , RoadsResponse . class , "path" , join ( '|' , path ) ) ; } | Takes up to 100 GPS points collected along a route and returns a similar set of data with the points snapped to the most likely roads the vehicle was traveling along . |
23,953 | public static PendingResult < SnappedPoint [ ] > snapToRoads ( GeoApiContext context , boolean interpolate , LatLng ... path ) { return context . get ( SNAP_TO_ROADS_API_CONFIG , RoadsResponse . class , "path" , join ( '|' , path ) , "interpolate" , String . valueOf ( interpolate ) ) ; } | Takes up to 100 GPS points collected along a route and returns a similar set of data with the points snapped to the most likely roads the vehicle was traveling along . Additionally you can request that the points be interpolated resulting in a path that smoothly follows the geometry of the road . |
23,954 | public static PendingResult < SpeedLimit [ ] > speedLimits ( GeoApiContext context , LatLng ... path ) { return context . get ( SPEEDS_API_CONFIG , SpeedsResponse . class , "path" , join ( '|' , path ) ) ; } | Returns the posted speed limit for given road segments . The provided LatLngs will first be snapped to the most likely roads the vehicle was traveling along . |
23,955 | public static PendingResult < SpeedLimit [ ] > speedLimits ( GeoApiContext context , String ... placeIds ) { String [ ] placeParams = new String [ 2 * placeIds . length ] ; int i = 0 ; for ( String placeId : placeIds ) { placeParams [ i ++ ] = "placeId" ; placeParams [ i ++ ] = placeId ; } return context . get ( SPEEDS_API_CONFIG , SpeedsResponse . class , placeParams ) ; } | Returns the posted speed limit for given road segments . |
23,956 | public static PendingResult < SnappedSpeedLimitResponse > snappedSpeedLimits ( GeoApiContext context , LatLng ... path ) { return context . get ( SPEEDS_API_CONFIG , CombinedResponse . class , "path" , join ( '|' , path ) ) ; } | Returns the result of snapping the provided points to roads and retrieving the speed limits . |
23,957 | public static PendingResult < SnappedPoint [ ] > nearestRoads ( GeoApiContext context , LatLng ... points ) { return context . get ( NEAREST_ROADS_API_CONFIG , RoadsResponse . class , "points" , join ( '|' , points ) ) ; } | Takes up to 100 GPS points and returns the closest road segment for each point . The points passed do not need to be part of a continuous path . |
23,958 | public CommandLine setInterpolateVariables ( boolean interpolate ) { getCommandSpec ( ) . interpolateVariables ( interpolate ) ; for ( CommandLine command : getCommandSpec ( ) . subcommands ( ) . values ( ) ) { command . setInterpolateVariables ( interpolate ) ; } return this ; } | Sets whether whether variables should be interpolated in String values . |
23,959 | public CommandLine setEndOfOptionsDelimiter ( String delimiter ) { getCommandSpec ( ) . parser ( ) . endOfOptionsDelimiter ( delimiter ) ; for ( CommandLine command : getCommandSpec ( ) . subcommands ( ) . values ( ) ) { command . setEndOfOptionsDelimiter ( delimiter ) ; } return this ; } | Sets the end - of - options delimiter that signals that the remaining command line arguments should be treated as positional parameters . |
23,960 | public List < String > getUnmatchedArguments ( ) { return interpreter . parseResultBuilder == null ? Collections . < String > emptyList ( ) : UnmatchedArgumentException . stripErrorMessage ( interpreter . parseResultBuilder . unmatched ) ; } | Returns the list of unmatched command line arguments if any . |
23,961 | public CommandLine setColorScheme ( Help . ColorScheme colorScheme ) { this . colorScheme = Assert . notNull ( colorScheme , "colorScheme" ) ; for ( CommandLine sub : getSubcommands ( ) . values ( ) ) { sub . setColorScheme ( colorScheme ) ; } return this ; } | Sets the color scheme to use when printing help . |
23,962 | private boolean shouldImport ( TypeName typeName ) { String pkg = typeName . getPackageName ( ) ; String simpleName = typeName . getSimpleName ( ) ; boolean exclude = ( pkg . equals ( "java.lang" ) || pkg . equals ( "" ) ) && getJavaDefaultTypes ( ) . contains ( simpleName ) ; return ! exclude ; } | Determines whether the given non - wildcard import should be added . By default this returns false if the simple name is a built - in Java language type name . |
23,963 | public String createImportDeclaration ( String lineDelimiter ) { StringBuilder result = new StringBuilder ( ) ; for ( TypeName importName : getImports ( ) ) { result . append ( lineDelimiter + "import " + importName + ";" ) ; } return result . toString ( ) ; } | Returns a string with the import declarations to add to the class using the specified line separator to separate import lines . |
23,964 | public static < T > T notNull ( T object , String description ) { if ( object == null ) { throw new NullPointerException ( description ) ; } return object ; } | Throws a NullPointerException if the specified object is null . |
23,965 | public static String toJavaDateTimeFormat ( String strftime ) { if ( ! StringUtils . contains ( strftime , '%' ) ) { return replaceL ( strftime ) ; } StringBuilder result = new StringBuilder ( ) ; for ( int i = 0 ; i < strftime . length ( ) ; i ++ ) { char c = strftime . charAt ( i ) ; if ( c == '%' ) { c = strftime . charAt ( ++ i ) ; boolean stripLeadingZero = false ; if ( c == '-' ) { stripLeadingZero = true ; c = strftime . charAt ( ++ i ) ; } if ( stripLeadingZero ) { result . append ( CONVERSIONS [ c ] . substring ( 1 ) ) ; } else { result . append ( CONVERSIONS [ c ] ) ; } } else if ( Character . isLetter ( c ) ) { result . append ( "'" ) ; while ( Character . isLetter ( c ) ) { result . append ( c ) ; if ( ++ i < strftime . length ( ) ) { c = strftime . charAt ( i ) ; } else { c = 0 ; } } result . append ( "'" ) ; -- i ; } else { result . append ( c ) ; } } return replaceL ( result . toString ( ) ) ; } | Parses a string in python strftime format returning the equivalent string in java date time format . |
23,966 | public String render ( String template , Map < String , ? > bindings ) { RenderResult result = renderForResult ( template , bindings ) ; List < TemplateError > fatalErrors = result . getErrors ( ) . stream ( ) . filter ( error -> error . getSeverity ( ) == ErrorType . FATAL ) . collect ( Collectors . toList ( ) ) ; if ( ! fatalErrors . isEmpty ( ) ) { throw new FatalTemplateErrorsException ( template , fatalErrors ) ; } return result . getOutput ( ) ; } | Render the given template using the given context bindings . |
23,967 | public void addResolvedFrom ( Context context ) { context . getResolvedExpressions ( ) . forEach ( this :: addResolvedExpression ) ; context . getResolvedFunctions ( ) . forEach ( this :: addResolvedFunction ) ; context . getResolvedValues ( ) . forEach ( this :: addResolvedValue ) ; } | Take all resolved strings from a context object and apply them to this context . Useful for passing resolved values up a tag hierarchy . |
23,968 | public String renderFlat ( String template ) { int depth = context . getRenderDepth ( ) ; try { if ( depth > config . getMaxRenderDepth ( ) ) { ENGINE_LOG . warn ( "Max render depth exceeded: {}" , Integer . toString ( depth ) ) ; return template ; } else { context . setRenderDepth ( depth + 1 ) ; return render ( parse ( template ) , false ) ; } } finally { context . setRenderDepth ( depth ) ; } } | Parse the given string into a root Node and then render it without processing any extend parents . This method should be used when the template is known to not have any extends or block tags . |
23,969 | public String render ( String template ) { ENGINE_LOG . debug ( template ) ; return render ( parse ( template ) , true ) ; } | Parse the given string into a root Node and then renders it processing extend parents . |
23,970 | public String render ( Node root , boolean processExtendRoots ) { OutputList output = new OutputList ( config . getMaxOutputSize ( ) ) ; for ( Node node : root . getChildren ( ) ) { lineNumber = node . getLineNumber ( ) ; position = node . getStartPosition ( ) ; String renderStr = node . getMaster ( ) . getImage ( ) ; if ( context . doesRenderStackContain ( renderStr ) ) { addError ( new TemplateError ( ErrorType . WARNING , ErrorReason . EXCEPTION , ErrorItem . TAG , "Rendering cycle detected: '" + renderStr + "'" , null , getLineNumber ( ) , node . getStartPosition ( ) , null , BasicTemplateErrorCategory . IMPORT_CYCLE_DETECTED , ImmutableMap . of ( "string" , renderStr ) ) ) ; output . addNode ( new RenderedOutputNode ( renderStr ) ) ; } else { OutputNode out ; context . pushRenderStack ( renderStr ) ; try { out = node . render ( this ) ; } catch ( DeferredValueException e ) { out = new RenderedOutputNode ( node . getMaster ( ) . getImage ( ) ) ; } context . popRenderStack ( ) ; output . addNode ( out ) ; } } if ( processExtendRoots ) { while ( ! extendParentRoots . isEmpty ( ) ) { context . getCurrentPathStack ( ) . push ( context . getExtendPathStack ( ) . peek ( ) . orElse ( "" ) , lineNumber , position ) ; Node parentRoot = extendParentRoots . removeFirst ( ) ; output = new OutputList ( config . getMaxOutputSize ( ) ) ; for ( Node node : parentRoot . getChildren ( ) ) { OutputNode out = node . render ( this ) ; output . addNode ( out ) ; } context . getExtendPathStack ( ) . pop ( ) ; context . getCurrentPathStack ( ) . pop ( ) ; } } resolveBlockStubs ( output ) ; return output . getValue ( ) ; } | Render the given root node using this interpreter s current context |
23,971 | public Object retraceVariable ( String variable , int lineNumber , int startPosition ) { if ( StringUtils . isBlank ( variable ) ) { return "" ; } Variable var = new Variable ( this , variable ) ; String varName = var . getName ( ) ; Object obj = context . get ( varName ) ; if ( obj != null ) { if ( obj instanceof DeferredValue ) { throw new DeferredValueException ( variable , lineNumber , startPosition ) ; } obj = var . resolve ( obj ) ; } else if ( getConfig ( ) . isFailOnUnknownTokens ( ) ) { throw new UnknownTokenException ( variable , lineNumber , startPosition ) ; } return obj ; } | Resolve a variable from the interpreter context returning null if not found . This method updates the template error accumulators when a variable is not found . |
23,972 | protected void parse ( ) { if ( image . length ( ) < 4 ) { throw new TemplateSyntaxException ( image , "Malformed tag token" , getLineNumber ( ) , getStartPosition ( ) ) ; } content = image . substring ( 2 , image . length ( ) - 2 ) ; if ( WhitespaceUtils . startsWith ( content , "-" ) ) { setLeftTrim ( true ) ; content = WhitespaceUtils . unwrap ( content , "-" , "" ) ; } if ( WhitespaceUtils . endsWith ( content , "-" ) ) { setRightTrim ( true ) ; content = WhitespaceUtils . unwrap ( content , "" , "-" ) ; } int nameStart = - 1 , pos = 0 , len = content . length ( ) ; for ( ; pos < len ; pos ++ ) { char c = content . charAt ( pos ) ; if ( nameStart == - 1 && Character . isJavaIdentifierStart ( c ) ) { nameStart = pos ; } else if ( nameStart != - 1 && ! Character . isJavaIdentifierPart ( c ) ) { break ; } } if ( pos < content . length ( ) ) { rawTagName = content . substring ( nameStart , pos ) ; helpers = content . substring ( pos ) ; } else { rawTagName = content . trim ( ) ; helpers = "" ; } tagName = rawTagName . toLowerCase ( ) ; } | Get tag name |
23,973 | private String transformPropertyName ( Object property ) { if ( property == null ) { return null ; } String propertyStr = property . toString ( ) ; if ( propertyStr . indexOf ( '_' ) == - 1 ) { return propertyStr ; } return CaseFormat . LOWER_UNDERSCORE . to ( CaseFormat . LOWER_CAMEL , propertyStr ) ; } | Transform snake case to property name . |
23,974 | private static int toIndex ( Object property ) { int index = 0 ; if ( property instanceof Number ) { index = ( ( Number ) property ) . intValue ( ) ; } else if ( property instanceof String ) { try { index = Integer . parseInt ( ( String ) property ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "Cannot parse list index: " + property ) ; } } else if ( property instanceof Character ) { index = ( ( Character ) property ) . charValue ( ) ; } else if ( property instanceof Boolean ) { index = ( ( Boolean ) property ) . booleanValue ( ) ? 1 : 0 ; } else { throw new IllegalArgumentException ( "Cannot coerce property to list index: " + property ) ; } return index ; } | Convert the given property to an index . Inspired by ListELResolver . toIndex but without the base param since we only use it for getValue where base is null . |
23,975 | public BinaryUploadRequest setFileToUpload ( String path ) throws FileNotFoundException { params . files . clear ( ) ; params . files . add ( new UploadFile ( path ) ) ; return this ; } | Sets the file used as raw body of the upload request . |
23,976 | public boolean checkPermissions ( ) { if ( Build . VERSION . SDK_INT <= Build . VERSION_CODES . LOLLIPOP_MR1 ) return true ; for ( String permission : mRequiredPermissions ) { if ( ContextCompat . checkSelfPermission ( mContext , permission ) != PackageManager . PERMISSION_GRANTED ) { mPermissionsToRequest . add ( permission ) ; } } if ( mPermissionsToRequest . isEmpty ( ) ) { return true ; } return false ; } | Checks if all the required permissions are granted . |
23,977 | public MultipartUploadRequest addFileToUpload ( String filePath , String parameterName , String fileName , String contentType ) throws FileNotFoundException , IllegalArgumentException { UploadFile file = new UploadFile ( filePath ) ; filePath = file . getPath ( ) ; if ( parameterName == null || "" . equals ( parameterName ) ) { throw new IllegalArgumentException ( "Please specify parameterName value for file: " + filePath ) ; } file . setProperty ( MultipartUploadTask . PROPERTY_PARAM_NAME , parameterName ) ; if ( contentType == null || contentType . isEmpty ( ) ) { contentType = file . getContentType ( context ) ; Logger . debug ( LOG_TAG , "Auto-detected MIME type for " + filePath + " is: " + contentType ) ; } else { Logger . debug ( LOG_TAG , "Content Type set for " + filePath + " is: " + contentType ) ; } file . setProperty ( MultipartUploadTask . PROPERTY_CONTENT_TYPE , contentType ) ; if ( fileName == null || "" . equals ( fileName ) ) { fileName = file . getName ( context ) ; Logger . debug ( LOG_TAG , "Using original file name: " + fileName ) ; } else { Logger . debug ( LOG_TAG , "Using custom file name: " + fileName ) ; } file . setProperty ( MultipartUploadTask . PROPERTY_REMOTE_FILE_NAME , fileName ) ; params . files . add ( file ) ; return this ; } | Adds a file to this upload request . |
23,978 | public final UploadNotificationConfig setTitleForAllStatuses ( String title ) { progress . title = title ; completed . title = title ; error . title = title ; cancelled . title = title ; return this ; } | Sets the notification title for all the notification statuses . |
23,979 | public final UploadNotificationConfig setLargeIconForAllStatuses ( Bitmap largeIcon ) { progress . largeIcon = largeIcon ; completed . largeIcon = largeIcon ; error . largeIcon = largeIcon ; cancelled . largeIcon = largeIcon ; return this ; } | Sets the same large notification icon for all the notification statuses . |
23,980 | public final UploadNotificationConfig setClickIntentForAllStatuses ( PendingIntent clickIntent ) { progress . clickIntent = clickIntent ; completed . clickIntent = clickIntent ; error . clickIntent = clickIntent ; cancelled . clickIntent = clickIntent ; return this ; } | Sets the same intent to be executed when the user taps on the notification for all the notification statuses . |
23,981 | public final UploadNotificationConfig addActionForAllStatuses ( UploadNotificationAction action ) { progress . actions . add ( action ) ; completed . actions . add ( action ) ; error . actions . add ( action ) ; cancelled . actions . add ( action ) ; return this ; } | Adds the same notification action for all the notification statuses . So for example if you want to have the same action while the notification is in progress cancelled completed or with an error this method will save you lines of code . |
23,982 | public B addHeader ( final String headerName , final String headerValue ) { httpParams . addHeader ( headerName , headerValue ) ; return self ( ) ; } | Adds a header to this upload request . |
23,983 | public B setBasicAuth ( final String username , final String password ) { String auth = Base64 . encodeToString ( ( username + ":" + password ) . getBytes ( ) , Base64 . NO_WRAP ) ; httpParams . addHeader ( "Authorization" , "Basic " + auth ) ; return self ( ) ; } | Sets the HTTP Basic Authentication header . |
23,984 | public B addParameter ( final String paramName , final String paramValue ) { httpParams . addParameter ( paramName , paramValue ) ; return self ( ) ; } | Adds a parameter to this upload request . |
23,985 | public B setCustomUserAgent ( String customUserAgent ) { if ( customUserAgent != null && ! customUserAgent . isEmpty ( ) ) { httpParams . customUserAgent = customUserAgent ; } return self ( ) ; } | Sets the custom user agent to use for this upload request . Note! If you set the User - Agent header by using the addHeader method that setting will be overwritten by the value set with this method . |
23,986 | public static synchronized void stopUpload ( final String uploadId ) { UploadTask removedTask = uploadTasksMap . get ( uploadId ) ; if ( removedTask != null ) { removedTask . cancel ( ) ; } } | Stops the upload task with the given uploadId . |
23,987 | public static synchronized List < String > getTaskList ( ) { List < String > tasks ; if ( uploadTasksMap . isEmpty ( ) ) { tasks = new ArrayList < > ( 1 ) ; } else { tasks = new ArrayList < > ( uploadTasksMap . size ( ) ) ; tasks . addAll ( uploadTasksMap . keySet ( ) ) ; } return tasks ; } | Gets the list of the currently active upload tasks . |
23,988 | public static synchronized void stopAllUploads ( ) { if ( uploadTasksMap . isEmpty ( ) ) { return ; } Iterator < String > iterator = uploadTasksMap . keySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { UploadTask taskToCancel = uploadTasksMap . get ( iterator . next ( ) ) ; taskToCancel . cancel ( ) ; } } | Stop all the active uploads . |
23,989 | UploadTask getTask ( Intent intent ) { String taskClass = intent . getStringExtra ( PARAM_TASK_CLASS ) ; if ( taskClass == null ) { return null ; } UploadTask uploadTask = null ; try { Class < ? > task = Class . forName ( taskClass ) ; if ( UploadTask . class . isAssignableFrom ( task ) ) { uploadTask = UploadTask . class . cast ( task . newInstance ( ) ) ; uploadTask . init ( this , intent ) ; } else { Logger . error ( TAG , taskClass + " does not extend UploadTask!" ) ; } Logger . debug ( TAG , "Successfully created new task with class: " + taskClass ) ; } catch ( Exception exc ) { Logger . error ( TAG , "Error while instantiating new task" , exc ) ; } return uploadTask ; } | Creates a new task instance based on the requested task class in the intent . |
23,990 | protected synchronized boolean holdForegroundNotification ( String uploadId , Notification notification ) { if ( ! isExecuteInForeground ( ) ) return false ; if ( foregroundUploadId == null ) { foregroundUploadId = uploadId ; Logger . debug ( TAG , uploadId + " now holds the foreground notification" ) ; } if ( uploadId . equals ( foregroundUploadId ) ) { startForeground ( UPLOAD_NOTIFICATION_BASE_ID , notification ) ; return true ; } return false ; } | Check if the task is currently the one shown in the foreground notification . |
23,991 | protected static void setUploadStatusDelegate ( String uploadId , UploadStatusDelegate delegate ) { if ( delegate == null ) return ; uploadDelegates . put ( uploadId , new WeakReference < > ( delegate ) ) ; } | Sets the delegate which will receive the events for the given upload request . Those events will not be sent in broadcast but only to the delegate . |
23,992 | protected static UploadStatusDelegate getUploadStatusDelegate ( String uploadId ) { WeakReference < UploadStatusDelegate > reference = uploadDelegates . get ( uploadId ) ; if ( reference == null ) return null ; UploadStatusDelegate delegate = reference . get ( ) ; if ( delegate == null ) { uploadDelegates . remove ( uploadId ) ; Logger . info ( TAG , "\n\n\nUpload delegate for upload with Id " + uploadId + " is gone!\n" + "Probably you have set it in an activity and the user navigated away from it\n" + "before the upload was completed. From now on, the events will be dispatched\n" + "with broadcast intents. If you see this message, consider switching to the\n" + "UploadServiceBroadcastReceiver registered globally in your manifest.\n" + "Read this:\n" + "https://github.com/gotev/android-upload-service/wiki/Monitoring-upload-status\n" ) ; } return delegate ; } | Gets the delegate for an upload request . |
23,993 | public String startUpload ( ) { UploadService . setUploadStatusDelegate ( params . id , delegate ) ; final Intent intent = new Intent ( context , UploadService . class ) ; this . initializeIntent ( intent ) ; intent . setAction ( UploadService . getActionUpload ( ) ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . O ) { if ( params . notificationConfig == null ) { throw new IllegalArgumentException ( "Android Oreo requires a notification configuration for the service to run. https://developer.android.com/reference/android/content/Context.html#startForegroundService(android.content.Intent)" ) ; } context . startForegroundService ( intent ) ; } else { context . startService ( intent ) ; } return params . id ; } | Start the background file upload service . |
23,994 | public void goUp ( ) { mCurrentPath = getParent ( mCurrentPath ) ; mCheckedItems . clear ( ) ; mCheckedVisibleViewHolders . clear ( ) ; refresh ( mCurrentPath ) ; } | Go up on level same as pressing on .. . |
23,995 | public String getProperty ( String key , String defaultValue ) { String val = properties . get ( key ) ; if ( val == null ) { val = defaultValue ; } return val ; } | Gets a property associated to this file . |
23,996 | private void calculateUploadedAndTotalBytes ( ) { uploadedBytes = 0 ; for ( String filePath : getSuccessfullyUploadedFiles ( ) ) { uploadedBytes += new File ( filePath ) . length ( ) ; } totalBytes = uploadedBytes ; for ( UploadFile file : params . files ) { totalBytes += file . length ( service ) ; } } | Calculates the total bytes of this upload task . This the sum of all the lengths of the successfully uploaded files and also the pending ones . |
23,997 | private void makeDirectories ( String dirPath , String permissions ) throws IOException { if ( ! dirPath . contains ( "/" ) ) return ; String [ ] pathElements = dirPath . split ( "/" ) ; if ( pathElements . length == 1 ) return ; int lastElement = dirPath . endsWith ( "/" ) ? pathElements . length : pathElements . length - 1 ; for ( int i = 0 ; i < lastElement ; i ++ ) { String singleDir = pathElements [ i ] ; if ( singleDir . isEmpty ( ) ) continue ; if ( ! ftpClient . changeWorkingDirectory ( singleDir ) ) { if ( ftpClient . makeDirectory ( singleDir ) ) { Logger . debug ( LOG_TAG , "Created remote directory: " + singleDir ) ; if ( permissions != null ) { setPermission ( singleDir , permissions ) ; } ftpClient . changeWorkingDirectory ( singleDir ) ; } else { throw new IOException ( "Unable to create remote directory: " + singleDir ) ; } } } } | Creates a nested directory structure on a FTP server and enters into it . |
23,998 | private String getRemoteFileName ( UploadFile file ) { if ( file . getProperty ( PARAM_REMOTE_PATH ) . endsWith ( "/" ) ) { return file . getName ( service ) ; } if ( file . getProperty ( PARAM_REMOTE_PATH ) . contains ( "/" ) ) { String [ ] tmp = file . getProperty ( PARAM_REMOTE_PATH ) . split ( "/" ) ; return tmp [ tmp . length - 1 ] ; } return file . getProperty ( PARAM_REMOTE_PATH ) ; } | Checks if the remote file path contains also the remote file name . If it s not specified the name of the local file will be used . |
23,999 | public FTPUploadRequest setUsernameAndPassword ( String username , String password ) { if ( username == null || "" . equals ( username ) ) { throw new IllegalArgumentException ( "Specify FTP account username!" ) ; } if ( password == null || "" . equals ( password ) ) { throw new IllegalArgumentException ( "Specify FTP account password!" ) ; } ftpParams . username = username ; ftpParams . password = password ; return this ; } | Set the credentials used to login on the FTP Server . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.