idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
29,500
protected void setDefaultInfoWindowLocation ( ) { int s = mOriginalPoints . size ( ) ; if ( s > 0 ) mInfoWindowLocation = mOriginalPoints . get ( s / 2 ) ; else mInfoWindowLocation = new GeoPoint ( 0.0 , 0.0 ) ; }
Internal method used to ensure that the infowindow will have a default position in all cases so that the user can call showInfoWindow even if no tap occured before . Currently set the position on the middle point of the polyline .
29,501
public void onDetach ( ) { this . getOverlayManager ( ) . onDetach ( this ) ; mTileProvider . detach ( ) ; mOldZoomController . setVisible ( false ) ; if ( mZoomController != null ) { mZoomController . onDetach ( ) ; } if ( mTileRequestCompleteHandler instanceof SimpleInvalidationHandler ) { ( ( SimpleInvalidationHandler ) mTileRequestCompleteHandler ) . destroy ( ) ; } mTileRequestCompleteHandler = null ; if ( mProjection != null ) mProjection . detach ( ) ; mProjection = null ; mRepository . onDetach ( ) ; mListners . clear ( ) ; }
destroys the map view all references to listeners all overlays etc
29,502
private static boolean parallelSideEffect ( final double pXA , final double pYA , final double pXB , final double pYB , final double pXC , final double pYC , final double pXD , final double pYD , final PointL pIntersection ) { if ( pXA == pXB ) { return parallelSideEffectSameX ( pXA , pYA , pXB , pYB , pXC , pYC , pXD , pYD , pIntersection ) ; } if ( pXC == pXD ) { return parallelSideEffectSameX ( pXC , pYC , pXD , pYD , pXA , pYA , pXB , pYB , pIntersection ) ; } final double k1 = ( pYB - pYA ) / ( pXB - pXA ) ; final double k2 = ( pYD - pYC ) / ( pXD - pXC ) ; if ( k1 != k2 ) { return false ; } final double b1 = pYA - k1 * pXA ; final double b2 = pYC - k2 * pXC ; if ( b1 != b2 ) { return false ; } final double xi = middle ( pXA , pXB , pXC , pXD ) ; final double yi = middle ( pYA , pYB , pYC , pYD ) ; return check ( pXA , pYA , pXB , pYB , pXC , pYC , pXD , pYD , pIntersection , xi , yi ) ; }
When the segments are parallels and overlap the middle of the overlap is considered as the intersection
29,503
private static boolean check ( final double pXA , final double pYA , final double pXB , final double pYB , final double pXC , final double pYC , final double pXD , final double pYD , final PointL pIntersection , final double pXI , final double pYI ) { if ( pXI < Math . min ( pXA , pXB ) || pXI > Math . max ( pXA , pXB ) ) { return false ; } if ( pXI < Math . min ( pXC , pXD ) || pXI > Math . max ( pXC , pXD ) ) { return false ; } if ( pYI < Math . min ( pYA , pYB ) || pYI > Math . max ( pYA , pYB ) ) { return false ; } if ( pYI < Math . min ( pYC , pYD ) || pYI > Math . max ( pYC , pYD ) ) { return false ; } if ( pIntersection != null ) { pIntersection . x = Math . round ( pXI ) ; pIntersection . y = Math . round ( pYI ) ; } return true ; }
Checks if computed intersection is valid and sets output accordingly
29,504
private static boolean divisionByZeroSideEffect ( final double pXA , final double pYA , final double pXB , final double pYB , final double pXC , final double pYC , final double pXD , final double pYD , final PointL pIntersection ) { return divisionByZeroSideEffectX ( pXA , pYA , pXB , pYB , pXC , pYC , pXD , pYD , pIntersection ) || divisionByZeroSideEffectX ( pXC , pYC , pXD , pYD , pXA , pYA , pXB , pYB , pIntersection ) || divisionByZeroSideEffectY ( pXA , pYA , pXB , pYB , pXC , pYC , pXD , pYD , pIntersection ) || divisionByZeroSideEffectY ( pXC , pYC , pXD , pYD , pXA , pYA , pXB , pYB , pIntersection ) ; }
Main intersection formula works only without division by zero
29,505
public boolean onSingleTapConfirmed ( final MotionEvent event , final MapView mapView ) { return ( activateSelectedItems ( event , mapView , new ActiveItem ( ) { public boolean run ( final int index ) { final ItemizedIconOverlay < Item > that = ItemizedIconOverlay . this ; if ( that . mOnItemGestureListener == null ) { return false ; } return onSingleTapUpHelper ( index , that . mItemList . get ( index ) , mapView ) ; } } ) ) ? true : super . onSingleTapConfirmed ( event , mapView ) ; }
Each of these methods performs a item sensitive check . If the item is located its corresponding method is called . The result of the call is returned .
29,506
private boolean activateSelectedItems ( final MotionEvent event , final MapView mapView , final ActiveItem task ) { final int eventX = Math . round ( event . getX ( ) ) ; final int eventY = Math . round ( event . getY ( ) ) ; for ( int i = 0 ; i < this . mItemList . size ( ) ; ++ i ) { if ( isEventOnItem ( getItem ( i ) , eventX , eventY , mapView ) ) { if ( task . run ( i ) ) { return true ; } } } return false ; }
When a content sensitive action is performed the content item needs to be identified . This method does that and then performs the assigned task on that item .
29,507
public void garbageCollection ( ) { int toBeRemoved = Integer . MAX_VALUE ; final int size = mCachedTiles . size ( ) ; if ( ! mStressedMemory ) { toBeRemoved = size - mCapacity ; if ( toBeRemoved <= 0 ) { return ; } } refreshAdditionalLists ( ) ; if ( mAutoEnsureCapacity ) { final int target = mMapTileArea . size ( ) + mAdditionalMapTileList . size ( ) ; if ( ensureCapacity ( target ) ) { if ( ! mStressedMemory ) { toBeRemoved = size - mCapacity ; if ( toBeRemoved <= 0 ) { return ; } } } } populateSyncCachedTiles ( mGC ) ; for ( int i = 0 ; i < mGC . getSize ( ) ; i ++ ) { final long index = mGC . get ( i ) ; if ( shouldKeepTile ( index ) ) { continue ; } remove ( index ) ; if ( -- toBeRemoved == 0 ) { break ; } ; } }
Removes from the memory cache all the tiles that should no longer be there
29,508
private void populateSyncCachedTiles ( final MapTileList pList ) { synchronized ( mCachedTiles ) { pList . ensureCapacity ( mCachedTiles . size ( ) ) ; pList . clear ( ) ; for ( final long index : mCachedTiles . keySet ( ) ) { pList . put ( index ) ; } } }
Just a helper method in order to parse all indices without concurrency side effects
29,509
public boolean startOrientationProvider ( IOrientationConsumer orientationConsumer ) { mOrientationConsumer = orientationConsumer ; boolean result = false ; final Sensor sensor = mSensorManager . getDefaultSensor ( Sensor . TYPE_ORIENTATION ) ; if ( sensor != null ) { result = mSensorManager . registerListener ( this , sensor , SensorManager . SENSOR_DELAY_UI ) ; } return result ; }
Enable orientation updates from the internal compass sensor and show the compass .
29,510
public void draw ( Canvas canvas , Projection pj ) { if ( mIcon == null ) return ; if ( mPosition == null ) return ; pj . toPixels ( mPosition , mPositionPixels ) ; int width = mIcon . getIntrinsicWidth ( ) ; int height = mIcon . getIntrinsicHeight ( ) ; Rect rect = new Rect ( 0 , 0 , width , height ) ; rect . offset ( - ( int ) ( mAnchorU * width ) , - ( int ) ( mAnchorV * height ) ) ; mIcon . setBounds ( rect ) ; mIcon . setAlpha ( ( int ) ( mAlpha * 255 ) ) ; float rotationOnScreen = ( mFlat ? - mBearing : pj . getOrientation ( ) - mBearing ) ; drawAt ( canvas , mIcon , mPositionPixels . x , mPositionPixels . y , false , rotationOnScreen ) ; }
Draw the icon .
29,511
public double getX01FromLongitude ( double longitude , boolean wrapEnabled ) { longitude = wrapEnabled ? Clip ( longitude , getMinLongitude ( ) , getMaxLongitude ( ) ) : longitude ; final double result = getX01FromLongitude ( longitude ) ; return wrapEnabled ? Clip ( result , 0 , 1 ) : result ; }
Converts a longitude to its X01 value id est a double between 0 and 1 for the whole longitude range
29,512
public double getY01FromLatitude ( double latitude , boolean wrapEnabled ) { latitude = wrapEnabled ? Clip ( latitude , getMinLatitude ( ) , getMaxLatitude ( ) ) : latitude ; final double result = getY01FromLatitude ( latitude ) ; return wrapEnabled ? Clip ( result , 0 , 1 ) : result ; }
Converts a latitude to its Y01 value id est a double between 0 and 1 for the whole latitude range
29,513
public void open ( Object object , GeoPoint position , int offsetX , int offsetY ) { close ( ) ; mRelatedObject = object ; mPosition = position ; mOffsetX = offsetX ; mOffsetY = offsetY ; onOpen ( object ) ; MapView . LayoutParams lp = new MapView . LayoutParams ( MapView . LayoutParams . WRAP_CONTENT , MapView . LayoutParams . WRAP_CONTENT , mPosition , MapView . LayoutParams . BOTTOM_CENTER , mOffsetX , mOffsetY ) ; if ( mMapView != null && mView != null ) { mMapView . addView ( mView , lp ) ; mIsVisible = true ; } else { Log . w ( IMapView . LOGTAG , "Error trapped, InfoWindow.open mMapView: " + ( mMapView == null ? "null" : "ok" ) + " mView: " + ( mView == null ? "null" : "ok" ) ) ; } }
open the InfoWindow at the specified GeoPosition + offset . If it was already opened close it before reopening .
29,514
public void close ( ) { if ( mIsVisible ) { mIsVisible = false ; ( ( ViewGroup ) mView . getParent ( ) ) . removeView ( mView ) ; onClose ( ) ; } }
hides the info window which triggers another render of the map
29,515
public void onDetach ( ) { close ( ) ; if ( mView != null ) mView . setTag ( null ) ; mView = null ; mMapView = null ; if ( Configuration . getInstance ( ) . isDebugMode ( ) ) Log . d ( IMapView . LOGTAG , "Marked detached" ) ; }
this destroys the window and all references to views
29,516
public static void closeAllInfoWindowsOn ( MapView mapView ) { ArrayList < InfoWindow > opened = getOpenedInfoWindowsOn ( mapView ) ; for ( InfoWindow infoWindow : opened ) { infoWindow . close ( ) ; } }
close all InfoWindows currently opened on this MapView
29,517
public static ArrayList < InfoWindow > getOpenedInfoWindowsOn ( MapView mapView ) { int count = mapView . getChildCount ( ) ; ArrayList < InfoWindow > opened = new ArrayList < InfoWindow > ( count ) ; for ( int i = 0 ; i < count ; i ++ ) { final View child = mapView . getChildAt ( i ) ; Object tag = child . getTag ( ) ; if ( tag != null && tag instanceof InfoWindow ) { InfoWindow infoWindow = ( InfoWindow ) tag ; opened . add ( infoWindow ) ; } } return opened ; }
return all InfoWindows currently opened on this MapView
29,518
private MilestoneManager getHalfKilometerManager ( ) { final Path arrowPath = new Path ( ) ; arrowPath . moveTo ( - 5 , - 5 ) ; arrowPath . lineTo ( 5 , 0 ) ; arrowPath . lineTo ( - 5 , 5 ) ; arrowPath . close ( ) ; final Paint backgroundPaint = getFillPaint ( COLOR_BACKGROUND ) ; return new MilestoneManager ( new MilestoneMeterDistanceLister ( 500 ) , new MilestonePathDisplayer ( 0 , true , arrowPath , backgroundPaint ) { protected void draw ( final Canvas pCanvas , final Object pParameter ) { final int halfKilometers = ( int ) Math . round ( ( ( double ) pParameter / 500 ) ) ; if ( halfKilometers % 2 == 0 ) { return ; } super . draw ( pCanvas , pParameter ) ; } } ) ; }
Half - kilometer milestones
29,519
public Point toWgs84 ( Point point ) { if ( projection != null ) { point = toWgs84 . transform ( point ) ; } return point ; }
Transform a projection point to WGS84
29,520
public Point toProjection ( Point point ) { if ( projection != null ) { point = fromWgs84 . transform ( point ) ; } return point ; }
Transform a WGS84 point to the projection
29,521
public static Polyline addPolylineToMap ( MapView map , Polyline polyline ) { if ( polyline . getInfoWindow ( ) == null ) polyline . setInfoWindow ( new BasicInfoWindow ( R . layout . bonuspack_bubble , map ) ) ; map . getOverlayManager ( ) . add ( polyline ) ; return polyline ; }
Add a Polyline to the map
29,522
public synchronized void close ( ) throws IOException { if ( journalWriter == null ) { return ; } for ( Entry entry : new ArrayList < Entry > ( lruEntries . values ( ) ) ) { if ( entry . currentEditor != null ) { entry . currentEditor . abort ( ) ; } } trimToSize ( ) ; journalWriter . close ( ) ; journalWriter = null ; }
Closes this cache . Stored values will remain on the filesystem .
29,523
protected boolean isSOFnMarker ( int marker ) { if ( marker <= 0xC3 && marker >= 0xC0 ) { return true ; } if ( marker <= 0xCB && marker >= 0xC5 ) { return true ; } if ( marker <= 0xCF && marker >= 0xCD ) { return true ; } return false ; }
can opt using array
29,524
protected void writeFull ( ) { byte [ ] imageData = rawImage . getData ( ) ; int numOfComponents = frameHeader . getNf ( ) ; int [ ] pixes = new int [ numOfComponents * DCTSIZE2 ] ; int blockIndex = 0 ; int startCoordinate = 0 , scanlineStride = numOfComponents * rawImage . getWidth ( ) , row = 0 ; x = 0 ; y = 0 ; for ( int m = 0 ; m < MCUsPerColumn * MCUsPerRow ; m ++ ) { blockIndex = 0 ; for ( int v = 0 ; v < maxVSampleFactor ; v ++ ) { for ( int h = 0 ; h < maxHSampleFactor ; h ++ ) { row = y + 1 ; startCoordinate = ( y * rawImage . getWidth ( ) + x ) * numOfComponents ; for ( int k = blockIndex * DCTSIZE2 , i = 0 ; k < blockIndex * DCTSIZE2 + DCTSIZE2 ; k ++ ) { pixes [ i ++ ] = allMCUDatas [ 0 ] [ m ] [ k ] ; if ( numOfComponents > 1 ) { pixes [ i ++ ] = allMCUDatas [ 1 ] [ m ] [ k ] ; pixes [ i ++ ] = allMCUDatas [ 2 ] [ m ] [ k ] ; } if ( numOfComponents > 3 ) { pixes [ i ++ ] = allMCUDatas [ 3 ] [ m ] [ k ] ; } x ++ ; if ( x % 8 == 0 ) { y ++ ; x -= 8 ; } } colorConvertor . convertBlock ( pixes , 0 , imageData , numOfComponents , startCoordinate , row , scanlineStride ) ; blockIndex ++ ; x += 8 ; y -= 8 ; } x -= maxHSampleFactor * 8 ; y += 8 ; } x += maxHSampleFactor * 8 ; y -= maxVSampleFactor * 8 ; if ( x >= rawImage . getWidth ( ) ) { x = 0 ; y += maxVSampleFactor * 8 ; } } }
Used by progressive mode
29,525
public int getValueId ( Clusterable c ) { currentItems ++ ; int index = TreeUtils . findNearestNodeIndex ( subNodes , c ) ; if ( index >= 0 ) { KMeansTreeNode node = subNodes . get ( index ) ; return node . getValueId ( c ) ; } return id ; }
Adds a clusterable to the current vocab tree for word creation
29,526
public static Node cloneNode ( Node node ) { if ( node == null ) { return null ; } IIOMetadataNode newNode = new IIOMetadataNode ( node . getNodeName ( ) ) ; if ( node instanceof IIOMetadataNode ) { IIOMetadataNode iioNode = ( IIOMetadataNode ) node ; Object obj = iioNode . getUserObject ( ) ; if ( obj instanceof byte [ ] ) { byte [ ] copyBytes = ( ( byte [ ] ) obj ) . clone ( ) ; newNode . setUserObject ( copyBytes ) ; } } NamedNodeMap attrs = node . getAttributes ( ) ; for ( int i = 0 ; i < attrs . getLength ( ) ; i ++ ) { Node attr = attrs . item ( i ) ; newNode . setAttribute ( attr . getNodeName ( ) , attr . getNodeValue ( ) ) ; } NodeList children = node . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { Node child = children . item ( i ) ; newNode . appendChild ( cloneNode ( child ) ) ; } return newNode ; }
Currently only use by GIFStreamMetadata and GIFImageMetadata
29,527
protected Cluster [ ] calculateInitialClusters ( List < ? extends Clusterable > values , int numClusters ) { Cluster [ ] clusters = new Cluster [ numClusters ] ; Random random = new Random ( 1 ) ; Set < Integer > clusterCenters = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < numClusters ; i ++ ) { int index = random . nextInt ( values . size ( ) ) ; while ( clusterCenters . contains ( index ) ) { index = random . nextInt ( values . size ( ) ) ; } clusterCenters . add ( index ) ; clusters [ i ] = new Cluster ( values . get ( index ) . getLocation ( ) , i ) ; } return clusters ; }
Calculates the initial clusters randomly this could be replaced with a better algorithm
29,528
public float [ ] getClusterMean ( ) { float [ ] normedCurrentLocation = new float [ mCurrentMeanLocation . length ] ; for ( int i = 0 ; i < mCurrentMeanLocation . length ; i ++ ) { normedCurrentLocation [ i ] = mCurrentMeanLocation [ i ] / ( ( float ) mClusterItems . size ( ) ) ; } return normedCurrentLocation ; }
Get the current mean value of the cluster s items
29,529
private void setItem ( int index , Timepoint time ) { time = roundToValidTime ( time , index ) ; mCurrentTime = time ; reselectSelector ( time , false , index ) ; }
Set either the hour the minute or the second . Will set the internal value and set the selection .
29,530
private boolean isHourInnerCircle ( int hourOfDay ) { boolean isMorning = hourOfDay <= 12 && hourOfDay != 0 ; if ( mController . getVersion ( ) != TimePickerDialog . Version . VERSION_1 ) isMorning = ! isMorning ; return mIs24HourMode && isMorning ; }
Check if a given hour appears in the outer circle or the inner circle
29,531
private int getCurrentlyShowingValue ( ) { int currentIndex = getCurrentItemShowing ( ) ; switch ( currentIndex ) { case HOUR_INDEX : return mCurrentTime . getHour ( ) ; case MINUTE_INDEX : return mCurrentTime . getMinute ( ) ; case SECOND_INDEX : return mCurrentTime . getSecond ( ) ; default : return - 1 ; } }
If the hours are showing return the current hour . If the minutes are showing return the current minute .
29,532
private Timepoint roundToValidTime ( Timepoint newSelection , int currentItemShowing ) { switch ( currentItemShowing ) { case HOUR_INDEX : return mController . roundToNearest ( newSelection , null ) ; case MINUTE_INDEX : return mController . roundToNearest ( newSelection , Timepoint . TYPE . HOUR ) ; default : return mController . roundToNearest ( newSelection , Timepoint . TYPE . MINUTE ) ; } }
Snap the input to a selectable value
29,533
public boolean trySettingInputEnabled ( boolean inputEnabled ) { if ( mDoingTouch && ! inputEnabled ) { return false ; } mInputEnabled = inputEnabled ; mGrayBox . setVisibility ( inputEnabled ? View . INVISIBLE : View . VISIBLE ) ; return true ; }
Set touch input as enabled or disabled for use with keyboard mode .
29,534
public static ObjectAnimator getPulseAnimator ( View labelToAnimate , float decreaseRatio , float increaseRatio ) { Keyframe k0 = Keyframe . ofFloat ( 0f , 1f ) ; Keyframe k1 = Keyframe . ofFloat ( 0.275f , decreaseRatio ) ; Keyframe k2 = Keyframe . ofFloat ( 0.69f , increaseRatio ) ; Keyframe k3 = Keyframe . ofFloat ( 1f , 1f ) ; PropertyValuesHolder scaleX = PropertyValuesHolder . ofKeyframe ( "scaleX" , k0 , k1 , k2 , k3 ) ; PropertyValuesHolder scaleY = PropertyValuesHolder . ofKeyframe ( "scaleY" , k0 , k1 , k2 , k3 ) ; ObjectAnimator pulseAnimator = ObjectAnimator . ofPropertyValuesHolder ( labelToAnimate , scaleX , scaleY ) ; pulseAnimator . setDuration ( PULSE_ANIMATOR_DURATION ) ; return pulseAnimator ; }
Render an animator to pulsate a view in place .
29,535
public static Calendar trimToMidnight ( Calendar calendar ) { calendar . set ( Calendar . HOUR_OF_DAY , 0 ) ; calendar . set ( Calendar . MINUTE , 0 ) ; calendar . set ( Calendar . SECOND , 0 ) ; calendar . set ( Calendar . MILLISECOND , 0 ) ; return calendar ; }
Trims off all time information effectively setting it to midnight Makes it easier to compare at just the day level
29,536
@ SuppressWarnings ( "unused" ) public static DatePickerDialog newInstance ( OnDateSetListener callback ) { Calendar now = Calendar . getInstance ( ) ; return DatePickerDialog . newInstance ( callback , now ) ; }
Create a new DatePickerDialog instance initialised to the current system date .
29,537
@ SuppressWarnings ( "unused" ) public void setHighlightedDays ( Calendar [ ] highlightedDays ) { for ( Calendar highlightedDay : highlightedDays ) { this . highlightedDays . add ( Utils . trimToMidnight ( ( Calendar ) highlightedDay . clone ( ) ) ) ; } if ( mDayPickerView != null ) mDayPickerView . onChange ( ) ; }
Sets an array of dates which should be highlighted when the picker is drawn
29,538
@ SuppressWarnings ( "DeprecatedIsStillUsed" ) public void setTimeZone ( TimeZone timeZone ) { mTimezone = timeZone ; mCalendar . setTimeZone ( timeZone ) ; YEAR_FORMAT . setTimeZone ( timeZone ) ; MONTH_FORMAT . setTimeZone ( timeZone ) ; DAY_FORMAT . setTimeZone ( timeZone ) ; }
Set which timezone the picker should use
29,539
public void setLocale ( Locale locale ) { mLocale = locale ; mWeekStart = Calendar . getInstance ( mTimezone , mLocale ) . getFirstDayOfWeek ( ) ; YEAR_FORMAT = new SimpleDateFormat ( "yyyy" , locale ) ; MONTH_FORMAT = new SimpleDateFormat ( "MMM" , locale ) ; DAY_FORMAT = new SimpleDateFormat ( "dd" , locale ) ; }
Set a custom locale to be used when generating various strings in the picker
29,540
public void start ( ) { if ( hasVibratePermission ( mContext ) ) { mVibrator = ( Vibrator ) mContext . getSystemService ( Service . VIBRATOR_SERVICE ) ; } mIsGloballyEnabled = checkGlobalSetting ( mContext ) ; Uri uri = Settings . System . getUriFor ( Settings . System . HAPTIC_FEEDBACK_ENABLED ) ; mContext . getContentResolver ( ) . registerContentObserver ( uri , false , mContentObserver ) ; }
Call to setup the controller .
29,541
private boolean hasVibratePermission ( Context context ) { PackageManager pm = context . getPackageManager ( ) ; int hasPerm = pm . checkPermission ( android . Manifest . permission . VIBRATE , context . getPackageName ( ) ) ; return hasPerm == PackageManager . PERMISSION_GRANTED ; }
Method to verify that vibrate permission has been granted .
29,542
@ SuppressWarnings ( "SameParameterValue" ) public static TimePickerDialog newInstance ( OnTimeSetListener callback , int hourOfDay , int minute , int second , boolean is24HourMode ) { TimePickerDialog ret = new TimePickerDialog ( ) ; ret . initialize ( callback , hourOfDay , minute , second , is24HourMode ) ; return ret ; }
Create a new TimePickerDialog instance with a given intial selection
29,543
public static TimePickerDialog newInstance ( OnTimeSetListener callback , int hourOfDay , int minute , boolean is24HourMode ) { return TimePickerDialog . newInstance ( callback , hourOfDay , minute , 0 , is24HourMode ) ; }
Create a new TimePickerDialog instance with a given initial selection
29,544
@ SuppressWarnings ( { "unused" , "SameParameterValue" } ) public static TimePickerDialog newInstance ( OnTimeSetListener callback , boolean is24HourMode ) { Calendar now = Calendar . getInstance ( ) ; return TimePickerDialog . newInstance ( callback , now . get ( Calendar . HOUR_OF_DAY ) , now . get ( Calendar . MINUTE ) , is24HourMode ) ; }
Create a new TimePickerDialog instance initialized to the current system time
29,545
private boolean processKeyUp ( int keyCode ) { if ( keyCode == KeyEvent . KEYCODE_TAB ) { if ( mInKbMode ) { if ( isTypedTimeFullyLegal ( ) ) { finishKbMode ( true ) ; } return true ; } } else if ( keyCode == KeyEvent . KEYCODE_ENTER ) { if ( mInKbMode ) { if ( ! isTypedTimeFullyLegal ( ) ) { return true ; } finishKbMode ( false ) ; } if ( mCallback != null ) { mCallback . onTimeSet ( this , mTimePicker . getHours ( ) , mTimePicker . getMinutes ( ) , mTimePicker . getSeconds ( ) ) ; } dismiss ( ) ; return true ; } else if ( keyCode == KeyEvent . KEYCODE_DEL ) { if ( mInKbMode ) { if ( ! mTypedTimes . isEmpty ( ) ) { int deleted = deleteLastTypedKey ( ) ; String deletedKeyStr ; if ( deleted == getAmOrPmKeyCode ( AM ) ) { deletedKeyStr = mAmText ; } else if ( deleted == getAmOrPmKeyCode ( PM ) ) { deletedKeyStr = mPmText ; } else { deletedKeyStr = String . format ( mLocale , "%d" , getValFromKeyCode ( deleted ) ) ; } Utils . tryAccessibilityAnnounce ( mTimePicker , String . format ( mDeletedKeyFormat , deletedKeyStr ) ) ; updateDisplay ( true ) ; } } } else if ( keyCode == KeyEvent . KEYCODE_0 || keyCode == KeyEvent . KEYCODE_1 || keyCode == KeyEvent . KEYCODE_2 || keyCode == KeyEvent . KEYCODE_3 || keyCode == KeyEvent . KEYCODE_4 || keyCode == KeyEvent . KEYCODE_5 || keyCode == KeyEvent . KEYCODE_6 || keyCode == KeyEvent . KEYCODE_7 || keyCode == KeyEvent . KEYCODE_8 || keyCode == KeyEvent . KEYCODE_9 || ( ! mIs24HourMode && ( keyCode == getAmOrPmKeyCode ( AM ) || keyCode == getAmOrPmKeyCode ( PM ) ) ) ) { if ( ! mInKbMode ) { if ( mTimePicker == null ) { Log . e ( TAG , "Unable to initiate keyboard mode, TimePicker was null." ) ; return true ; } mTypedTimes . clear ( ) ; tryStartingKbMode ( keyCode ) ; return true ; } if ( addKeyIfLegal ( keyCode ) ) { updateDisplay ( false ) ; } return true ; } return false ; }
For keyboard mode processes key events .
29,546
public void setMonthParams ( int selectedDay , int year , int month , int weekStart ) { if ( month == - 1 && year == - 1 ) { throw new InvalidParameterException ( "You must specify month and year for this view" ) ; } mSelectedDay = selectedDay ; mMonth = month ; mYear = year ; final Calendar today = Calendar . getInstance ( mController . getTimeZone ( ) , mController . getLocale ( ) ) ; mHasToday = false ; mToday = - 1 ; mCalendar . set ( Calendar . MONTH , mMonth ) ; mCalendar . set ( Calendar . YEAR , mYear ) ; mCalendar . set ( Calendar . DAY_OF_MONTH , 1 ) ; mDayOfWeekStart = mCalendar . get ( Calendar . DAY_OF_WEEK ) ; if ( weekStart != - 1 ) { mWeekStart = weekStart ; } else { mWeekStart = mCalendar . getFirstDayOfWeek ( ) ; } mNumCells = mCalendar . getActualMaximum ( Calendar . DAY_OF_MONTH ) ; for ( int i = 0 ; i < mNumCells ; i ++ ) { final int day = i + 1 ; if ( sameDay ( day , today ) ) { mHasToday = true ; mToday = day ; } } mNumRows = calculateNumRows ( ) ; mTouchHelper . invalidateRoot ( ) ; }
Sets all the parameters for displaying this week . The only required parameter is the week number . Other parameters have a default value and will only update if a new value is included except for focus month which will always default to no focus month if no value is passed in .
29,547
public int getDayFromLocation ( float x , float y ) { final int day = getInternalDayFromLocation ( x , y ) ; if ( day < 1 || day > mNumCells ) { return - 1 ; } return day ; }
Calculates the day that the given x position is in accounting for week number . Returns the day or - 1 if the position wasn t in a day .
29,548
protected int getInternalDayFromLocation ( float x , float y ) { int dayStart = mEdgePadding ; if ( x < dayStart || x > mWidth - mEdgePadding ) { return - 1 ; } int row = ( int ) ( y - getMonthHeaderSize ( ) ) / mRowHeight ; int column = ( int ) ( ( x - dayStart ) * mNumDays / ( mWidth - dayStart - mEdgePadding ) ) ; int day = column - findDayOffset ( ) + 1 ; day += row * mNumDays ; return day ; }
Calculates the day that the given x position is in accounting for week number .
29,549
private String getWeekDayLabel ( Calendar day ) { Locale locale = mController . getLocale ( ) ; if ( Build . VERSION . SDK_INT < 18 ) { String dayName = new SimpleDateFormat ( "E" , locale ) . format ( day . getTime ( ) ) ; String dayLabel = dayName . toUpperCase ( locale ) . substring ( 0 , 1 ) ; if ( locale . equals ( Locale . CHINA ) || locale . equals ( Locale . CHINESE ) || locale . equals ( Locale . SIMPLIFIED_CHINESE ) || locale . equals ( Locale . TRADITIONAL_CHINESE ) ) { int len = dayName . length ( ) ; dayLabel = dayName . substring ( len - 1 , len ) ; } if ( locale . getLanguage ( ) . equals ( "he" ) || locale . getLanguage ( ) . equals ( "iw" ) ) { if ( mDayLabelCalendar . get ( Calendar . DAY_OF_WEEK ) != Calendar . SATURDAY ) { int len = dayName . length ( ) ; dayLabel = dayName . substring ( len - 2 , len - 1 ) ; } else { dayLabel = dayName . toUpperCase ( locale ) . substring ( 0 , 1 ) ; } } if ( locale . getLanguage ( ) . equals ( "ca" ) ) dayLabel = dayName . toLowerCase ( ) . substring ( 0 , 2 ) ; if ( locale . getLanguage ( ) . equals ( "es" ) && day . get ( Calendar . DAY_OF_WEEK ) == Calendar . WEDNESDAY ) dayLabel = "X" ; return dayLabel ; } if ( weekDayLabelFormatter == null ) { weekDayLabelFormatter = new SimpleDateFormat ( "EEEEE" , locale ) ; } return weekDayLabelFormatter . format ( day . getTime ( ) ) ; }
Return a 1 or 2 letter String for use as a weekday label
29,550
private void calculateGridSizes ( float numbersRadius , float xCenter , float yCenter , float textSize , float [ ] textGridHeights , float [ ] textGridWidths ) { float offset1 = numbersRadius ; float offset2 = numbersRadius * ( ( float ) Math . sqrt ( 3 ) ) / 2f ; float offset3 = numbersRadius / 2f ; mPaint . setTextSize ( textSize ) ; mSelectedPaint . setTextSize ( textSize ) ; mInactivePaint . setTextSize ( textSize ) ; yCenter -= ( mPaint . descent ( ) + mPaint . ascent ( ) ) / 2 ; textGridHeights [ 0 ] = yCenter - offset1 ; textGridWidths [ 0 ] = xCenter - offset1 ; textGridHeights [ 1 ] = yCenter - offset2 ; textGridWidths [ 1 ] = xCenter - offset2 ; textGridHeights [ 2 ] = yCenter - offset3 ; textGridWidths [ 2 ] = xCenter - offset3 ; textGridHeights [ 3 ] = yCenter ; textGridWidths [ 3 ] = xCenter ; textGridHeights [ 4 ] = yCenter + offset3 ; textGridWidths [ 4 ] = xCenter + offset3 ; textGridHeights [ 5 ] = yCenter + offset2 ; textGridWidths [ 5 ] = xCenter + offset2 ; textGridHeights [ 6 ] = yCenter + offset1 ; textGridWidths [ 6 ] = xCenter + offset1 ; }
Using the trigonometric Unit Circle calculate the positions that the text will need to be drawn at based on the specified circle radius . Place the values in the textGridHeights and textGridWidths parameters .
29,551
private void drawTexts ( Canvas canvas , float textSize , Typeface typeface , String [ ] texts , float [ ] textGridWidths , float [ ] textGridHeights ) { mPaint . setTextSize ( textSize ) ; mPaint . setTypeface ( typeface ) ; Paint [ ] textPaints = assignTextColors ( texts ) ; canvas . drawText ( texts [ 0 ] , textGridWidths [ 3 ] , textGridHeights [ 0 ] , textPaints [ 0 ] ) ; canvas . drawText ( texts [ 1 ] , textGridWidths [ 4 ] , textGridHeights [ 1 ] , textPaints [ 1 ] ) ; canvas . drawText ( texts [ 2 ] , textGridWidths [ 5 ] , textGridHeights [ 2 ] , textPaints [ 2 ] ) ; canvas . drawText ( texts [ 3 ] , textGridWidths [ 6 ] , textGridHeights [ 3 ] , textPaints [ 3 ] ) ; canvas . drawText ( texts [ 4 ] , textGridWidths [ 5 ] , textGridHeights [ 4 ] , textPaints [ 4 ] ) ; canvas . drawText ( texts [ 5 ] , textGridWidths [ 4 ] , textGridHeights [ 5 ] , textPaints [ 5 ] ) ; canvas . drawText ( texts [ 6 ] , textGridWidths [ 3 ] , textGridHeights [ 6 ] , textPaints [ 6 ] ) ; canvas . drawText ( texts [ 7 ] , textGridWidths [ 2 ] , textGridHeights [ 5 ] , textPaints [ 7 ] ) ; canvas . drawText ( texts [ 8 ] , textGridWidths [ 1 ] , textGridHeights [ 4 ] , textPaints [ 8 ] ) ; canvas . drawText ( texts [ 9 ] , textGridWidths [ 0 ] , textGridHeights [ 3 ] , textPaints [ 9 ] ) ; canvas . drawText ( texts [ 10 ] , textGridWidths [ 1 ] , textGridHeights [ 2 ] , textPaints [ 10 ] ) ; canvas . drawText ( texts [ 11 ] , textGridWidths [ 2 ] , textGridHeights [ 1 ] , textPaints [ 11 ] ) ; }
Draw the 12 text values at the positions specified by the textGrid parameters .
29,552
public void setSelection ( int selectionDegrees , boolean isInnerCircle , boolean forceDrawDot ) { mSelectionDegrees = selectionDegrees ; mSelectionRadians = selectionDegrees * Math . PI / 180 ; mForceDrawDot = forceDrawDot ; if ( mHasInnerCircle ) { if ( isInnerCircle ) { mNumbersRadiusMultiplier = mInnerNumbersRadiusMultiplier ; } else { mNumbersRadiusMultiplier = mOuterNumbersRadiusMultiplier ; } } }
Set the selection .
29,553
protected void setUpRecyclerView ( DatePickerDialog . ScrollOrientation scrollOrientation ) { setVerticalScrollBarEnabled ( false ) ; setFadingEdgeLength ( 0 ) ; int gravity = scrollOrientation == DatePickerDialog . ScrollOrientation . VERTICAL ? Gravity . TOP : Gravity . START ; GravitySnapHelper helper = new GravitySnapHelper ( gravity , position -> { if ( pageListener != null ) pageListener . onPageChanged ( position ) ; } ) ; helper . attachToRecyclerView ( this ) ; }
Sets all the required fields for the list view . Override this method to set a different list view behavior .
29,554
public boolean dispatchPopulateAccessibilityEvent ( AccessibilityEvent event ) { if ( event . getEventType ( ) == AccessibilityEvent . TYPE_WINDOW_STATE_CHANGED ) { event . getText ( ) . clear ( ) ; int flags = DateUtils . FORMAT_SHOW_DATE | DateUtils . FORMAT_SHOW_YEAR | DateUtils . FORMAT_SHOW_WEEKDAY ; String dateString = DateUtils . formatDateTime ( getContext ( ) , mDateMillis , flags ) ; event . getText ( ) . add ( dateString ) ; return true ; } return super . dispatchPopulateAccessibilityEvent ( event ) ; }
Announce the currently - selected date when launched .
29,555
public int getIsTouchingAmOrPm ( float xCoord , float yCoord ) { if ( ! mDrawValuesReady ) { return - 1 ; } int squaredYDistance = ( int ) ( ( yCoord - mAmPmYCenter ) * ( yCoord - mAmPmYCenter ) ) ; int distanceToAmCenter = ( int ) Math . sqrt ( ( xCoord - mAmXCenter ) * ( xCoord - mAmXCenter ) + squaredYDistance ) ; if ( distanceToAmCenter <= mAmPmCircleRadius && ! mAmDisabled ) { return AM ; } int distanceToPmCenter = ( int ) Math . sqrt ( ( xCoord - mPmXCenter ) * ( xCoord - mPmXCenter ) + squaredYDistance ) ; if ( distanceToPmCenter <= mAmPmCircleRadius && ! mPmDisabled ) { return PM ; } return - 1 ; }
Calculate whether the coordinates are touching the AM or PM circle .
29,556
public void setExcludeFilter ( File filterFile ) { if ( filterFile != null && filterFile . length ( ) > 0 ) { excludeFile = filterFile ; } else { if ( filterFile != null ) { log ( "Warning: exclude filter file " + filterFile + ( filterFile . exists ( ) ? " is empty" : " does not exist" ) ) ; } excludeFile = null ; } }
Set the exclude filter file
29,557
public void setIncludeFilter ( File filterFile ) { if ( filterFile != null && filterFile . length ( ) > 0 ) { includeFile = filterFile ; } else { if ( filterFile != null ) { log ( "Warning: include filter file " + filterFile + ( filterFile . exists ( ) ? " is empty" : " does not exist" ) ) ; } includeFile = null ; } }
Set the include filter file
29,558
public void setBaselineBugs ( File baselineBugs ) { if ( baselineBugs != null && baselineBugs . length ( ) > 0 ) { this . baselineBugs = baselineBugs ; } else { if ( baselineBugs != null ) { log ( "Warning: baseline bugs file " + baselineBugs + ( baselineBugs . exists ( ) ? " is empty" : " does not exist" ) ) ; } this . baselineBugs = null ; } }
Set the baseline bugs file
29,559
public void setAuxClasspath ( Path src ) { boolean nonEmpty = false ; String [ ] elementList = src . list ( ) ; for ( String anElementList : elementList ) { if ( ! "" . equals ( anElementList ) ) { nonEmpty = true ; break ; } } if ( nonEmpty ) { if ( auxClasspath == null ) { auxClasspath = src ; } else { auxClasspath . append ( src ) ; } } }
the auxclasspath to use .
29,560
public void setAuxClasspathRef ( Reference r ) { Path path = createAuxClasspath ( ) ; path . setRefid ( r ) ; path . toString ( ) ; }
Adds a reference to a sourcepath defined elsewhere .
29,561
public void setAuxAnalyzepath ( Path src ) { boolean nonEmpty = false ; String [ ] elementList = src . list ( ) ; for ( String anElementList : elementList ) { if ( ! "" . equals ( anElementList ) ) { nonEmpty = true ; break ; } } if ( nonEmpty ) { if ( auxAnalyzepath == null ) { auxAnalyzepath = src ; } else { auxAnalyzepath . append ( src ) ; } } }
the auxAnalyzepath to use .
29,562
public void setSourcePath ( Path src ) { if ( sourcePath == null ) { sourcePath = src ; } else { sourcePath . append ( src ) ; } }
the sourcepath to use .
29,563
public void setExcludePath ( Path src ) { if ( excludePath == null ) { excludePath = src ; } else { excludePath . append ( src ) ; } }
the excludepath to use .
29,564
public void setIncludePath ( Path src ) { if ( includePath == null ) { includePath = src ; } else { includePath . append ( src ) ; } }
the includepath to use .
29,565
protected void checkParameters ( ) { super . checkParameters ( ) ; if ( projectFile == null && classLocations . size ( ) == 0 && filesets . size ( ) == 0 && dirsets . size ( ) == 0 && auxAnalyzepath == null ) { throw new BuildException ( "either projectfile, <class/>, <fileset/> or <auxAnalyzepath/> child " + "elements must be defined for task <" + getTaskName ( ) + "/>" , getLocation ( ) ) ; } if ( outputFormat != null && ! ( "xml" . equalsIgnoreCase ( outputFormat . trim ( ) ) || "xml:withMessages" . equalsIgnoreCase ( outputFormat . trim ( ) ) || "html" . equalsIgnoreCase ( outputFormat . trim ( ) ) || "text" . equalsIgnoreCase ( outputFormat . trim ( ) ) || "xdocs" . equalsIgnoreCase ( outputFormat . trim ( ) ) || "emacs" . equalsIgnoreCase ( outputFormat . trim ( ) ) ) ) { throw new BuildException ( "output attribute must be either " + "'text', 'xml', 'html', 'xdocs' or 'emacs' for task <" + getTaskName ( ) + "/>" , getLocation ( ) ) ; } if ( reportLevel != null && ! ( "experimental" . equalsIgnoreCase ( reportLevel . trim ( ) ) || "low" . equalsIgnoreCase ( reportLevel . trim ( ) ) || "medium" . equalsIgnoreCase ( reportLevel . trim ( ) ) || "high" . equalsIgnoreCase ( reportLevel . trim ( ) ) ) ) { throw new BuildException ( "reportlevel attribute must be either " + "'experimental' or 'low' or 'medium' or 'high' for task <" + getTaskName ( ) + "/>" , getLocation ( ) ) ; } List < String > efforts = Arrays . asList ( "min" , "less" , "default" , "more" , "max" ) ; if ( effort != null && ! efforts . contains ( effort ) ) { throw new BuildException ( "effort attribute must be one of " + efforts ) ; } }
Check that all required attributes have been set
29,566
static boolean isEclipsePluginDisabled ( String pluginId , Map < URI , Plugin > allPlugins ) { for ( Plugin plugin : allPlugins . values ( ) ) { if ( pluginId . equals ( plugin . getPluginId ( ) ) ) { return false ; } } return true ; }
Eclipse plugin can be disabled ONLY by user so it must NOT be in the list of loaded plugins
29,567
public static < Fact , AnalysisType extends BasicAbstractDataflowAnalysis < Fact > > void printCFG ( Dataflow < Fact , AnalysisType > dataflow , PrintStream out ) { DataflowCFGPrinter < Fact , AnalysisType > printer = new DataflowCFGPrinter < > ( dataflow ) ; printer . print ( out ) ; }
Print CFG annotated with results from given dataflow analysis .
29,568
private void fillMenu ( ) { isBugItem = new MenuItem ( menu , SWT . RADIO ) ; isBugItem . setText ( "Bug" ) ; notBugItem = new MenuItem ( menu , SWT . RADIO ) ; notBugItem . setText ( "Not Bug" ) ; isBugItem . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { if ( bugInstance != null ) { classifyWarning ( bugInstance , true ) ; } } } ) ; notBugItem . addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { if ( bugInstance != null ) { classifyWarning ( bugInstance , false ) ; } } } ) ; menu . addMenuListener ( new MenuAdapter ( ) { public void menuShown ( MenuEvent e ) { if ( DEBUG ) { System . out . println ( "Synchronizing menu!" ) ; } syncMenu ( ) ; } } ) ; }
Fill the classification menu .
29,569
private void syncMenu ( ) { if ( bugInstance != null ) { isBugItem . setEnabled ( true ) ; notBugItem . setEnabled ( true ) ; BugProperty isBugProperty = bugInstance . lookupProperty ( BugProperty . IS_BUG ) ; if ( isBugProperty == null ) { isBugItem . setSelection ( false ) ; notBugItem . setSelection ( false ) ; } else { boolean isBug = isBugProperty . getValueAsBoolean ( ) ; isBugItem . setSelection ( isBug ) ; notBugItem . setSelection ( ! isBug ) ; } } else { if ( DEBUG ) { System . out . println ( "No bug instance found, disabling menu items" ) ; } isBugItem . setEnabled ( false ) ; notBugItem . setEnabled ( false ) ; isBugItem . setSelection ( false ) ; notBugItem . setSelection ( false ) ; } }
Update menu to match currently selected BugInstance .
29,570
public PatternMatcher execute ( ) throws DataflowAnalysisException { workList . addLast ( cfg . getEntry ( ) ) ; while ( ! workList . isEmpty ( ) ) { BasicBlock basicBlock = workList . removeLast ( ) ; visitedBlockMap . put ( basicBlock , basicBlock ) ; BasicBlock . InstructionIterator i = basicBlock . instructionIterator ( ) ; while ( i . hasNext ( ) ) { attemptMatch ( basicBlock , i . duplicate ( ) ) ; i . next ( ) ; } Iterator < BasicBlock > succIterator = cfg . successorIterator ( basicBlock ) ; while ( succIterator . hasNext ( ) ) { BasicBlock succ = succIterator . next ( ) ; if ( visitedBlockMap . get ( succ ) == null ) { workList . addLast ( succ ) ; } } } return this ; }
Search for examples of the ByteCodePattern .
29,571
private void attemptMatch ( BasicBlock basicBlock , BasicBlock . InstructionIterator instructionIterator ) throws DataflowAnalysisException { work ( new State ( basicBlock , instructionIterator , pattern . getFirst ( ) ) ) ; }
Attempt to begin a match .
29,572
public static final String getString ( Type type ) { if ( type instanceof GenericObjectType ) { return ( ( GenericObjectType ) type ) . toString ( true ) ; } else if ( type instanceof ArrayType ) { return TypeCategory . asString ( ( ArrayType ) type ) ; } else { return type . toString ( ) ; } }
Get String representation of a Type including Generic information
29,573
private boolean askToSave ( ) { if ( mainFrame . isProjectChanged ( ) ) { int response = JOptionPane . showConfirmDialog ( mainFrame , L10N . getLocalString ( "dlg.save_current_changes" , "The current project has been changed, Save current changes?" ) , L10N . getLocalString ( "dlg.save_changes" , "Save Changes?" ) , JOptionPane . YES_NO_CANCEL_OPTION , JOptionPane . WARNING_MESSAGE ) ; if ( response == JOptionPane . YES_OPTION ) { if ( mainFrame . getSaveFile ( ) != null ) { save ( ) ; } else { saveAs ( ) ; } } else if ( response == JOptionPane . CANCEL_OPTION ) { return true ; } } return false ; }
Returns true if cancelled
29,574
SaveReturn saveAnalysis ( final File f ) { Future < Object > waiter = mainFrame . getBackgroundExecutor ( ) . submit ( ( ) -> { BugSaver . saveBugs ( f , mainFrame . getBugCollection ( ) , mainFrame . getProject ( ) ) ; return null ; } ) ; try { waiter . get ( ) ; } catch ( InterruptedException e ) { return SaveReturn . SAVE_ERROR ; } catch ( ExecutionException e ) { return SaveReturn . SAVE_ERROR ; } mainFrame . setProjectChanged ( false ) ; return SaveReturn . SAVE_SUCCESSFUL ; }
Save current analysis as file passed in . Return SAVE_SUCCESSFUL if save successful . Method doesn t do much . This method is more if need to do other things in the future for saving analysis . And to keep saving naming convention .
29,575
public String getClassPath ( ) { StringBuilder buf = new StringBuilder ( ) ; for ( Entry entry : entryList ) { if ( buf . length ( ) > 0 ) { buf . append ( File . pathSeparator ) ; } buf . append ( entry . getURL ( ) ) ; } return buf . toString ( ) ; }
Return the classpath string .
29,576
private InputStream getInputStreamForResource ( String resourceName ) { for ( Entry entry : entryList ) { InputStream in ; try { in = entry . openStream ( resourceName ) ; if ( in != null ) { if ( URLClassPathRepository . DEBUG ) { System . out . println ( "\t==> found " + resourceName + " in " + entry . getURL ( ) ) ; } return in ; } } catch ( IOException ignore ) { } } if ( URLClassPathRepository . DEBUG ) { System . out . println ( "\t==> could not find " + resourceName + " on classpath" ) ; } return null ; }
Open a stream to read given resource .
29,577
public JavaClass lookupClass ( String className ) throws ClassNotFoundException { if ( classesThatCantBeFound . contains ( className ) ) { throw new ClassNotFoundException ( "Error while looking for class " + className + ": class not found" ) ; } String resourceName = className . replace ( '.' , '/' ) + ".class" ; InputStream in = null ; boolean parsedClass = false ; try { in = getInputStreamForResource ( resourceName ) ; if ( in == null ) { classesThatCantBeFound . add ( className ) ; throw new ClassNotFoundException ( "Error while looking for class " + className + ": class not found" ) ; } ClassParser classParser = new ClassParser ( in , resourceName ) ; JavaClass javaClass = classParser . parse ( ) ; parsedClass = true ; return javaClass ; } catch ( IOException e ) { classesThatCantBeFound . add ( className ) ; throw new ClassNotFoundException ( "IOException while looking for class " + className , e ) ; } finally { if ( in != null && ! parsedClass ) { try { in . close ( ) ; } catch ( IOException ignore ) { } } } }
Look up a class from the classpath .
29,578
public static String getURLProtocol ( String urlString ) { String protocol = null ; int firstColon = urlString . indexOf ( ':' ) ; if ( firstColon >= 0 ) { String specifiedProtocol = urlString . substring ( 0 , firstColon ) ; if ( FindBugs . knownURLProtocolSet . contains ( specifiedProtocol ) ) { protocol = specifiedProtocol ; } } return protocol ; }
Get the URL protocol of given URL string .
29,579
public static String getFileExtension ( String fileName ) { int lastDot = fileName . lastIndexOf ( '.' ) ; return ( lastDot >= 0 ) ? fileName . substring ( lastDot ) : null ; }
Get the file extension of given fileName .
29,580
public void killLoadsOfField ( XField field ) { if ( ! REDUNDANT_LOAD_ELIMINATION ) { return ; } HashSet < AvailableLoad > killMe = new HashSet < > ( ) ; for ( AvailableLoad availableLoad : getAvailableLoadMap ( ) . keySet ( ) ) { if ( availableLoad . getField ( ) . equals ( field ) ) { if ( RLE_DEBUG ) { System . out . println ( "KILLING Load of " + availableLoad + " in " + this ) ; } killMe . add ( availableLoad ) ; } } killAvailableLoads ( killMe ) ; }
Kill all loads of given field .
29,581
public void addMeta ( char meta , String replacement ) { metaCharacterSet . set ( meta ) ; replacementMap . put ( new String ( new char [ ] { meta } ) , replacement ) ; }
Add a metacharacter and its replacement .
29,582
public static String getResourceString ( String key ) { ResourceBundle bundle = FindbugsPlugin . getDefault ( ) . getResourceBundle ( ) ; try { return bundle . getString ( key ) ; } catch ( MissingResourceException e ) { return key ; } }
Returns the string from the plugin s resource bundle or key if not found .
29,583
public static String getFindBugsEnginePluginLocation ( ) { URL u = plugin . getBundle ( ) . getEntry ( "/" ) ; try { URL bundleRoot = FileLocator . resolve ( u ) ; String path = bundleRoot . getPath ( ) ; if ( FindBugsBuilder . DEBUG ) { System . out . println ( "Pluginpath: " + path ) ; } if ( path . endsWith ( "/eclipsePlugin/" ) ) { File f = new File ( path ) ; f = f . getParentFile ( ) ; f = new File ( f , "findbugs" ) ; path = f . getPath ( ) + "/" ; } return path ; } catch ( IOException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "IO Exception locating engine plugin" ) ; } return null ; }
Find the filesystem path of the FindBugs plugin directory .
29,584
public void logException ( Throwable e , String message ) { logMessage ( IStatus . ERROR , message , e ) ; }
Log an exception .
29,585
public static IPath getBugCollectionFile ( IProject project ) { IPath path = getDefault ( ) . getStateLocation ( ) ; return path . append ( project . getName ( ) + ".fbwarnings.xml" ) ; }
Get the file resource used to store findbugs warnings for a project .
29,586
public static SortedBugCollection getBugCollection ( IProject project , IProgressMonitor monitor ) throws CoreException { SortedBugCollection bugCollection = ( SortedBugCollection ) project . getSessionProperty ( SESSION_PROPERTY_BUG_COLLECTION ) ; if ( bugCollection == null ) { try { readBugCollectionAndProject ( project , monitor ) ; bugCollection = ( SortedBugCollection ) project . getSessionProperty ( SESSION_PROPERTY_BUG_COLLECTION ) ; } catch ( IOException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Could not read bug collection for project" ) ; bugCollection = createDefaultEmptyBugCollection ( project ) ; } catch ( DocumentException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Could not read bug collection for project" ) ; bugCollection = createDefaultEmptyBugCollection ( project ) ; } } return bugCollection ; }
Get the stored BugCollection for project . If there is no stored bug collection for the project or if an error occurs reading the stored bug collection a default empty collection is created and returned .
29,587
private static void readBugCollectionAndProject ( IProject project , IProgressMonitor monitor ) throws IOException , DocumentException , CoreException { SortedBugCollection bugCollection ; IPath bugCollectionPath = getBugCollectionFile ( project ) ; File bugCollectionFile = bugCollectionPath . toFile ( ) ; if ( ! bugCollectionFile . exists ( ) ) { getDefault ( ) . logInfo ( "creating new bug collection: " + bugCollectionPath . toOSString ( ) ) ; createDefaultEmptyBugCollection ( project ) ; return ; } UserPreferences prefs = getUserPreferences ( project ) ; bugCollection = new SortedBugCollection ( ) ; bugCollection . getProject ( ) . setGuiCallback ( new EclipseGuiCallback ( project ) ) ; bugCollection . readXML ( bugCollectionFile ) ; cacheBugCollectionAndProject ( project , bugCollection , bugCollection . getProject ( ) ) ; }
Read saved bug collection and findbugs project from file . Will populate the bug collection and findbugs project session properties if successful . If there is no saved bug collection and project for the eclipse project then FileNotFoundException will be thrown .
29,588
public static void storeBugCollection ( IProject project , final SortedBugCollection bugCollection , IProgressMonitor monitor ) throws IOException , CoreException { project . setSessionProperty ( SESSION_PROPERTY_BUG_COLLECTION , bugCollection ) ; if ( bugCollection != null ) { writeBugCollection ( project , bugCollection , monitor ) ; } }
Store a new bug collection for a project . The collection is stored in the session and also in a file in the project .
29,589
public static void saveCurrentBugCollection ( IProject project , IProgressMonitor monitor ) throws CoreException { if ( isBugCollectionDirty ( project ) ) { SortedBugCollection bugCollection = ( SortedBugCollection ) project . getSessionProperty ( SESSION_PROPERTY_BUG_COLLECTION ) ; if ( bugCollection != null ) { writeBugCollection ( project , bugCollection , monitor ) ; } } }
If necessary save current bug collection for project to disk .
29,590
public static UserPreferences getProjectPreferences ( IProject project , boolean forceRead ) { try { UserPreferences prefs = ( UserPreferences ) project . getSessionProperty ( SESSION_PROPERTY_USERPREFS ) ; if ( prefs == null || forceRead ) { prefs = readUserPreferences ( project ) ; if ( prefs == null ) { prefs = getWorkspacePreferences ( ) . clone ( ) ; } project . setSessionProperty ( SESSION_PROPERTY_USERPREFS , prefs ) ; } return prefs ; } catch ( CoreException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Error getting SpotBugs preferences for project" ) ; return getWorkspacePreferences ( ) . clone ( ) ; } }
Get project own preferences set .
29,591
public static void saveUserPreferences ( IProject project , final UserPreferences userPrefs ) throws CoreException { FileOutput userPrefsOutput = new FileOutput ( ) { public void writeFile ( OutputStream os ) throws IOException { userPrefs . write ( os ) ; } public String getTaskDescription ( ) { return "writing user preferences" ; } } ; if ( project != null ) { project . setSessionProperty ( SESSION_PROPERTY_USERPREFS , userPrefs ) ; IFile userPrefsFile = getUserPreferencesFile ( project ) ; ensureReadWrite ( userPrefsFile ) ; IO . writeFile ( userPrefsFile , userPrefsOutput , null ) ; if ( project . getFile ( DEPRECATED_PREFS_PATH ) . equals ( userPrefsFile ) ) { String message = "Found old style FindBugs preferences for project '" + project . getName ( ) + "'. This preferences are not at the default location: '" + DEFAULT_PREFS_PATH + "'." + " Please move '" + DEPRECATED_PREFS_PATH + "' to '" + DEFAULT_PREFS_PATH + "'." ; getDefault ( ) . logWarning ( message ) ; } } else { ByteArrayOutputStream bos = new ByteArrayOutputStream ( 10000 ) ; try { userPrefs . write ( bos ) ; } catch ( IOException e ) { getDefault ( ) . logException ( e , "Failed to write user preferences" ) ; return ; } Properties props = new Properties ( ) ; try { props . load ( new ByteArrayInputStream ( bos . toByteArray ( ) ) ) ; } catch ( IOException e ) { getDefault ( ) . logException ( e , "Failed to save user preferences" ) ; return ; } IPreferenceStore store = getDefault ( ) . getPreferenceStore ( ) ; resetStore ( store , UserPreferences . KEY_PLUGIN ) ; resetStore ( store , UserPreferences . KEY_EXCLUDE_BUGS ) ; resetStore ( store , UserPreferences . KEY_EXCLUDE_FILTER ) ; resetStore ( store , UserPreferences . KEY_INCLUDE_FILTER ) ; for ( Entry < Object , Object > entry : props . entrySet ( ) ) { store . putValue ( ( String ) entry . getKey ( ) , ( String ) entry . getValue ( ) ) ; } if ( store instanceof IPersistentPreferenceStore ) { IPersistentPreferenceStore store2 = ( IPersistentPreferenceStore ) store ; try { store2 . save ( ) ; } catch ( IOException e ) { getDefault ( ) . logException ( e , "Failed to save user preferences" ) ; } } } }
Save current UserPreferences for given project or workspace .
29,592
private static void resetStore ( IPreferenceStore store , String prefix ) { int start = 0 ; while ( start < 99 ) { String name = prefix + start ; if ( store . contains ( name ) ) { store . setToDefault ( name ) ; } else { break ; } start ++ ; } }
Removes all consequent enumerated keys from given store staring with given prefix
29,593
private static void ensureReadWrite ( IFile file ) throws CoreException { if ( file . isReadOnly ( ) ) { IStatus checkOutStatus = ResourcesPlugin . getWorkspace ( ) . validateEdit ( new IFile [ ] { file } , null ) ; if ( ! checkOutStatus . isOK ( ) ) { throw new CoreException ( checkOutStatus ) ; } } }
Ensure that a file is writable . If not currently writable check it as so that we can edit it .
29,594
private static UserPreferences readUserPreferences ( IProject project ) throws CoreException { IFile userPrefsFile = getUserPreferencesFile ( project ) ; if ( ! userPrefsFile . exists ( ) ) { return null ; } try { InputStream in = userPrefsFile . getContents ( true ) ; UserPreferences userPrefs = FindBugsPreferenceInitializer . createDefaultUserPreferences ( ) ; userPrefs . read ( in ) ; return userPrefs ; } catch ( IOException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Could not read user preferences for project" ) ; return null ; } }
Read UserPreferences for project from the file in the project directory . Returns null if the preferences have not been saved to a file or if there is an error reading the preferences file .
29,595
public RecursiveFileSearch search ( ) throws InterruptedException { File baseFile = new File ( baseDir ) ; String basePath = bestEffortCanonicalPath ( baseFile ) ; directoryWorkList . add ( baseFile ) ; directoriesScanned . add ( basePath ) ; directoriesScannedList . add ( basePath ) ; while ( ! directoryWorkList . isEmpty ( ) ) { File dir = directoryWorkList . removeFirst ( ) ; if ( ! dir . isDirectory ( ) ) { continue ; } File [ ] contentList = dir . listFiles ( ) ; if ( contentList == null ) { continue ; } for ( File aContentList : contentList ) { if ( Thread . interrupted ( ) ) { throw new InterruptedException ( ) ; } File file = aContentList ; if ( ! fileFilter . accept ( file ) ) { continue ; } if ( file . isDirectory ( ) ) { String myPath = bestEffortCanonicalPath ( file ) ; if ( myPath . startsWith ( basePath ) && directoriesScanned . add ( myPath ) ) { directoriesScannedList . add ( myPath ) ; directoryWorkList . add ( file ) ; } } else { resultList . add ( file . getPath ( ) ) ; } } } return this ; }
Perform the search .
29,596
public static MethodDescriptor getMethodDescriptor ( JavaClass jclass , Method method ) { return DescriptorFactory . instance ( ) . getMethodDescriptor ( jclass . getClassName ( ) . replace ( '.' , '/' ) , method . getName ( ) , method . getSignature ( ) , method . isStatic ( ) ) ; }
Construct a MethodDescriptor from JavaClass and method .
29,597
public static ClassDescriptor getClassDescriptor ( JavaClass jclass ) { return DescriptorFactory . instance ( ) . getClassDescriptor ( ClassName . toSlashedClassName ( jclass . getClassName ( ) ) ) ; }
Construct a ClassDescriptor from a JavaClass .
29,598
public static boolean preTiger ( JavaClass jclass ) { return jclass . getMajor ( ) < JDK15_MAJOR || ( jclass . getMajor ( ) == JDK15_MAJOR && jclass . getMinor ( ) < JDK15_MINOR ) ; }
Checks if classfile was compiled for pre 1 . 5 target
29,599
public void addBugCategory ( BugCategory bugCategory ) { BugCategory old = bugCategories . get ( bugCategory . getCategory ( ) ) ; if ( old != null ) { throw new IllegalArgumentException ( "Category already exists" ) ; } bugCategories . put ( bugCategory . getCategory ( ) , bugCategory ) ; }
Add a BugCategory reported by the Plugin .