code
stringlengths
73
34.1k
label
stringclasses
1 value
@Override 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); }
java
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; }
java
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; }
java
public void open(Object object, GeoPoint position, int offsetX, int offsetY) { close(); //if it was already opened 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")); } }
java
public void close() { if (mIsVisible) { mIsVisible = false; ((ViewGroup) mView.getParent()).removeView(mView); onClose(); } }
java
public void onDetach() { close(); if (mView != null) mView.setTag(null); mView = null; mMapView = null; if (Configuration.getInstance().isDebugMode()) Log.d(IMapView.LOGTAG, "Marked detached"); }
java
public static void closeAllInfoWindowsOn(MapView mapView) { ArrayList<InfoWindow> opened = getOpenedInfoWindowsOn(mapView); for (InfoWindow infoWindow : opened) { infoWindow.close(); } }
java
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; }
java
private MilestoneManager getHalfKilometerManager() { final Path arrowPath = new Path(); // a simple arrow towards the right arrowPath.moveTo(-5, -5); arrowPath.lineTo(5, 0); arrowPath.lineTo(-5, 5); arrowPath.close(); final Paint backgroundPaint = getFillPaint(COLOR_BACKGROUND); return new MilestoneManager( // display an arrow at 500m every 1km new MilestoneMeterDistanceLister(500), new MilestonePathDisplayer(0, true, arrowPath, backgroundPaint) { @Override 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); } } ); }
java
public Point toWgs84(Point point) { if (projection != null) { point = toWgs84.transform(point); } return point; }
java
public Point toProjection(Point point) { if (projection != null) { point = fromWgs84.transform(point); } return point; }
java
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; }
java
public synchronized void close() throws IOException { if (journalWriter == null) { return; // Already closed. } for (Entry entry : new ArrayList<Entry>(lruEntries.values())) { if (entry.currentEditor != null) { entry.currentEditor.abort(); } } trimToSize(); journalWriter.close(); journalWriter = null; }
java
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; }
java
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; // one MCU for (int v = 0; v < maxVSampleFactor; v++) { for (int h = 0; h < maxHSampleFactor; h++) { row = y + 1; startCoordinate = (y * rawImage.getWidth() + x) * numOfComponents; // one block 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; } } }
java
public int getValueId(Clusterable c) { currentItems++; /* * if(isLeafNode()) { return id; } */ int index = TreeUtils.findNearestNodeIndex(subNodes, c); if (index >= 0) { KMeansTreeNode node = subNodes.get(index); return node.getValueId(c); } return id; }
java
public static Node cloneNode(Node node) { if(node == null) { return null; } IIOMetadataNode newNode = new IIOMetadataNode(node.getNodeName()); //clone user object if(node instanceof IIOMetadataNode) { IIOMetadataNode iioNode = (IIOMetadataNode)node; Object obj = iioNode.getUserObject(); if(obj instanceof byte[]) { byte[] copyBytes = ((byte[])obj).clone(); newNode.setUserObject(copyBytes); } } //clone attributes NamedNodeMap attrs = node.getAttributes(); for(int i = 0; i < attrs.getLength(); i++ ) { Node attr = attrs.item(i); newNode.setAttribute(attr.getNodeName(), attr.getNodeValue()); } //clone children NodeList children = node.getChildNodes(); for(int i = 0; i < children.getLength(); i++) { Node child = children.item(i); newNode.appendChild(cloneNode(child)); } return newNode; }
java
protected Cluster[] calculateInitialClusters(List<? extends Clusterable> values, int numClusters){ Cluster[] clusters = new Cluster[numClusters]; //choose centers and create the initial clusters 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; }
java
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; }
java
private void setItem(int index, Timepoint time) { time = roundToValidTime(time, index); mCurrentTime = time; reselectSelector(time, false, index); }
java
private boolean isHourInnerCircle(int hourOfDay) { // We'll have the 00 hours on the outside circle. boolean isMorning = hourOfDay <= 12 && hourOfDay != 0; // In the version 2 layout the circles are swapped if (mController.getVersion() != TimePickerDialog.Version.VERSION_1) isMorning = !isMorning; return mIs24HourMode && isMorning; }
java
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; } }
java
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); } }
java
public boolean trySettingInputEnabled(boolean inputEnabled) { if (mDoingTouch && !inputEnabled) { // If we're trying to disable input, but we're in the middle of a touch event, // we'll allow the touch event to continue before disabling input. return false; } mInputEnabled = inputEnabled; mGrayBox.setVisibility(inputEnabled? View.INVISIBLE : View.VISIBLE); return true; }
java
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; }
java
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; }
java
@SuppressWarnings("unused") public static DatePickerDialog newInstance(OnDateSetListener callback) { Calendar now = Calendar.getInstance(); return DatePickerDialog.newInstance(callback, now); }
java
@SuppressWarnings("unused") public void setHighlightedDays(Calendar[] highlightedDays) { for (Calendar highlightedDay : highlightedDays) { this.highlightedDays.add(Utils.trimToMidnight((Calendar) highlightedDay.clone())); } if (mDayPickerView != null) mDayPickerView.onChange(); }
java
@SuppressWarnings("DeprecatedIsStillUsed") @Deprecated public void setTimeZone(TimeZone timeZone) { mTimezone = timeZone; mCalendar.setTimeZone(timeZone); YEAR_FORMAT.setTimeZone(timeZone); MONTH_FORMAT.setTimeZone(timeZone); DAY_FORMAT.setTimeZone(timeZone); }
java
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); }
java
public void start() { if (hasVibratePermission(mContext)) { mVibrator = (Vibrator) mContext.getSystemService(Service.VIBRATOR_SERVICE); } // Setup a listener for changes in haptic feedback settings mIsGloballyEnabled = checkGlobalSetting(mContext); Uri uri = Settings.System.getUriFor(Settings.System.HAPTIC_FEEDBACK_ENABLED); mContext.getContentResolver().registerContentObserver(uri, false, mContentObserver); }
java
private boolean hasVibratePermission(Context context) { PackageManager pm = context.getPackageManager(); int hasPerm = pm.checkPermission(android.Manifest.permission.VIBRATE, context.getPackageName()); return hasPerm == PackageManager.PERMISSION_GRANTED; }
java
@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; }
java
public static TimePickerDialog newInstance(OnTimeSetListener callback, int hourOfDay, int minute, boolean is24HourMode) { return TimePickerDialog.newInstance(callback, hourOfDay, minute, 0, is24HourMode); }
java
@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); }
java
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) { // Something's wrong, because time picker should definitely not be null. Log.e(TAG, "Unable to initiate keyboard mode, TimePicker was null."); return true; } mTypedTimes.clear(); tryStartingKbMode(keyCode); return true; } // We're already in keyboard mode. if (addKeyIfLegal(keyCode)) { updateDisplay(false); } return true; } return false; }
java
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; // Allocate space for caching the day numbers and focus values mMonth = month; mYear = year; // Figure out what day today is //final Time today = new Time(Time.getCurrentTimezone()); //today.setToNow(); 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(); // Invalidate cached accessibility information. mTouchHelper.invalidateRoot(); }
java
public int getDayFromLocation(float x, float y) { final int day = getInternalDayFromLocation(x, y); if (day < 1 || day > mNumCells) { return -1; } return day; }
java
protected int getInternalDayFromLocation(float x, float y) { int dayStart = mEdgePadding; if (x < dayStart || x > mWidth - mEdgePadding) { return -1; } // Selection is (x - start) / (pixels/day) == (x -s) * day / pixels 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; }
java
private String getWeekDayLabel(Calendar day) { Locale locale = mController.getLocale(); // Localised short version of the string is not available on API < 18 if (Build.VERSION.SDK_INT < 18) { String dayName = new SimpleDateFormat("E", locale).format(day.getTime()); String dayLabel = dayName.toUpperCase(locale).substring(0, 1); // Chinese labels should be fetched right to left 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); } // Most hebrew labels should select the second to last character 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 { // I know this is duplication, but it makes the code easier to grok by // having all hebrew code in the same block dayLabel = dayName.toUpperCase(locale).substring(0, 1); } } // Catalan labels should be two digits in lowercase if (locale.getLanguage().equals("ca")) dayLabel = dayName.toLowerCase().substring(0, 2); // Correct single character label in Spanish is X if (locale.getLanguage().equals("es") && day.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY) dayLabel = "X"; return dayLabel; } // Getting the short label is a one liner on API >= 18 if (weekDayLabelFormatter == null) { weekDayLabelFormatter = new SimpleDateFormat("EEEEE", locale); } return weekDayLabelFormatter.format(day.getTime()); }
java
private void calculateGridSizes(float numbersRadius, float xCenter, float yCenter, float textSize, float[] textGridHeights, float[] textGridWidths) { /* * The numbers need to be drawn in a 7x7 grid, representing the points on the Unit Circle. */ float offset1 = numbersRadius; // cos(30) = a / r => r * cos(30) = a => r * √3/2 = a float offset2 = numbersRadius * ((float) Math.sqrt(3)) / 2f; // sin(30) = o / r => r * sin(30) = o => r / 2 = a float offset3 = numbersRadius / 2f; mPaint.setTextSize(textSize); mSelectedPaint.setTextSize(textSize); mInactivePaint.setTextSize(textSize); // We'll need yTextBase to be slightly lower to account for the text's baseline. 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; }
java
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]); }
java
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; } } }
java
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 -> { // Leverage the fact that the SnapHelper figures out which position is shown and // pass this on to our PageListener after the snap has happened if (pageListener != null) pageListener.onPageChanged(position); }); helper.attachToRecyclerView(this); }
java
@Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { // Clear the event's current text so that only the current date will be spoken. 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); }
java
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; } // Neither was close enough. return -1; }
java
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; } }
java
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; } }
java
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; } }
java
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); } } }
java
public void setAuxClasspathRef(Reference r) { Path path = createAuxClasspath(); path.setRefid(r); path.toString(); // Evaluated for its side-effects (throwing a // BuildException) }
java
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); } } }
java
public void setSourcePath(Path src) { if (sourcePath == null) { sourcePath = src; } else { sourcePath.append(src); } }
java
public void setExcludePath(Path src) { if (excludePath == null) { excludePath = src; } else { excludePath.append(src); } }
java
public void setIncludePath(Path src) { if (includePath == null) { includePath = src; } else { includePath.append(src); } }
java
@Override 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()); } // FindBugs allows both, so there's no apparent reason for this check // if ( excludeFile != null && includeFile != null ) { // throw new BuildException("only one of excludeFile and includeFile " + // " attributes may be used in 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); } }
java
static boolean isEclipsePluginDisabled(String pluginId, Map<URI, Plugin> allPlugins) { for (Plugin plugin : allPlugins.values()) { if(pluginId.equals(plugin.getPluginId())) { return false; } } return true; }
java
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); }
java
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() { /* * (non-Javadoc) * * @see * org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse * .swt.events.SelectionEvent) */ @Override public void widgetSelected(SelectionEvent e) { if (bugInstance != null) { classifyWarning(bugInstance, true); } } }); notBugItem.addSelectionListener(new SelectionAdapter() { /* * (non-Javadoc) * * @see * org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse * .swt.events.SelectionEvent) */ @Override public void widgetSelected(SelectionEvent e) { if (bugInstance != null) { classifyWarning(bugInstance, false); } } }); menu.addMenuListener(new MenuAdapter() { @Override public void menuShown(MenuEvent e) { // Before showing the menu, sync its contents // with the current BugInstance (if any) if (DEBUG) { System.out.println("Synchronizing menu!"); } syncMenu(); } }); }
java
private void syncMenu() { if (bugInstance != null) { isBugItem.setEnabled(true); notBugItem.setEnabled(true); BugProperty isBugProperty = bugInstance.lookupProperty(BugProperty.IS_BUG); if (isBugProperty == null) { // Unclassified isBugItem.setSelection(false); notBugItem.setSelection(false); } else { boolean isBug = isBugProperty.getValueAsBoolean(); isBugItem.setSelection(isBug); notBugItem.setSelection(!isBug); } } else { // No bug instance, so uncheck and disable the menu items if (DEBUG) { System.out.println("No bug instance found, disabling menu items"); } isBugItem.setEnabled(false); notBugItem.setEnabled(false); isBugItem.setSelection(false); notBugItem.setSelection(false); } }
java
public PatternMatcher execute() throws DataflowAnalysisException { workList.addLast(cfg.getEntry()); while (!workList.isEmpty()) { BasicBlock basicBlock = workList.removeLast(); visitedBlockMap.put(basicBlock, basicBlock); // Scan instructions of basic block for possible matches BasicBlock.InstructionIterator i = basicBlock.instructionIterator(); while (i.hasNext()) { attemptMatch(basicBlock, i.duplicate()); i.next(); } // Add successors of the basic block (which haven't been visited // already) Iterator<BasicBlock> succIterator = cfg.successorIterator(basicBlock); while (succIterator.hasNext()) { BasicBlock succ = succIterator.next(); if (visitedBlockMap.get(succ) == null) { workList.addLast(succ); } } } return this; }
java
private void attemptMatch(BasicBlock basicBlock, BasicBlock.InstructionIterator instructionIterator) throws DataflowAnalysisException { work(new State(basicBlock, instructionIterator, pattern.getFirst())); }
java
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(); } }
java
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; // IF no, do nothing. } } return false; }
java
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; }
java
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(); }
java
private InputStream getInputStreamForResource(String resourceName) { // Try each classpath entry, in order, until we find one // that has the resource. Catch and ignore IOExceptions. // FIXME: The following code should throw IOException. // // URL.openStream() does not seem to distinguish // whether the resource does not exist, vs. some // transient error occurring while trying to access it. // This is unfortunate, because we really should throw // an exception out of this method in the latter case, // since it means our knowledge of the classpath is // incomplete. // // Short of reimplementing HTTP, etc., ourselves, // there is probably nothing we can do about this problem. 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) { // Ignore } } if (URLClassPathRepository.DEBUG) { System.out.println("\t==> could not find " + resourceName + " on classpath"); } return null; }
java
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) { // Ignore } } } }
java
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; }
java
public static String getFileExtension(String fileName) { int lastDot = fileName.lastIndexOf('.'); return (lastDot >= 0) ? fileName.substring(lastDot) : null; }
java
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); }
java
public void addMeta(char meta, String replacement) { metaCharacterSet.set(meta); replacementMap.put(new String(new char[] { meta }), replacement); }
java
public static String getResourceString(String key) { ResourceBundle bundle = FindbugsPlugin.getDefault().getResourceBundle(); try { return bundle.getString(key); } catch (MissingResourceException e) { return key; } }
java
public static String getFindBugsEnginePluginLocation() { // findbugs.home should be set to the directory the plugin is // installed in. URL u = plugin.getBundle().getEntry("/"); try { URL bundleRoot = FileLocator.resolve(u); String path = bundleRoot.getPath(); if (FindBugsBuilder.DEBUG) { System.out.println("Pluginpath: " + path); //$NON-NLS-1$ } 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; }
java
public void logException(Throwable e, String message) { logMessage(IStatus.ERROR, message, e); }
java
public static IPath getBugCollectionFile(IProject project) { // IPath path = project.getWorkingLocation(PLUGIN_ID); // // project-specific but not user-specific? IPath path = getDefault().getStateLocation(); // user-specific but not // project-specific return path.append(project.getName() + ".fbwarnings.xml"); }
java
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; }
java
private static void readBugCollectionAndProject(IProject project, IProgressMonitor monitor) throws IOException, DocumentException, CoreException { SortedBugCollection bugCollection; IPath bugCollectionPath = getBugCollectionFile(project); // Don't turn the path to an IFile because it isn't local to the // project. // see the javadoc for org.eclipse.core.runtime.Plugin File bugCollectionFile = bugCollectionPath.toFile(); if (!bugCollectionFile.exists()) { // throw new // FileNotFoundException(bugCollectionFile.getLocation().toOSString()); getDefault().logInfo("creating new bug collection: " + bugCollectionPath.toOSString()); createDefaultEmptyBugCollection(project); // since we no longer // throw, have to do this // here return; } UserPreferences prefs = getUserPreferences(project); bugCollection = new SortedBugCollection(); bugCollection.getProject().setGuiCallback(new EclipseGuiCallback(project)); bugCollection.readXML(bugCollectionFile); cacheBugCollectionAndProject(project, bugCollection, bugCollection.getProject()); }
java
public static void storeBugCollection(IProject project, final SortedBugCollection bugCollection, IProgressMonitor monitor) throws IOException, CoreException { // Store the bug collection and findbugs project in the session project.setSessionProperty(SESSION_PROPERTY_BUG_COLLECTION, bugCollection); if (bugCollection != null) { writeBugCollection(project, bugCollection, monitor); } }
java
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); } } }
java
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(); } }
java
public static void saveUserPreferences(IProject project, final UserPreferences userPrefs) throws CoreException { FileOutput userPrefsOutput = new FileOutput() { @Override public void writeFile(OutputStream os) throws IOException { userPrefs.write(os); } @Override public String getTaskDescription() { return "writing user preferences"; } }; if (project != null) { // Make the new user preferences current for the project 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 { // write the workspace preferences to the eclipse preference store 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(); // Reset any existing custom group entries 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"); } } } }
java
private static void resetStore(IPreferenceStore store, String prefix) { int start = 0; // 99 is paranoia. while(start < 99){ String name = prefix + start; if(store.contains(name)){ store.setToDefault(name); } else { break; } start ++; } }
java
private static void ensureReadWrite(IFile file) throws CoreException { /* * fix for bug 1683264: we should checkout file before writing to it */ if (file.isReadOnly()) { IStatus checkOutStatus = ResourcesPlugin.getWorkspace().validateEdit(new IFile[] { file }, null); if (!checkOutStatus.isOK()) { throw new CoreException(checkOutStatus); } } }
java
private static UserPreferences readUserPreferences(IProject project) throws CoreException { IFile userPrefsFile = getUserPreferencesFile(project); if (!userPrefsFile.exists()) { return null; } try { // force is preventing us for out-of-sync exception if file was // changed externally 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; } }
java
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; }
java
public static MethodDescriptor getMethodDescriptor(JavaClass jclass, Method method) { return DescriptorFactory.instance().getMethodDescriptor(jclass.getClassName().replace('.', '/'), method.getName(), method.getSignature(), method.isStatic()); }
java
public static ClassDescriptor getClassDescriptor(JavaClass jclass) { return DescriptorFactory.instance().getClassDescriptor(ClassName.toSlashedClassName(jclass.getClassName())); }
java
public static boolean preTiger(JavaClass jclass) { return jclass.getMajor() < JDK15_MAJOR || (jclass.getMajor() == JDK15_MAJOR && jclass.getMinor() < JDK15_MINOR); }
java
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); }
java
public DetectorFactory getFactoryByShortName(final String shortName) { return findFirstMatchingFactory(factory -> factory.getShortName().equals(shortName)); }
java
public DetectorFactory getFactoryByFullName(final String fullName) { return findFirstMatchingFactory(factory -> factory.getFullName().equals(fullName)); }
java
public Collection<TypeQualifierValue<?>> getDirectlyRelevantTypeQualifiers(MethodDescriptor m) { Collection<TypeQualifierValue<?>> result = methodToDirectlyRelevantQualifiersMap.get(m); if (result != null) { return result; } return Collections.<TypeQualifierValue<?>> emptyList(); }
java
public void setDirectlyRelevantTypeQualifiers(MethodDescriptor methodDescriptor, Collection<TypeQualifierValue<?>> qualifiers) { methodToDirectlyRelevantQualifiersMap.put(methodDescriptor, qualifiers); allKnownQualifiers.addAll(qualifiers); }
java
private int adjustPriority(int priority) { try { Subtypes2 subtypes2 = AnalysisContext.currentAnalysisContext().getSubtypes2(); if (!subtypes2.hasSubtypes(getClassDescriptor())) { priority++; } else { Set<ClassDescriptor> mySubtypes = subtypes2.getSubtypes(getClassDescriptor()); String myPackagename = getThisClass().getPackageName(); for (ClassDescriptor c : mySubtypes) { if (c.equals(getClassDescriptor())) { continue; } if (!c.getPackageName().equals(myPackagename)) { priority--; break; } } } } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } return priority; }
java
void registerDetector(DetectorFactory factory) { if (FindBugs.DEBUG) { System.out.println("Registering detector: " + factory.getFullName()); } String detectorName = factory.getShortName(); if(!factoryList.contains(factory)) { factoryList.add(factory); } else { LOGGER.log(Level.WARNING, "Trying to add already registered factory: " + factory + ", " + factory.getPlugin()); } factoriesByName.put(detectorName, factory); factoriesByDetectorClassName.put(factory.getFullName(), factory); }
java
public @CheckForNull BugPattern lookupBugPattern(String bugType) { if (bugType == null) { return null; } return bugPatternMap.get(bugType); }
java
public Collection<String> getBugCategories() { ArrayList<String> result = new ArrayList<>(categoryDescriptionMap.size()); for(BugCategory c : categoryDescriptionMap.values()) { if (!c.isHidden()) { result.add(c.getCategory()); } } return result; }
java
public static boolean isGetterMethod(ClassContext classContext, Method method) { MethodGen methodGen = classContext.getMethodGen(method); if (methodGen == null) { return false; } InstructionList il = methodGen.getInstructionList(); // System.out.println("Checking getter method: " + method.getName()); if (il.getLength() > 60) { return false; } int count = 0; Iterator<InstructionHandle> it = il.iterator(); while (it.hasNext()) { InstructionHandle ih = it.next(); switch (ih.getInstruction().getOpcode()) { case Const.GETFIELD: count++; if (count > 1) { return false; } break; case Const.PUTFIELD: case Const.BALOAD: case Const.CALOAD: case Const.DALOAD: case Const.FALOAD: case Const.IALOAD: case Const.LALOAD: case Const.SALOAD: case Const.AALOAD: case Const.BASTORE: case Const.CASTORE: case Const.DASTORE: case Const.FASTORE: case Const.IASTORE: case Const.LASTORE: case Const.SASTORE: case Const.AASTORE: case Const.PUTSTATIC: return false; case Const.INVOKESTATIC: case Const.INVOKEVIRTUAL: case Const.INVOKEINTERFACE: case Const.INVOKESPECIAL: case Const.GETSTATIC: // no-op } } // System.out.println("Found getter method: " + method.getName()); return true; }
java
private FieldStats getStats(XField field) { FieldStats stats = statMap.get(field); if (stats == null) { stats = new FieldStats(field); statMap.put(field, stats); } return stats; }
java