_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q166800
DefaultImageLoadHandler.setLoadingBitmap
validation
public void setLoadingBitmap(Bitmap loadingBitmap) { if (Version.hasHoneycomb()) { mLoadingDrawable = new BitmapDrawable(mContext.getResources(), loadingBitmap); } }
java
{ "resource": "" }
q166801
TitleHeaderBar.setCustomizedRightView
validation
public void setCustomizedRightView(View view) { RelativeLayout.LayoutParams lp = makeLayoutParams(view); lp.addRule(CENTER_VERTICAL); lp.addRule(ALIGN_PARENT_RIGHT); getRightViewContainer().addView(view, lp); }
java
{ "resource": "" }
q166802
SimpleDownloader.downloadToStream
validation
public boolean downloadToStream(ImageTask imageTask, String urlString, OutputStream outputStream, ProgressUpdateHandler progressUpdateHandler) { disableConnectionReuseIfNecessary(); HttpURLConnection urlConnection = null; BufferedOutputStream out = null; BufferedInputStream in = null; try { final URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(0); int len = urlConnection.getContentLength(); int total = 0; in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE); out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE); int b; while ((b = in.read()) != -1) { total++; out.write(b); if (progressUpdateHandler != null) { progressUpdateHandler.onProgressUpdate(total, len); } } return true; } catch (final IOException e) { CLog.e(LOG_TAG, "Error in downloadBitmap - " + e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (final IOException e) { } } return false; }
java
{ "resource": "" }
q166803
ImageTask.addImageView
validation
public void addImageView(CubeImageView imageView) { if (null == imageView) { return; } if (null == mFirstImageViewHolder) { mFirstImageViewHolder = new ImageViewHolder(imageView); return; } ImageViewHolder holder = mFirstImageViewHolder; for (; ; holder = holder.mNext) { if (holder.contains(imageView)) { return; } if (holder.mNext == null) { break; } } ImageViewHolder newHolder = new ImageViewHolder(imageView); newHolder.mPrev = holder; holder.mNext = newHolder; }
java
{ "resource": "" }
q166804
ImageTask.removeImageView
validation
public void removeImageView(CubeImageView imageView) { if (null == imageView || null == mFirstImageViewHolder) { return; } ImageViewHolder holder = mFirstImageViewHolder; do { if (holder.contains(imageView)) { // Make sure entry is right. if (holder == mFirstImageViewHolder) { mFirstImageViewHolder = holder.mNext; } if (null != holder.mNext) { holder.mNext.mPrev = holder.mPrev; } if (null != holder.mPrev) { holder.mPrev.mNext = holder.mNext; } } } while ((holder = holder.mNext) != null); }
java
{ "resource": "" }
q166805
ImageTask.onLoading
validation
public void onLoading(ImageLoadHandler handler) { mFlag = mFlag | STATUS_LOADING; if (null == handler) { return; } if (mFirstImageViewHolder == null) { handler.onLoading(this, null); } else { ImageViewHolder holder = mFirstImageViewHolder; do { final CubeImageView imageView = holder.getImageView(); if (null != imageView) { handler.onLoading(this, imageView); } } while ((holder = holder.mNext) != null); } }
java
{ "resource": "" }
q166806
ImageTask.onLoadTaskFinish
validation
public void onLoadTaskFinish(BitmapDrawable drawable, ImageLoadHandler handler) { mFlag &= ~STATUS_LOADING; if (null == handler) { return; } int errorCode = mFlag & ERROR_CODE_MASK; if (errorCode > 0) { onLoadError(errorCode, handler); return; } if (null != mImageTaskStatistics) { mImageTaskStatistics.s5_beforeShow(); } if (mFirstImageViewHolder == null) { handler.onLoadFinish(this, null, drawable); } else { ImageViewHolder holder = mFirstImageViewHolder; do { final CubeImageView imageView = holder.getImageView(); if (null != imageView) { imageView.onLoadFinish(); handler.onLoadFinish(this, imageView, drawable); } } while ((holder = holder.mNext) != null); } if (null != mImageTaskStatistics) { mImageTaskStatistics.s6_afterShow(ImageProvider.getBitmapSize(drawable)); ImagePerformanceStatistics.onImageLoaded(this, mImageTaskStatistics); } }
java
{ "resource": "" }
q166807
ImageTask.joinSizeInfoToKey
validation
public static String joinSizeInfoToKey(String key, int w, int h) { if (w > 0 && h != Integer.MAX_VALUE && h > 0 && h != Integer.MAX_VALUE) { return new StringBuilder(key).append(SIZE_SP).append(w).append(SIZE_SP).append(h).toString(); } return key; }
java
{ "resource": "" }
q166808
ImageTask.joinSizeTagToKey
validation
public static String joinSizeTagToKey(String key, String tag) { return new StringBuilder(key).append(SIZE_SP).append(tag).toString(); }
java
{ "resource": "" }
q166809
DiskCacheProvider.openDiskCacheAsync
validation
public void openDiskCacheAsync() { if (DEBUG) { CLog.d(LOG_TAG, "%s: initDiskCacheAsync", mDiskCache); } synchronized (mDiskCacheLock) { mDiskCacheStarting = true; new FileCacheTask(TASK_INIT_CACHE).executeNow(); } }
java
{ "resource": "" }
q166810
DiskCacheProvider.flushDiskCacheAsyncWithDelay
validation
public void flushDiskCacheAsyncWithDelay(int delay) { if (DEBUG) { CLog.d(LOG_TAG, "%s, flushDiskCacheAsyncWithDelay", delay); } if (mIsDelayFlushing) { return; } mIsDelayFlushing = true; new FileCacheTask(TASK_FLUSH_CACHE).executeAfter(delay); }
java
{ "resource": "" }
q166811
DiskCacheProvider.getDiskCache
validation
public DiskCache getDiskCache() { if (!mDiskCacheReady) { if (DEBUG) { CLog.d(LOG_TAG, "%s, try to access disk cache, but it is not open, try to open it.", mDiskCache); } openDiskCacheAsync(); } synchronized (mDiskCacheLock) { while (mDiskCacheStarting) { try { if (DEBUG) { CLog.d(LOG_TAG, "%s, try to access, but disk cache is not ready, wait", mDiskCache); } mDiskCacheLock.wait(); } catch (InterruptedException e) { } } } return mDiskCache; }
java
{ "resource": "" }
q166812
FileUtils.deleteDirectoryQuickly
validation
public static void deleteDirectoryQuickly(File dir) throws IOException { if (!dir.exists()) { return; } final File to = new File(dir.getAbsolutePath() + System.currentTimeMillis()); dir.renameTo(to); if (!dir.exists()) { // rebuild dir.mkdirs(); } // try to run "rm -r" to remove the whole directory if (to.exists()) { String deleteCmd = "rm -r " + to; Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec(deleteCmd); process.waitFor(); } catch (IOException e) { } catch (InterruptedException e) { e.printStackTrace(); } } if (!to.exists()) { return; } deleteDirectoryRecursively(to); if (to.exists()) { to.delete(); } }
java
{ "resource": "" }
q166813
DiskFileUtils.getExternalCacheDir
validation
@TargetApi(Build.VERSION_CODES.FROYO) public static File getExternalCacheDir(Context context) { if (Version.hasFroyo()) { File path = context.getExternalCacheDir(); // In some case, even the sd card is mounted, getExternalCacheDir will return null, may be it is nearly full. if (path != null) { return path; } } // Before Froyo or the path is null, we need to construct the external cache folder ourselves final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/"; return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir); }
java
{ "resource": "" }
q166814
DiskFileUtils.getUsableSpace
validation
@SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.GINGERBREAD) public static long getUsableSpace(File path) { if (path == null) { return -1; } if (Version.hasGingerbread()) { return path.getUsableSpace(); } else { if (!path.exists()) { return 0; } else { final StatFs stats = new StatFs(path.getPath()); return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks(); } } }
java
{ "resource": "" }
q166815
CubeImageView.notifyDrawable
validation
private static void notifyDrawable(Drawable drawable, final boolean isDisplayed) { if (drawable instanceof RecyclingBitmapDrawable) { // The drawable is a CountingBitmapDrawable, so notify it ((RecyclingBitmapDrawable) drawable).setIsDisplayed(isDisplayed); } else if (drawable instanceof LayerDrawable) { // The drawable is a LayerDrawable, so recurse on each layer LayerDrawable layerDrawable = (LayerDrawable) drawable; for (int i = 0, z = layerDrawable.getNumberOfLayers(); i < z; i++) { notifyDrawable(layerDrawable.getDrawable(i), isDisplayed); } } }
java
{ "resource": "" }
q166816
CubeFragment.onResume
validation
@Override public void onResume() { super.onResume(); if (!mFirstResume) { onBack(); } if (mFirstResume) { mFirstResume = false; } if (DEBUG) { showStatus("onResume"); } }
java
{ "resource": "" }
q166817
ListPageInfo.lastItem
validation
public T lastItem() { if (mDataList == null || mDataList.size() == 0) { return null; } return mDataList.get(mDataList.size() - 1); }
java
{ "resource": "" }
q166818
Fab.hide
validation
@Override public void hide() { // Only use scale animation if FAB is visible if (getVisibility() == View.VISIBLE) { // Pivots indicate where the animation begins from float pivotX = getPivotX() + getTranslationX(); float pivotY = getPivotY() + getTranslationY(); // Animate FAB shrinking ScaleAnimation anim = new ScaleAnimation(1, 0, 1, 0, pivotX, pivotY); anim.setDuration(FAB_ANIM_DURATION); anim.setInterpolator(getInterpolator()); startAnimation(anim); } setVisibility(View.INVISIBLE); }
java
{ "resource": "" }
q166819
MaterialSheetAnimation.alignSheetWithFab
validation
public void alignSheetWithFab(View fab) { // NOTE: View.getLocationOnScreen() returns the view's coordinates on the screen // whereas other view methods like getRight() and getY() return coordinates relative // to the view's parent. Using those methods can lead to incorrect calculations when // the two views do not have the same parent. // Get FAB's coordinates int[] fabCoords = new int[2]; fab.getLocationOnScreen(fabCoords); // Get sheet's coordinates int[] sheetCoords = new int[2]; sheet.getLocationOnScreen(sheetCoords); // NOTE: Use the diffs between the positions of the FAB and sheet to align the sheet. // We have to use the diffs because the coordinates returned by getLocationOnScreen() // include the status bar and any other system UI elements, meaning the coordinates // aren't representative of the usable screen space. int leftDiff = sheetCoords[0] - fabCoords[0]; int rightDiff = (sheetCoords[0] + sheet.getWidth()) - (fabCoords[0] + fab.getWidth()); int topDiff = sheetCoords[1] - fabCoords[1]; int bottomDiff = (sheetCoords[1] + sheet.getHeight()) - (fabCoords[1] + fab.getHeight()); // NOTE: Preserve the sheet's margins to allow users to shift the sheet's position // to compensate for the fact that the design support library's FAB has extra // padding within the view ViewGroup.MarginLayoutParams sheetLayoutParams = (ViewGroup.MarginLayoutParams) sheet .getLayoutParams(); // Set sheet's new coordinates (only if there is a change in coordinates because // setting the same coordinates can cause the view to "drift" - moving 0.5 to 1 pixels // around the screen) if (rightDiff != 0) { float sheetX = sheet.getX(); // Align the right side of the sheet with the right side of the FAB if // doing so would not move the sheet off the screen if (rightDiff <= sheetX) { sheet.setX(sheetX - rightDiff - sheetLayoutParams.rightMargin); revealXDirection = RevealXDirection.LEFT; } // Otherwise, align the left side of the sheet with the left side of the FAB else if (leftDiff != 0 && leftDiff <= sheetX) { sheet.setX(sheetX - leftDiff + sheetLayoutParams.leftMargin); revealXDirection = RevealXDirection.RIGHT; } } if (bottomDiff != 0) { float sheetY = sheet.getY(); // Align the bottom of the sheet with the bottom of the FAB if (bottomDiff <= sheetY) { sheet.setY(sheetY - bottomDiff - sheetLayoutParams.bottomMargin); revealYDirection = RevealYDirection.UP; } // Otherwise, align the top of the sheet with the top of the FAB else if (topDiff != 0 && topDiff <= sheetY) { sheet.setY(sheetY - topDiff + sheetLayoutParams.topMargin); revealYDirection = RevealYDirection.DOWN; } } }
java
{ "resource": "" }
q166820
MaterialSheetAnimation.morphFromFab
validation
public void morphFromFab(View fab, long showSheetDuration, long showSheetColorDuration, AnimationListener listener) { sheet.setVisibility(View.VISIBLE); revealSheetWithFab(fab, getFabRevealRadius(fab), getSheetRevealRadius(), showSheetDuration, fabColor, sheetColor, showSheetColorDuration, listener); }
java
{ "resource": "" }
q166821
MaterialSheetAnimation.morphIntoFab
validation
public void morphIntoFab(View fab, long hideSheetDuration, long hideSheetColorDuration, AnimationListener listener) { revealSheetWithFab(fab, getSheetRevealRadius(), getFabRevealRadius(fab), hideSheetDuration, sheetColor, fabColor, hideSheetColorDuration, listener); }
java
{ "resource": "" }
q166822
OverlayAnimation.hide
validation
public void hide(long duration, final AnimationListener listener) { overlay.animate().alpha(0).setDuration(duration).setInterpolator(interpolator) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { if (listener != null) { listener.onStart(); } } @Override public void onAnimationEnd(Animator animation) { overlay.setVisibility(View.GONE); if (listener != null) { listener.onEnd(); } } }).start(); }
java
{ "resource": "" }
q166823
MaterialSheetFab.showSheet
validation
public void showSheet() { if (isAnimating()) { return; } isShowing = true; // Show overlay overlayAnimation.show(SHOW_OVERLAY_ANIM_DURATION, null); // Morph FAB into sheet morphIntoSheet(new AnimationListener() { @Override public void onEnd() { // Call event listener if (eventListener != null) { eventListener.onSheetShown(); } // Assuming that this is the last animation to finish isShowing = false; // Hide sheet after it is shown if (hideSheetAfterSheetIsShown) { hideSheet(); hideSheetAfterSheetIsShown = false; } } }); // Call event listener if (eventListener != null) { eventListener.onShowSheet(); } }
java
{ "resource": "" }
q166824
MainActivity.setupActionBar
validation
private void setupActionBar() { setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); }
java
{ "resource": "" }
q166825
MainActivity.setupDrawer
validation
private void setupDrawer() { drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.opendrawer, R.string.closedrawer); drawerLayout.setDrawerListener(drawerToggle); }
java
{ "resource": "" }
q166826
MainActivity.setupTabs
validation
private void setupTabs() { // Setup view pager ViewPager viewpager = (ViewPager) findViewById(R.id.viewpager); viewpager.setAdapter(new MainPagerAdapter(this, getSupportFragmentManager())); viewpager.setOffscreenPageLimit(MainPagerAdapter.NUM_ITEMS); updatePage(viewpager.getCurrentItem()); // Setup tab layout TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewpager); viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int i) { updatePage(i); } @Override public void onPageScrollStateChanged(int i) { } }); }
java
{ "resource": "" }
q166827
MainActivity.setupFab
validation
private void setupFab() { Fab fab = (Fab) findViewById(R.id.fab); View sheetView = findViewById(R.id.fab_sheet); View overlay = findViewById(R.id.overlay); int sheetColor = getResources().getColor(R.color.background_card); int fabColor = getResources().getColor(R.color.theme_accent); // Create material sheet FAB materialSheetFab = new MaterialSheetFab<>(fab, sheetView, overlay, sheetColor, fabColor); // Set material sheet event listener materialSheetFab.setEventListener(new MaterialSheetFabEventListener() { @Override public void onShowSheet() { // Save current status bar color statusBarColor = getStatusBarColor(); // Set darker status bar color to match the dim overlay setStatusBarColor(getResources().getColor(R.color.theme_primary_dark2)); } @Override public void onHideSheet() { // Restore status bar color setStatusBarColor(statusBarColor); } }); // Set material sheet item click listeners findViewById(R.id.fab_sheet_item_recording).setOnClickListener(this); findViewById(R.id.fab_sheet_item_reminder).setOnClickListener(this); findViewById(R.id.fab_sheet_item_photo).setOnClickListener(this); findViewById(R.id.fab_sheet_item_note).setOnClickListener(this); }
java
{ "resource": "" }
q166828
MainActivity.updateFab
validation
private void updateFab(int selectedPage) { switch (selectedPage) { case MainPagerAdapter.ALL_POS: materialSheetFab.showFab(); break; case MainPagerAdapter.SHARED_POS: materialSheetFab.showFab(0, -getResources().getDimensionPixelSize(R.dimen.snackbar_height)); break; case MainPagerAdapter.FAVORITES_POS: default: materialSheetFab.hideSheetThenFab(); break; } }
java
{ "resource": "" }
q166829
MainActivity.updateSnackbar
validation
private void updateSnackbar(int selectedPage) { View snackbar = findViewById(R.id.snackbar); switch (selectedPage) { case MainPagerAdapter.SHARED_POS: snackbar.setVisibility(View.VISIBLE); break; case MainPagerAdapter.ALL_POS: case MainPagerAdapter.FAVORITES_POS: default: snackbar.setVisibility(View.GONE); break; } }
java
{ "resource": "" }
q166830
FabAnimation.morphIntoSheet
validation
public void morphIntoSheet(int endX, int endY, Side side, int arcDegrees, float scaleFactor, long duration, AnimationListener listener) { morph(endX, endY, side, arcDegrees, scaleFactor, duration, listener); }
java
{ "resource": "" }
q166831
FabAnimation.morphFromSheet
validation
public void morphFromSheet(int endX, int endY, Side side, int arcDegrees, float scaleFactor, long duration, AnimationListener listener) { fab.setVisibility(View.VISIBLE); morph(endX, endY, side, arcDegrees, scaleFactor, duration, listener); }
java
{ "resource": "" }
q166832
SuggestionsAdapter.hideSuggestionsIfNecessary
validation
private void hideSuggestionsIfNecessary(final @NonNull QueryToken currentQuery, final @NonNull TokenSource source) { String queryTS = currentQuery.getTokenString(); String currentTS = source.getCurrentTokenString(); if (!isWaitingForResults(currentQuery) && queryTS != null && queryTS.equals(currentTS)) { mSuggestionsVisibilityManager.displaySuggestions(false); } }
java
{ "resource": "" }
q166833
MentionsLoader.getSuggestions
validation
public List<T> getSuggestions(QueryToken queryToken) { String prefix = queryToken.getKeywords().toLowerCase(); List<T> suggestions = new ArrayList<>(); if (mData != null) { for (T suggestion : mData) { String name = suggestion.getSuggestiblePrimaryText().toLowerCase(); if (name.startsWith(prefix)) { suggestions.add(suggestion); } } } return suggestions; }
java
{ "resource": "" }
q166834
WordTokenizer.containsExplicitChar
validation
public boolean containsExplicitChar(final @NonNull CharSequence input) { if (!TextUtils.isEmpty(input)) { for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (isExplicitChar(c)) { return true; } } } return false; }
java
{ "resource": "" }
q166835
WordTokenizer.containsWordBreakingChar
validation
public boolean containsWordBreakingChar(final @NonNull CharSequence input) { if (!TextUtils.isEmpty(input)) { for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (isWordBreakingChar(c)) { return true; } } } return false; }
java
{ "resource": "" }
q166836
WordTokenizer.onlyLettersOrDigits
validation
public boolean onlyLettersOrDigits(final @NonNull CharSequence input, final int numCharsToCheck, final int start) { // Starting position must be within the input string if (start < 0 || start > input.length()) { return false; } // Check the first "numCharsToCheck" characters to ensure they are a letter or digit for (int i = 0; i < numCharsToCheck; i++) { int positionToCheck = start + i; // Return false if we would throw an Out-of-Bounds exception if (positionToCheck >= input.length()) { return false; } // Return false early if current character is not a letter or digit char charToCheck = input.charAt(positionToCheck); if (!Character.isLetterOrDigit(charToCheck)) { return false; } } // First "numCharsToCheck" characters are either letters or digits, so return true return true; }
java
{ "resource": "" }
q166837
WordTokenizer.getSearchStartIndex
validation
protected int getSearchStartIndex(final @NonNull Spanned text, int cursor) { if (cursor < 0 || cursor > text.length()) { cursor = 0; } // Get index of the end of the last span before the cursor (or 0 if does not exist) MentionSpan[] spans = text.getSpans(0, text.length(), MentionSpan.class); int closestToCursor = 0; for (MentionSpan span : spans) { int end = text.getSpanEnd(span); if (end > closestToCursor && end <= cursor) { closestToCursor = end; } } // Get the index of the start of the line String textString = text.toString().substring(0, cursor); int lineStartIndex = 0; if (textString.contains(mConfig.LINE_SEPARATOR)) { lineStartIndex = textString.lastIndexOf(mConfig.LINE_SEPARATOR) + 1; } // Return whichever is closer before to the cursor return Math.max(closestToCursor, lineStartIndex); }
java
{ "resource": "" }
q166838
WordTokenizer.getSearchEndIndex
validation
protected int getSearchEndIndex(final @NonNull Spanned text, int cursor) { if (cursor < 0 || cursor > text.length()) { cursor = 0; } // Get index of the start of the first span after the cursor (or text.length() if does not exist) MentionSpan[] spans = text.getSpans(0, text.length(), MentionSpan.class); int closestAfterCursor = text.length(); for (MentionSpan span : spans) { int start = text.getSpanStart(span); if (start < closestAfterCursor && start >= cursor) { closestAfterCursor = start; } } // Get the index of the end of the line String textString = text.toString().substring(cursor, text.length()); int lineEndIndex = text.length(); if (textString.contains(mConfig.LINE_SEPARATOR)) { lineEndIndex = cursor + textString.indexOf(mConfig.LINE_SEPARATOR); } // Return whichever is closest after the cursor return Math.min(closestAfterCursor, lineEndIndex); }
java
{ "resource": "" }
q166839
RichEditorView.displayTextCounter
validation
public void displayTextCounter(boolean display) { if (display) { mTextCounterView.setVisibility(TextView.VISIBLE); } else { mTextCounterView.setVisibility(TextView.GONE); } }
java
{ "resource": "" }
q166840
RichEditorView.disableSpellingSuggestions
validation
private void disableSpellingSuggestions(boolean disable) { // toggling suggestions often resets the cursor location, but we don't want that to happen int start = mMentionsEditText.getSelectionStart(); int end = mMentionsEditText.getSelectionEnd(); // -1 means there is no selection or cursor. if (start == -1 || end == -1) { return; } if (disable) { // store the previous input type mOriginalInputType = mMentionsEditText.getInputType(); } mMentionsEditText.setRawInputType(disable ? InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS : mOriginalInputType); mMentionsEditText.setSelection(start, end); }
java
{ "resource": "" }
q166841
RichEditorView.updateEditorTextCount
validation
private void updateEditorTextCount() { if (mMentionsEditText != null && mTextCounterView != null) { int textCount = mMentionsEditText.getMentionsText().length(); mTextCounterView.setText(String.valueOf(textCount)); if (mTextCountLimit > 0 && textCount > mTextCountLimit) { mTextCounterView.setTextColor(mBeyondCountLimitTextColor); } else { mTextCounterView.setTextColor(mWithinCountLimitTextColor); } } }
java
{ "resource": "" }
q166842
RichEditorView.setMentionSpanFactory
validation
public void setMentionSpanFactory(@NonNull final MentionsEditText.MentionSpanFactory factory) { if (mMentionsEditText != null) { mMentionsEditText.setMentionSpanFactory(factory); } }
java
{ "resource": "" }
q166843
MentionsEditText.copy
validation
private void copy(@IntRange(from = 0) int start, @IntRange(from = 0) int end) { MentionsEditable text = getMentionsText(); SpannableStringBuilder copiedText = (SpannableStringBuilder) text.subSequence(start, end); MentionSpan[] spans = text.getSpans(start, end, MentionSpan.class); Intent intent = null; if (spans.length > 0) { // Save MentionSpan and it's start offset. intent = new Intent(); intent.putExtra(KEY_MENTION_SPANS, spans); int[] spanStart = new int[spans.length]; for (int i = 0; i < spans.length; i++) { spanStart[i] = copiedText.getSpanStart(spans[i]); } intent.putExtra(KEY_MENTION_SPAN_STARTS, spanStart); } saveToClipboard(copiedText, intent); }
java
{ "resource": "" }
q166844
MentionsEditText.paste
validation
private void paste(@IntRange(from = 0) int min, @IntRange(from = 0) int max) { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); MentionsEditable text = getMentionsText(); text.replace(text.length(), text.length(), clipboard.getText()); } else { pasteHoneycombImpl(min, max); } }
java
{ "resource": "" }
q166845
MentionsEditText.pasteHoneycombImpl
validation
@TargetApi(Build.VERSION_CODES.HONEYCOMB) private void pasteHoneycombImpl(@IntRange(from = 0) int min, @IntRange(from = 0) int max) { ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = clipboard.getPrimaryClip(); if (clip != null) { for (int i = 0; i < clip.getItemCount(); i++) { ClipData.Item item = clip.getItemAt(i); String selectedText = item.coerceToText(getContext()).toString(); MentionsEditable text = getMentionsText(); MentionSpan[] spans = text.getSpans(min, max, MentionSpan.class); /* * We need to remove the span between min and max. This is required because in * {@link SpannableStringBuilder#replace(int, int, CharSequence)} existing spans within * the Editable that entirely cover the replaced range are retained, but any that * were strictly within the range that was replaced are removed. In our case the existing * spans are retained if the selection entirely covers the span. So, we just remove * the existing span and replace the new text with that span. */ for (MentionSpan span : spans) { if (text.getSpanEnd(span) == min) { // We do not want to remove the span, when we want to paste anything just next // to the existing span. In this case "text.getSpanEnd(span)" will be equal // to min. continue; } text.removeSpan(span); } Intent intent = item.getIntent(); // Just set the plain text if we do not have mentions data in the intent/bundle if (intent == null) { text.replace(min, max, selectedText); continue; } Bundle bundle = intent.getExtras(); if (bundle == null) { text.replace(min, max, selectedText); continue; } bundle.setClassLoader(getContext().getClassLoader()); int[] spanStart = bundle.getIntArray(KEY_MENTION_SPAN_STARTS); Parcelable[] parcelables = bundle.getParcelableArray(KEY_MENTION_SPANS); if (parcelables == null || parcelables.length <= 0 || spanStart == null || spanStart.length <= 0) { text.replace(min, max, selectedText); continue; } // Set the MentionSpan in text. SpannableStringBuilder s = new SpannableStringBuilder(selectedText); for (int j = 0; j < parcelables.length; j++) { MentionSpan mentionSpan = (MentionSpan) parcelables[j]; s.setSpan(mentionSpan, spanStart[j], spanStart[j] + mentionSpan.getDisplayString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } text.replace(min, max, s); } } }
java
{ "resource": "" }
q166846
MentionsEditText.updateSelectionIfRequired
validation
private void updateSelectionIfRequired(final int selStart, final int selEnd) { MentionsEditable text = getMentionsText(); MentionSpan startMentionSpan = text.getMentionSpanAtOffset(selStart); MentionSpan endMentionSpan = text.getMentionSpanAtOffset(selEnd); boolean selChanged = false; int start = selStart; int end = selEnd; if (text.getSpanStart(startMentionSpan) < selStart && selStart < text.getSpanEnd(startMentionSpan)) { start = text.getSpanStart(startMentionSpan); selChanged = true; } if (text.getSpanStart(endMentionSpan) < selEnd && selEnd < text.getSpanEnd(endMentionSpan)) { end = text.getSpanEnd(endMentionSpan); selChanged = true; } if (selChanged) { setSelection(start, end); } }
java
{ "resource": "" }
q166847
MentionsEditText.onCursorChanged
validation
private boolean onCursorChanged(final int index) { Editable text = getText(); if (text == null) { return false; } MentionSpan[] allSpans = text.getSpans(0, text.length(), MentionSpan.class); for (MentionSpan span : allSpans) { // Deselect span if the cursor is not on the span. if (span.isSelected() && (index < text.getSpanStart(span) || index > text.getSpanEnd(span))) { span.setSelected(false); updateSpan(span); } } // Do not allow the user to set the cursor within a span. If the user tries to do so, select // move the cursor to the end of it. MentionSpan[] currentSpans = text.getSpans(index, index, MentionSpan.class); if (currentSpans.length != 0) { MentionSpan span = currentSpans[0]; int start = text.getSpanStart(span); int end = text.getSpanEnd(span); if (index > start && index < end) { super.setSelection(end); return true; } } return false; }
java
{ "resource": "" }
q166848
MentionsEditText.deselectAllSpans
validation
public void deselectAllSpans() { mBlockCompletion = true; Editable text = getText(); MentionSpan[] spans = text.getSpans(0, text.length(), MentionSpan.class); for (MentionSpan span : spans) { if (span.isSelected()) { span.setSelected(false); updateSpan(span); } } mBlockCompletion = false; }
java
{ "resource": "" }
q166849
TimeParserUtil.parseDuration
validation
public static long parseDuration(String duration) { if (duration == null || duration.isEmpty()) { throw new IllegalArgumentException("duration may not be null"); } long toAdd = -1; if (days.matcher(duration).matches()) { Matcher matcher = days.matcher(duration); matcher.matches(); toAdd = Long.parseLong(matcher.group(1)) * 60 * 60 * 24 * 1000; } else if (hours.matcher(duration).matches()) { Matcher matcher = hours.matcher(duration); matcher.matches(); toAdd = Long.parseLong(matcher.group(1)) * 60 * 60 * 1000; } else if (minutes.matcher(duration).matches()) { Matcher matcher = minutes.matcher(duration); matcher.matches(); toAdd = Long.parseLong(matcher.group(1)) * 60 * 1000; } else if (seconds.matcher(duration).matches()) { Matcher matcher = seconds.matcher(duration); matcher.matches(); toAdd = Long.parseLong(matcher.group(1)) * 1000; } else if (milliseconds.matcher(duration).matches()) { Matcher matcher = milliseconds.matcher(duration); matcher.matches(); toAdd = Long.parseLong(matcher.group(1)); } if (toAdd == -1) { throw new IllegalArgumentException("Invalid duration pattern : " + duration); } return toAdd; }
java
{ "resource": "" }
q166850
SVGUtils.escapeForXML
validation
public static String escapeForXML(String source) { Args.nullNotPermitted(source, "source"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < source.length(); i++) { char c = source.charAt(i); switch (c) { case '<' : { sb.append("&lt;"); break; } case '>' : { sb.append("&gt;"); break; } case '&' : { String next = source.substring(i, Math.min(i + 6, source.length())); if (next.startsWith("&lt;") || next.startsWith("&gt;") || next.startsWith("&amp;") || next.startsWith("&apos;") || next.startsWith("&quot;")) { sb.append(c); } else { sb.append("&amp;"); } break; } case '\'' : { sb.append("&apos;"); break; } case '\"' : { sb.append("&quot;"); break; } default : sb.append(c); } } return sb.toString(); }
java
{ "resource": "" }
q166851
SVGUtils.writeToHTML
validation
public static void writeToHTML(File file, String title, String svgElement) throws IOException { BufferedWriter writer = null; try { FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); writer = new BufferedWriter(osw); writer.write("<!DOCTYPE html>\n"); writer.write("<html>\n"); writer.write("<head>\n"); writer.write("<title>" + title + "</title>\n"); writer.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"); writer.write("</head>\n"); writer.write("<body>\n"); writer.write(svgElement + "\n"); writer.write("</body>\n"); writer.write("</html>\n"); writer.flush(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException ex) { Logger.getLogger(SVGUtils.class.getName()).log(Level.SEVERE, null, ex); } } }
java
{ "resource": "" }
q166852
SVGGraphicsConfiguration.createCompatibleImage
validation
@Override public BufferedImage createCompatibleImage(int width, int height) { ColorModel model = getColorModel(); WritableRaster raster = model.createCompatibleWritableRaster(width, height); return new BufferedImage(model, raster, model.isAlphaPremultiplied(), null); }
java
{ "resource": "" }
q166853
SVGGraphicsConfiguration.createCompatibleVolatileImage
validation
@Override public VolatileImage createCompatibleVolatileImage(int width, int height, ImageCapabilities caps, int transparency) throws AWTException { if (img == null) { img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); gc = img.createGraphics().getDeviceConfiguration(); } return gc.createCompatibleVolatileImage(width, height, caps, transparency); }
java
{ "resource": "" }
q166854
ViewBox.valueStr
validation
public String valueStr() { return new StringBuilder().append(this.minX).append(" ") .append(this.minY).append(" ").append(this.width).append(" ") .append(this.height).toString(); }
java
{ "resource": "" }
q166855
StandardFontMapper.mapFont
validation
@Override public String mapFont(String family) { Args.nullNotPermitted(family, "family"); String alternate = this.alternates.get(family); if (alternate != null) { return alternate; } return family; }
java
{ "resource": "" }
q166856
SVGGraphics2D.setShapeRendering
validation
public void setShapeRendering(String value) { if (!value.equals("auto") && !value.equals("crispEdges") && !value.equals("geometricPrecision") && !value.equals("optimizeSpeed")) { throw new IllegalArgumentException("Unrecognised value: " + value); } this.shapeRendering = value; }
java
{ "resource": "" }
q166857
SVGGraphics2D.setTextRendering
validation
public void setTextRendering(String value) { if (!value.equals("auto") && !value.equals("optimizeSpeed") && !value.equals("optimizeLegibility") && !value.equals("geometricPrecision")) { throw new IllegalArgumentException("Unrecognised value: " + value); } this.textRendering = value; }
java
{ "resource": "" }
q166858
SVGGraphics2D.appendOptionalElementIDFromHint
validation
private void appendOptionalElementIDFromHint(StringBuilder sb) { String elementID = (String) this.hints.get(SVGHints.KEY_ELEMENT_ID); if (elementID != null) { this.hints.put(SVGHints.KEY_ELEMENT_ID, null); // clear it if (this.elementIDs.contains(elementID)) { throw new IllegalStateException("The element id " + elementID + " is already used."); } else { this.elementIDs.add(elementID); } this.sb.append("id=\"").append(elementID).append("\" "); } }
java
{ "resource": "" }
q166859
SVGGraphics2D.getSVGPathData
validation
private String getSVGPathData(Path2D path) { StringBuilder b = new StringBuilder("d=\""); float[] coords = new float[6]; boolean first = true; PathIterator iterator = path.getPathIterator(null); while (!iterator.isDone()) { int type = iterator.currentSegment(coords); if (!first) { b.append(" "); } first = false; switch (type) { case (PathIterator.SEG_MOVETO): b.append("M ").append(geomDP(coords[0])).append(" ") .append(geomDP(coords[1])); break; case (PathIterator.SEG_LINETO): b.append("L ").append(geomDP(coords[0])).append(" ") .append(geomDP(coords[1])); break; case (PathIterator.SEG_QUADTO): b.append("Q ").append(geomDP(coords[0])) .append(" ").append(geomDP(coords[1])) .append(" ").append(geomDP(coords[2])) .append(" ").append(geomDP(coords[3])); break; case (PathIterator.SEG_CUBICTO): b.append("C ").append(geomDP(coords[0])).append(" ") .append(geomDP(coords[1])).append(" ") .append(geomDP(coords[2])).append(" ") .append(geomDP(coords[3])).append(" ") .append(geomDP(coords[4])).append(" ") .append(geomDP(coords[5])); break; case (PathIterator.SEG_CLOSE): b.append("Z "); break; default: break; } iterator.next(); } return b.append("\"").toString(); }
java
{ "resource": "" }
q166860
SVGGraphics2D.rgbColorStr
validation
private String rgbColorStr(Color c) { StringBuilder b = new StringBuilder("rgb("); b.append(c.getRed()).append(",").append(c.getGreen()).append(",") .append(c.getBlue()).append(")"); return b.toString(); }
java
{ "resource": "" }
q166861
SVGGraphics2D.rgbaColorStr
validation
private String rgbaColorStr(Color c) { StringBuilder b = new StringBuilder("rgba("); double alphaPercent = c.getAlpha() / 255.0; b.append(c.getRed()).append(",").append(c.getGreen()).append(",") .append(c.getBlue()); b.append(",").append(transformDP(alphaPercent)); b.append(")"); return b.toString(); }
java
{ "resource": "" }
q166862
SVGGraphics2D.strokeStyle
validation
private String strokeStyle() { double strokeWidth = 1.0f; String strokeCap = DEFAULT_STROKE_CAP; String strokeJoin = DEFAULT_STROKE_JOIN; float miterLimit = DEFAULT_MITER_LIMIT; float[] dashArray = new float[0]; if (this.stroke instanceof BasicStroke) { BasicStroke bs = (BasicStroke) this.stroke; strokeWidth = bs.getLineWidth() > 0.0 ? bs.getLineWidth() : this.zeroStrokeWidth; switch (bs.getEndCap()) { case BasicStroke.CAP_ROUND: strokeCap = "round"; break; case BasicStroke.CAP_SQUARE: strokeCap = "square"; break; case BasicStroke.CAP_BUTT: default: // already set to "butt" } switch (bs.getLineJoin()) { case BasicStroke.JOIN_BEVEL: strokeJoin = "bevel"; break; case BasicStroke.JOIN_ROUND: strokeJoin = "round"; break; case BasicStroke.JOIN_MITER: default: // already set to "miter" } miterLimit = bs.getMiterLimit(); dashArray = bs.getDashArray(); } StringBuilder b = new StringBuilder(); b.append("stroke-width: ").append(strokeWidth).append(";"); b.append("stroke: ").append(svgColorStr()).append(";"); b.append("stroke-opacity: ").append(getColorAlpha() * getAlpha()) .append(";"); if (!strokeCap.equals(DEFAULT_STROKE_CAP)) { b.append("stroke-linecap: ").append(strokeCap).append(";"); } if (!strokeJoin.equals(DEFAULT_STROKE_JOIN)) { b.append("stroke-linejoin: ").append(strokeJoin).append(";"); } if (Math.abs(DEFAULT_MITER_LIMIT - miterLimit) < 0.001) { b.append("stroke-miterlimit: ").append(geomDP(miterLimit)); } if (dashArray != null && dashArray.length != 0) { b.append("stroke-dasharray: "); for (int i = 0; i < dashArray.length; i++) { if (i != 0) b.append(", "); b.append(dashArray[i]); } b.append(";"); } if (this.checkStrokeControlHint) { Object hint = getRenderingHint(RenderingHints.KEY_STROKE_CONTROL); if (RenderingHints.VALUE_STROKE_NORMALIZE.equals(hint) && !this.shapeRendering.equals("crispEdges")) { b.append("shape-rendering:crispEdges;"); } if (RenderingHints.VALUE_STROKE_PURE.equals(hint) && !this.shapeRendering.equals("geometricPrecision")) { b.append("shape-rendering:geometricPrecision;"); } } return b.toString(); }
java
{ "resource": "" }
q166863
SVGGraphics2D.getSVGFillStyle
validation
private String getSVGFillStyle() { StringBuilder b = new StringBuilder(); b.append("fill: ").append(svgColorStr()).append("; "); b.append("fill-opacity: ").append(getColorAlpha() * getAlpha()); return b.toString(); }
java
{ "resource": "" }
q166864
SVGGraphics2D.getSVGFontStyle
validation
private String getSVGFontStyle() { StringBuilder b = new StringBuilder(); b.append("fill: ").append(svgColorStr()).append("; "); b.append("fill-opacity: ").append(getColorAlpha() * getAlpha()) .append("; "); String fontFamily = this.fontMapper.mapFont(this.font.getFamily()); b.append("font-family: ").append(fontFamily).append("; "); b.append("font-size: ").append(this.font.getSize()).append(this.fontSizeUnits).append(";"); if (this.font.isBold()) { b.append(" font-weight: bold;"); } if (this.font.isItalic()) { b.append(" font-style: italic;"); } return b.toString(); }
java
{ "resource": "" }
q166865
SVGGraphics2D.getFontMetrics
validation
@Override public FontMetrics getFontMetrics(Font f) { if (this.fmImage == null) { this.fmImage = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); this.fmImageG2D = this.fmImage.createGraphics(); this.fmImageG2D.setRenderingHint( RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); } return this.fmImageG2D.getFontMetrics(f); }
java
{ "resource": "" }
q166866
SVGGraphics2D.scale
validation
@Override public void scale(double sx, double sy) { AffineTransform t = getTransform(); t.scale(sx, sy); setTransform(t); }
java
{ "resource": "" }
q166867
SVGGraphics2D.transform
validation
@Override public void transform(AffineTransform t) { AffineTransform tx = getTransform(); tx.concatenate(t); setTransform(tx); }
java
{ "resource": "" }
q166868
SVGGraphics2D.setTransform
validation
@Override public void setTransform(AffineTransform t) { if (t == null) { this.transform = new AffineTransform(); } else { this.transform = new AffineTransform(t); } this.clipRef = null; }
java
{ "resource": "" }
q166869
SVGGraphics2D.setClip
validation
@Override public void setClip(Shape shape) { // null is handled fine here... this.clip = this.transform.createTransformedShape(shape); this.clipRef = null; }
java
{ "resource": "" }
q166870
SVGGraphics2D.registerClip
validation
private String registerClip(Shape clip) { if (clip == null) { this.clipRef = null; return null; } // generate the path String pathStr = getSVGPathData(new Path2D.Double(clip)); int index = this.clipPaths.indexOf(pathStr); if (index < 0) { this.clipPaths.add(pathStr); index = this.clipPaths.size() - 1; } return this.defsKeyPrefix + CLIP_KEY_PREFIX + index; }
java
{ "resource": "" }
q166871
SVGGraphics2D.clip
validation
@Override public void clip(Shape s) { if (s instanceof Line2D) { s = s.getBounds2D(); } if (this.clip == null) { setClip(s); return; } Shape ts = this.transform.createTransformedShape(s); if (!ts.intersects(this.clip.getBounds2D())) { setClip(new Rectangle2D.Double()); } else { Area a1 = new Area(ts); Area a2 = new Area(this.clip); a1.intersect(a2); this.clip = new Path2D.Double(a1); } this.clipRef = null; }
java
{ "resource": "" }
q166872
SVGGraphics2D.clipRect
validation
@Override public void clipRect(int x, int y, int width, int height) { setRect(x, y, width, height); clip(this.rect); }
java
{ "resource": "" }
q166873
SVGGraphics2D.setClip
validation
@Override public void setClip(int x, int y, int width, int height) { setRect(x, y, width, height); setClip(this.rect); }
java
{ "resource": "" }
q166874
SVGGraphics2D.getPNGBytes
validation
private byte[] getPNGBytes(Image img) { RenderedImage ri; if (img instanceof RenderedImage) { ri = (RenderedImage) img; } else { BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = bi.createGraphics(); g2.drawImage(img, 0, 0, null); ri = bi; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(ri, "png", baos); } catch (IOException ex) { Logger.getLogger(SVGGraphics2D.class.getName()).log(Level.SEVERE, "IOException while writing PNG data.", ex); } return baos.toByteArray(); }
java
{ "resource": "" }
q166875
SVGGraphics2D.drawRenderedImage
validation
@Override public void drawRenderedImage(RenderedImage img, AffineTransform xform) { BufferedImage bi = GraphicsUtils.convertRenderedImage(img); drawImage(bi, xform, null); }
java
{ "resource": "" }
q166876
SVGGraphics2D.drawRenderableImage
validation
@Override public void drawRenderableImage(RenderableImage img, AffineTransform xform) { RenderedImage ri = img.createDefaultRendering(); drawRenderedImage(ri, xform); }
java
{ "resource": "" }
q166877
SVGGraphics2D.getRadialGradientElement
validation
private String getRadialGradientElement(String id, RadialGradientPaint rgp) { StringBuilder b = new StringBuilder("<radialGradient id=\"").append(id) .append("\" gradientUnits=\"userSpaceOnUse\" "); Point2D center = rgp.getCenterPoint(); Point2D focus = rgp.getFocusPoint(); float radius = rgp.getRadius(); b.append("cx=\"").append(geomDP(center.getX())).append("\" "); b.append("cy=\"").append(geomDP(center.getY())).append("\" "); b.append("r=\"").append(geomDP(radius)).append("\" "); b.append("fx=\"").append(geomDP(focus.getX())).append("\" "); b.append("fy=\"").append(geomDP(focus.getY())).append("\">"); Color[] colors = rgp.getColors(); float[] fractions = rgp.getFractions(); for (int i = 0; i < colors.length; i++) { Color c = colors[i]; float f = fractions[i]; b.append("<stop offset=\"").append(geomDP(f * 100)).append("%\" "); b.append("stop-color=\"").append(rgbColorStr(c)).append("\""); if (c.getAlpha() < 255) { double alphaPercent = c.getAlpha() / 255.0; b.append(" stop-opacity=\"").append(transformDP(alphaPercent)) .append("\""); } b.append("/>"); } return b.append("</radialGradient>").toString(); }
java
{ "resource": "" }
q166878
SVGGraphics2D.getClipPathRef
validation
private String getClipPathRef() { if (this.clip == null) { return ""; } if (this.clipRef == null) { this.clipRef = registerClip(getClip()); } StringBuilder b = new StringBuilder(); b.append("clip-path=\"url(#").append(this.clipRef).append(")\""); return b.toString(); }
java
{ "resource": "" }
q166879
ViolationParserUtils.getParts
validation
public static List<String> getParts(String string, final String... regexpList) { final List<String> parts = new ArrayList<>(); for (final String regexp : regexpList) { final Pattern pattern = Pattern.compile(regexp); final Matcher matcher = pattern.matcher(string); final boolean found = matcher.find(); if (!found) { return new ArrayList<>(); } final String part = matcher.group(1).trim(); parts.add(part); string = string.replaceFirst(quote(matcher.group()), "").trim(); } return parts; }
java
{ "resource": "" }
q166880
BaseService.recordLevel
validation
protected void recordLevel(final String statKey, final long level) { final String longKey = getActualStatKey(statKey); statsCollector.recordLevel(longKey, level); }
java
{ "resource": "" }
q166881
BaseService.recordTiming
validation
protected void recordTiming(String statKey, long timeSpan) { final String longKey = getActualStatKey(statKey); statsCollector.recordTiming(longKey, timeSpan); }
java
{ "resource": "" }
q166882
ProxyServiceImpl.trackTimeouts
validation
private void trackTimeouts() { new ArrayList<>(httpRequestHolderList).forEach(httpRequestHolder -> { /* If it is handled then remove it from the list. */ if (httpRequestHolder.request.isHandled()) { httpRequestHolderList.remove(httpRequestHolder); return; } /* Get the duration that this request has been around. */ final long duration = time - httpRequestHolder.startTime; /* See if the duration is greater than the timeout time. */ if (duration > timeOutIntervalMS) { /* If we timed out, mark the request as handled, and then notify the client that the backend timed out. */ httpRequestHolder.request.handled(); /* Tell client that the backend timed out. */ httpRequestHolder.request.getReceiver().timeoutWithMessage(String.format("\"TIMEOUT %s %s %s\"", httpRequestHolder.request.address(), httpRequestHolder.request.getRemoteAddress(), httpRequestHolder.startTime )); /* If we timed out then remove this from the list. */ httpRequestHolderList.remove(httpRequestHolder); //Not very fast if you a lot of outstanding requests } }); }
java
{ "resource": "" }
q166883
ProxyServiceImpl.checkClient
validation
private void checkClient() { try { /** If the errorCount is greater than 0, make sure we are still connected. */ if (errorCount.get() > 0) { errorCount.set(0); if (backendServiceHttpClient == null || backendServiceHttpClient.isClosed()) { if (backendServiceHttpClient != null) { try { backendServiceHttpClient.stop(); } catch (Exception ex) { logger.debug("Was unable to stop the client connection", ex); } } backendServiceHttpClient = httpClientBuilder.buildAndStart(); lastHttpClientStart = time; } } /** If the ping builder is present, use it to ping the service. */ if (pingBuilder.isPresent()) { if (backendServiceHttpClient != null) { pingBuilder.get().setBinaryReceiver((code, contentType, body) -> { if (code >= 200 && code < 299) { pingCount.incrementAndGet(); } else { errorCount.incrementAndGet(); } }).setErrorHandler(e -> { logger.error("Error doing ping operation", e); errorCount.incrementAndGet(); }); final HttpRequest httpRequest = pingBuilder.get().build(); backendServiceHttpClient.sendHttpRequest(httpRequest); } } } catch (Exception ex) { errorHandler.accept(ex); logger.error("Unable to check connection"); } }
java
{ "resource": "" }
q166884
ProxyServiceImpl.handleRequest
validation
@Override public void handleRequest(final HttpRequest clientRequest) { if (trackTimeOuts) { httpRequestHolderList.add(new HttpRequestHolder(clientRequest, time)); } if (httpClientRequestPredicate.test(clientRequest)) { createBackEndRequestPopulateAndForward(clientRequest); } }
java
{ "resource": "" }
q166885
ProxyServiceImpl.createBackEndRequestPopulateAndForward
validation
private void createBackEndRequestPopulateAndForward(final HttpRequest clientRequest) { try { if (backendServiceHttpClient == null) { handleHttpClientErrorsForBackend(clientRequest, new HttpClientClosedConnectionException("Not connected")); long timeSinceLastStart = time - lastHttpClientStart; if (timeSinceLastStart > 10_000) { checkClient(); } return; } /* forward request to backend client. */ final HttpRequestBuilder httpRequestBuilder = HttpRequestBuilder.httpRequestBuilder() .copyRequest(clientRequest).setBinaryReceiver(new HttpBinaryReceiver() { @Override public void response(final int code, final String contentType, final byte[] body, final MultiMap<String, String> headers) { handleBackendClientResponses(clientRequest, code, contentType, body, headers); } @Override public void response(int code, String contentType, byte[] body) { response(code, contentType, body, MultiMap.empty()); } }).setErrorHandler(e -> handleHttpClientErrorsForBackend(clientRequest, e)); /** Give user of the lib a chance to populate headers and such. */ beforeSend.accept(httpRequestBuilder); backendServiceHttpClient.sendHttpRequest(httpRequestBuilder.build()); } catch (HttpClientClosedConnectionException httpClientClosedConnectionException) { errorCount.incrementAndGet(); errorHandler.accept(httpClientClosedConnectionException); logger.error("Unable to forward request", httpClientClosedConnectionException); handleHttpClientErrorsForBackend(clientRequest, httpClientClosedConnectionException); backendServiceHttpClient = null; long timeSinceLastStart = time - lastHttpClientStart; if (timeSinceLastStart > 10_000) { checkClient(); } } catch (Exception ex) { errorCount.incrementAndGet(); errorHandler.accept(ex); logger.error("Unable to forward request", ex); handleHttpClientErrorsForBackend(clientRequest, ex); long timeSinceLastStart = time - lastHttpClientStart; if (timeSinceLastStart > 10_000) { checkClient(); } } }
java
{ "resource": "" }
q166886
ProxyServiceImpl.handleHttpClientErrorsForBackend
validation
private void handleHttpClientErrorsForBackend(final HttpRequest clientRequest, final Exception e) { /* Notify error handler that we got an error. */ errorHandler.accept(e); /* Increment our error count. */ errorCount.incrementAndGet(); /* Create the error message. */ final String errorMessage = String.format("Unable to make request %s ", clientRequest.address()); /* Log the error. */ logger.error(errorMessage, e); /* Don't send the error to the client if we already handled this, i.e., timedout already. */ if (!clientRequest.isHandled()) { clientRequest.handled(); /* Notify the client that there was an error. */ clientRequest.getReceiver().error(String.format("\"%s\"", errorMessage)); } }
java
{ "resource": "" }
q166887
ProxyServiceImpl.handleBackendClientResponses
validation
private void handleBackendClientResponses(final HttpRequest clientRequest, final int code, final String contentType, final byte[] body, final MultiMap<String, String> headers) { /** If it is handled like it timed out already or some other error then don't do anything. */ if (!clientRequest.isHandled()) { /* If it was handled, let everyone know so we don't get a timeout. */ clientRequest.handled(); /* Send the response out the front end. */ clientRequest.getReceiver().response(code, contentType, body, headers); } }
java
{ "resource": "" }
q166888
ProxyServiceImpl.process
validation
@QueueCallback({QueueCallbackType.EMPTY, QueueCallbackType.IDLE, QueueCallbackType.LIMIT}) public void process() { reactor.process(); time = timer.time(); }
java
{ "resource": "" }
q166889
LokateServiceDiscoveryProvider.createLokateServiceDiscovery
validation
public static ServiceDiscovery createLokateServiceDiscovery(final List<URI> configs) { return serviceDiscoveryBuilder() .setServiceDiscoveryProvider( new LokateServiceDiscoveryProvider( DiscoveryService.create(configs))) .build(); }
java
{ "resource": "" }
q166890
ServiceBundleImpl.doCall
validation
private void doCall(MethodCall<Object> methodCall) { if (debug) { logger.debug(ServiceBundleImpl.class.getName(), "::doCall() ", methodCall.name(), methodCall.address(), "\n", methodCall); } try { if (methodCall.hasCallback()) { callbackManager.registerCallbacks(methodCall); } boolean[] continueFlag = new boolean[1]; methodCall = handleBeforeMethodCall(methodCall, continueFlag); if (!continueFlag[0]) { if (debug) { logger.debug(ServiceBundleImpl.class.getName() + "::doCall() " + "Flag from before call handling does not want to continue"); } } else { final Consumer<MethodCall<Object>> methodDispatcher = getMethodDispatcher(methodCall); methodDispatcher.accept(methodCall); } } catch (Exception ex) { Response<Object> response = new ResponseImpl<>(methodCall, ex); this.responseQueue.sendQueue().sendAndFlush(response); } }
java
{ "resource": "" }
q166891
ServiceBundleImpl.call
validation
@Override @SuppressWarnings("unchecked") public void call(final MethodCall<Object> methodCall) { if (debug) { logger.debug(ServiceBundleImpl.class.getName() + "::call() " + methodCall.name() + " " + " " + methodCall.address() + "\n" + methodCall); } methodSendQueue.send(methodCall); }
java
{ "resource": "" }
q166892
ServiceBundleImpl.createLocalProxy
validation
@Override public <T> T createLocalProxy(final Class<T> serviceInterface, final String myService) { final Consumer<MethodCall<Object>> callConsumer = this.serviceMapping.get(myService); if (callConsumer == null) { logger.error("Service requested does not exist " + myService); } return factory.createLocalProxy(serviceInterface, myService, this, beforeMethodSent); }
java
{ "resource": "" }
q166893
ServiceBundleImpl.beforeMethodCall
validation
private MethodCall<Object> beforeMethodCall(MethodCall<Object> methodCall, boolean[] continueCall) { if (this.beforeMethodCall.before(methodCall)) { continueCall[0] = true; methodCall = transformBeforeMethodCall(methodCall); continueCall[0] = this.beforeMethodCallAfterTransform.before(methodCall); return methodCall; } else { continueCall[0] = false; } return methodCall; }
java
{ "resource": "" }
q166894
ServiceBundleImpl.transformBeforeMethodCall
validation
private MethodCall<Object> transformBeforeMethodCall(MethodCall<Object> methodCall) { if (argTransformer == null || argTransformer == ServiceConstants.NO_OP_ARG_TRANSFORM) { return methodCall; } Object arg = this.argTransformer.transform(methodCall); return MethodCallBuilder.transformed(methodCall, arg); }
java
{ "resource": "" }
q166895
ServiceBundleImpl.stop
validation
@SuppressWarnings("Convert2streamapi") public void stop() { if (debug) { logger.debug(ServiceBundleImpl.class.getName(), "::stop()"); } methodQueue.stop(); for (Stoppable service : servicesToStop) { service.stop(); } try { responseQueue.stop(); } catch (Exception ex) { logger.debug("", ex); } try { webResponseQueue.stop(); } catch (Exception ex) { logger.debug("", ex); } if (systemManager != null) systemManager.serviceShutDown(); }
java
{ "resource": "" }
q166896
ServiceBundleImpl.startUpCallQueue
validation
public ServiceBundle startUpCallQueue() { methodQueue.startListener(new ReceiveQueueListener<MethodCall<Object>>() { long time; long lastTimeAutoFlush; /** * When we receive a method call, we call doCall. * @param item item */ @Override public void receive(MethodCall<Object> item) { doCall(item); //Do call calls forwardEvent but does not flush. Only when the queue is empty do we flush. } /** * If the queue is empty, then go ahead, and flush to each client all incoming requests every 50 milliseconds. */ @Override public void empty() { time = timer.now(); if (time > (lastTimeAutoFlush + 50)) { //noinspection Convert2streamapi for (SendQueue<MethodCall<Object>> sendQueue : sendQueues) { sendQueue.flushSends(); } lastTimeAutoFlush = time; } } }); return this; }
java
{ "resource": "" }
q166897
DnsSupport.findServiceName
validation
public String findServiceName(final String dnsServiceName) { String serviceName = dnsServiceNameToServiceName.get(dnsServiceName); serviceName = serviceName == null ? dnsServiceName : serviceName; if (debug) logger.debug("FindServiceName dnsServiceName={} serviceName={}", dnsServiceName, serviceName); return serviceName; }
java
{ "resource": "" }
q166898
DnsSupport.loadServiceEndpointsByServiceName
validation
public void loadServiceEndpointsByServiceName(final Callback<List<EndpointDefinition>> callback, final String serviceName) { loadServiceEndpointsByDNSService(callback, findDnsServiceName(serviceName)); }
java
{ "resource": "" }
q166899
DnsSupport.convertSrvRecordToEndpointDefinition
validation
private EndpointDefinition convertSrvRecordToEndpointDefinition(final SrvRecord srvRecord) { return new EndpointDefinition(findServiceName(srvRecord.service()), srvRecord.target(), srvRecord.port()); }
java
{ "resource": "" }