auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void selectGlobalTypeFilter(final Activity activity, final Action1<CacheType> okayListener) { final List<CacheType> cacheTypes = new ArrayList<>(); cacheTypes.add(CacheType.ALL); cacheTypes.add(CacheType.TRADITIONAL); cacheTypes.add(CacheType.MULTI); cacheTypes.add(CacheType.MYSTERY); final List<CacheType> sorted = new ArrayList<>(Arrays.asList(CacheType.values())); sorted.removeAll(cacheTypes); Collections.sort(sorted, new Comparator<CacheType>() { @Override public int compare(final CacheType left, final CacheType right) { return TextUtils.COLLATOR.compare(left.getL10n(), right.getL10n()); } }); cacheTypes.addAll(sorted); <START> int checkedItem = cacheTypes.indexOf(Settings.getCacheType()); <END> if (checkedItem < 0) { checkedItem = 0; } final String[] items = new String[cacheTypes.size()]; for (int i = 0; i < cacheTypes.size(); i++) { items[i] = cacheTypes.get(i).getL10n(); } final Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.menu_filter); builder.setSingleChoiceItems(items, checkedItem, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int position) { final CacheType cacheType = cacheTypes.get(position); Settings.setCacheType(cacheType); okayListener.call(cacheType); dialog.dismiss(); } }); builder.create().show(); }</code><technical_language>java final int checkedItem = Math.max(0, cacheTypes.indexOf(Settings.getCacheType()); convey intention more (IMO)</technical_language>

Target:
public static void selectGlobalTypeFilter(final Activity activity, final Action1<CacheType> okayListener) { final List<CacheType> cacheTypes = new ArrayList<>(); cacheTypes.add(CacheType.ALL); cacheTypes.add(CacheType.TRADITIONAL); cacheTypes.add(CacheType.MULTI); cacheTypes.add(CacheType.MYSTERY); final List<CacheType> sorted = new ArrayList<>(Arrays.asList(CacheType.values())); sorted.removeAll(cacheTypes); Collections.sort(sorted, new Comparator<CacheType>() { @Override public int compare(final CacheType left, final CacheType right) { return TextUtils.COLLATOR.compare(left.getL10n(), right.getL10n()); } }); cacheTypes.addAll(sorted); final int checkedItem = Math.max(0, cacheTypes.indexOf(Settings.getCacheType())); final String[] items = new String[cacheTypes.size()]; for (int i = 0; i < cacheTypes.size(); i++) { items[i] = cacheTypes.get(i).getL10n(); } final Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.menu_filter); builder.setSingleChoiceItems(items, checkedItem, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int position) { final CacheType cacheType = cacheTypes.get(position); Settings.setCacheType(cacheType); okayListener.call(cacheType); dialog.dismiss(); } }); builder.create().show(); }
Source:
<code>public TimeZone getTransactionTimeZone() { <START> String tzName = execConfig.get(String.class, "transaction_timezone", "UTC"); <END> return TimeZone.getTimeZone(tzName); }</code><technical_language>transaction_time_zone</technical_language>

Target:
public DateTimeZone getTransactionTimeZone() { return execConfig.get(DateTimeZone.class, "transaction_time_zone", DateTimeZone.UTC); }
Source:
<code><START> static void initProviderAsynchronously(@NonNull IProject project) { <END> synchronized (INSTANCE.projects) { if (INSTANCE.projects.contains(project)) { return; } INSTANCE.projects.add(project); } INSTANCE.schedule(); }</code><technical_language>* style nit: move static method beginning of class * visibility reduced private</technical_language>

Target:
private static void initProviderAsynchronously( @NonNull IProject project) { synchronized (INSTANCE.projects) { if (INSTANCE.projects.contains(project)) { return; } INSTANCE.projects.add(project); } INSTANCE.schedule(); }
Source:
<code><START> public IOpenShiftConnection getConnection(final String clientId, final String username, final String password, <END> final String authKey, final String authIV, final String serverUrl, final ISSLCertificateCallback sslCertificateCallback) throws OpenShiftException { return getConnection(clientId, username, password, authKey, authIV, serverUrl, sslCertificateCallback, createDHECipherExclusionRegex()); }</code><technical_language>is difference this getconnection other getconnections</technical_language>

Target:
public IOpenShiftConnection getConnection(final String clientId, final String username, final String password, final String authKey, final String authIV, final String serverUrl, final ISSLCertificateCallback sslCertificateCallback) throws OpenShiftException { return getConnection(clientId, username, password, authKey, authIV, serverUrl, sslCertificateCallback, createCipherExclusionRegex(getConfiguration())); }
Source:
<code>public static <T> List<T> safeGetList(Map map, String key, Class<T> type) { List<?> unchecked = safeGet(map, key, List.class); if (unchecked == null) { <START> return null; <END> } try { return (List<T>) unchecked.stream().map(type::cast).collect(Collectors.toList()); } catch (ClassCastException e) { LOGGER.debug(EXCEPTION_OCCURRED_PARSING, e); LOGGER.warn( "Form configuration field was malformed, expected a List containing type {}", key, type.getName()); } return null; }</code><technical_language>Return empty list instead of null (same for L77)</technical_language>

Target:
public static <T> List<T> safeGetList(Map map, String key, Class<T> type) { List<?> unchecked = safeGet(map, key, List.class); if (unchecked == null) { return Collections.emptyList(); } try { return (List<T>) unchecked.stream().map(type::cast).collect(Collectors.toList()); } catch (ClassCastException e) { LOGGER.debug(EXCEPTION_OCCURRED_PARSING, e); LOGGER.warn( "Form configuration field was malformed, expected a List containing type {}", key, type.getName()); } return Collections.emptyList(); }
Source:
<code>public String getLatestPatchSet() { <START> RevisionInfo topmost = getRevisionInfoByNumber(new Integer(fSelectedRevision.get_number()).toString()); <END> return topmost.getId(); }</code><technical_language>send latest patch set !</technical_language>

Target:
public String getLatestPatchSet() { EMap<String, RevisionInfo> revisions = fChangeInfo.getRevisions(); int topNumber = 0; for (Entry<String, RevisionInfo> entry : revisions.entrySet()) { if (entry.getValue().get_number() > topNumber) { topNumber = entry.getValue().get_number(); } } RevisionInfo topmost = getRevisionInfoByNumber(new Integer(topNumber).toString()); return topmost.getId(); }
Source:
<code>private Optional<Deadline> createOperationDeadline() { Deadline contextDeadline = Context.current().getDeadline(); if (contextDeadline != null) { return Optional.of(contextDeadline); } else if (useTimeout) { return Optional.of(Deadline.after(requestTimeoutMs, TimeUnit.MILLISECONDS)); } else { return Optional.absent(); <START> } <END> }</code><technical_language>minor code style improvement: java Deadline deadline = Optional.ofNullable(Context.current().getDeadline()); if (useTimeout) { deadline = deadline.or(Deadline.after(requestTimeoutMs, TimeUnit.MILLISECONDS)); } return deadline;</technical_language>

Target:
private Optional<Deadline> createOperationDeadline() { Optional<Deadline> deadline = Optional.fromNullable(Context.current().getDeadline()); if (useTimeout) { deadline = deadline.or(Optional.of(Deadline.after(requestTimeoutMs, TimeUnit.MILLISECONDS))); } return deadline; }
Source:
<code>private static void deleteFolderContents(IProject project, String folderName) { IFolder folder = project.getFolder(folderName); <START> class DeleteContents implements IResourceVisitor { @Override public boolean visit(IResource resource) throws CoreException { if (!folder.equals(resource)) { resource.delete(true, null); return false; } return true; } } if (folder.isAccessible()) { try { folder.accept(new DeleteContents()); } catch (CoreException e) { String message = "Failed to delete contents of folder " + folderName + " of project " + project.getName(); throw new AssertionError(message, e); } } <END> }</code><technical_language>folder.delete(true, null)</technical_language>

Target:
private static void deleteFolderContents(IProject project, String folderName) { try { IFolder folder = project.getFolder(folderName); folder.delete(true, null); folder.create(true, false, null); } catch (CoreException e) { throw new AssertionError("Failed to delete folder: " + folderName + " in project: " + project.getName(), e); } }
Source:
<code>public CommandCallback getCallback() { <START> return Injector.injectMembers(new ConcurrentChildCommandsExecutionCallback()); <END> }</code><technical_language>Instance</technical_language>

Target:
public CommandCallback getCallback() { return callbackProvider.get(); }
Source:
<code><START> public void setIgnoredPlayerTimeout(IUser user, long time) { <END> UUID uuid = user.getBase().getUniqueId(); System.out.println("UUID: " + uuid); System.out.println("Map: " + ignoredPlayerTimeouts); ignoredPlayerTimeouts.put(uuid, time); System.out.println("Map (final): " + ignoredPlayerTimeouts); setIgnoredPlayerTimeouts(ignoredPlayerTimeouts); }</code><technical_language>Style fix suggestion public void setIgnoredPlayerTimeout(IUser user, long time) {</technical_language>

Target:
public void setIgnoredPlayerTimeout(IUser user, long time) { UUID uuid = user.getBase().getUniqueId(); ignoredPlayerTimeouts.put(uuid, time); setIgnoredPlayerTimeouts(ignoredPlayerTimeouts); }
Source:
<code>public void complete() { if (completed || subscriber.isUnsubscribed()) { return; } try { super.complete(); if (getOutput() != null) { <START> if (getOutput().hasError()) { <END> subscriber.onError(new RedisCommandExecutionException(getOutput().getError())); completed = true; return; } Object result = getOutput().get(); if (!(getOutput() instanceof StreamingOutput<?>) && result != null) { if (dissolve && result instanceof Collection) { Collection<T> collection = (Collection<T>) result; for (T t : collection) { subscriber.onNext(t); } } else { subscriber.onNext((T) result); } } } subscriber.onCompleted(); } finally { completed = true; } }</code><technical_language>block before. idea is emit items arrived error occurred terminate a call onError. Streaming output behave non-streaming outputs longer emit items terminate directly</technical_language>

Target:
public void complete() { if (completed || subscriber.isUnsubscribed()) { return; } try { super.complete(); if (getOutput() != null) { Object result = getOutput().get(); if (!(getOutput() instanceof StreamingOutput<?>) && result != null) { if (dissolve && result instanceof Collection) { Collection<T> collection = (Collection<T>) result; for (T t : collection) { subscriber.onNext(t); } } else { subscriber.onNext((T) result); } } if (getOutput().hasError()) { subscriber.onError(new RedisCommandExecutionException(getOutput().getError())); completed = true; return; } } subscriber.onCompleted(); } finally { completed = true; } }
Source:
<code>public void should_work_and_log_warning_when_deprecated_key() throws Exception { <START> settings.setProperty(JavaScriptPlugin.TS_LCOV_REPORT_PATHS, UT_LCOV + ", " + IT_LCOV); <END> coverageSensor.execute(context); testTwoFilesContext(); assertThat(logTester.logs(LoggerLevel.WARN)).contains("The use of sonar.typescript.lcov.reportPaths for coverage import is deprecated, use sonar.javascript.lcov.reportPaths instead!"); }</code><technical_language>test case report is mentioned in typescript property</technical_language>

Target:
public void should_work_and_log_warning_when_deprecated_key() throws Exception { settings.setProperty(JavaScriptPlugin.LCOV_REPORT_PATHS, ""); settings.setProperty(JavaScriptPlugin.TS_LCOV_REPORT_PATHS, TWO_REPORTS); coverageSensor.execute(context); assertTwoReportsCoverageDataPresent(); assertThat(logTester.logs(LoggerLevel.WARN)).contains(DEPRECATED_MESSAGE); }
Source:
<code>private void checkChangedField(AllTypes allTypes, final String... fieldNames) { assertNotNull(fieldNames); allTypes.addChangeListener(new RealmObjectChangeListener<RealmModel>() { @Override public void onChange(RealmModel object, ObjectChangeSet changeSet) { assertEquals(fieldNames.length, changeSet.getChangedFields().length); for (String name : fieldNames) { assertTrue(changeSet.isFieldChanged(name)); assertFalse(changeSet.isFieldChanged(name + "NotThere")); for (String field : changeSet.getChangedFields()) { if (field.equals(name)) { break; } <START> fail("Cannot find field " + name + " in field changes."); <END> } } looperThread.testComplete(); } }); looperThread.keepStrongReference.add(allTypes); }</code><technical_language>fail for-loop? current impl runs 1 iteration (either exit break fail)</technical_language>

Target:
private void checkChangedField(AllTypes allTypes, final String... fieldNames) { assertNotNull(fieldNames); allTypes.addChangeListener(new RealmObjectChangeListener<RealmModel>() { @Override public void onChange(RealmModel object, ObjectChangeSet changeSet) { assertEquals(fieldNames.length, changeSet.getChangedFields().length); List<String> changedFields = Arrays.asList(changeSet.getChangedFields()); for (String name : fieldNames) { assertTrue(changeSet.isFieldChanged(name)); assertFalse(changeSet.isFieldChanged(name + "NotThere")); if (!changedFields.contains(name)) { fail("Cannot find field " + name + " in field changes."); } } looperThread.testComplete(); } }); looperThread.keepStrongReference.add(allTypes); }
Source:
<code>private Response handleSaveRole(SecurityRole securityRole, boolean post) { ValidationResult validationResult = securityRole.validate(); if (post) { validationResult.merge(service.getSecurityService().validateSecurityRoleName(securityRole.getRoleName())); } if (validationResult.valid()) { SecurityRole savedRole = service.getSecurityService().saveSecurityRole(securityRole); if (post) { <START> return Response.created(URI.create("v1/resource/securityroles")).entity(savedRole).build(); <END> } else { return Response.ok(savedRole).build(); } } else { return Response.ok(validationResult.toRestError()).build(); } }</code><technical_language>I this ok get encoded. point newly created role</technical_language>

Target:
private Response handleSaveRole(SecurityRole securityRole, boolean post) { ValidationResult validationResult = securityRole.validate(); if (post) { validationResult.merge(service.getSecurityService().validateSecurityRoleName(securityRole.getRoleName())); } if (validationResult.valid()) { SecurityRole savedRole = service.getSecurityService().saveSecurityRole(securityRole); if (post) { return Response.created(URI.create("v1/resource/securityroles/" + URLEncoder.encode(savedRole.getRoleName()))).entity(savedRole).build(); } else { return Response.ok(savedRole).build(); } } else { return Response.ok(validationResult.toRestError()).build(); } }
Source:
<code>private void setPendingStatusesToAllEligibleTasks(List<EligibleTaskDescriptor> eligibleTasks) { List<EligibleTaskDescriptorImpl> notPendingYet = eligibleTasks.stream() .map(task -> (EligibleTaskDescriptorImpl) task) .filter(task -> !task.getInternal() .getStatus() .equals(TaskStatus.PENDING)) .collect(Collectors.toList()); notPendingYet.forEach(task -> { if (task.getInternal().getScheduledTime() == -1) { task.getInternal().setScheduledTime(System.currentTimeMillis()); } task.getInternal().setStatus(TaskStatus.PENDING); }); notPendingYet.forEach(task -> { getDBManager().updateTaskStatus(task, TaskStatus.PENDING); getDBManager().updateScheduledTime(task.getJobId().longValue(), task.getTaskId().longValue(), <START> task.getInternal().getScheduledTime()); <END> }); }</code><technical_language>generate 2 transactions, making operation non-atomic. I aggregate this in a single transaction if</technical_language>

Target:
private void setPendingStatusesToAllEligibleTasks(List<EligibleTaskDescriptor> eligibleTasks) { List<EligibleTaskDescriptorImpl> notPendingYet = eligibleTasks.stream() .map(task -> (EligibleTaskDescriptorImpl) task) .filter(task -> !task.getInternal() .getStatus() .equals(TaskStatus.PENDING)) .collect(Collectors.toList()); notPendingYet.forEach(task -> { if (task.getInternal().getScheduledTime() == -1) { task.getInternal().setScheduledTime(System.currentTimeMillis()); } task.getInternal().setStatus(TaskStatus.PENDING); }); notPendingYet.forEach(task -> { getDBManager().updateTaskStatusAndScheduledTime(task, TaskStatus.PENDING, task.getInternal().getScheduledTime()); }); }
Source:
<code>private void filterValues(String filterRaw, boolean synchronous) { synchronized(mSyncLock) { if(mCurrentSortThread != null) { mCurrentSortThread.finish(); } <START> String[] searchTerms = filterRaw.split(" "); <END> for(int i = 0 ; i < searchTerms.length ; ++i) { searchTerms[i] = StringUtils.normalize(searchTerms[i]); } mCurrentSortThread = new EntitySearcher(filterRaw, searchTerms); mCurrentSortThread.startThread(); if(synchronous) { try { mCurrentSortThread.thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } }</code><technical_language>Safer split \w+</technical_language>

Target:
private void filterValues(String filterRaw, boolean synchronous) { synchronized(mSyncLock) { if(mCurrentSortThread != null) { mCurrentSortThread.finish(); } String[] searchTerms = filterRaw.split("\\s+"); for(int i = 0 ; i < searchTerms.length ; ++i) { searchTerms[i] = StringUtils.normalize(searchTerms[i]); } mCurrentSortThread = new EntitySearcher(filterRaw, searchTerms); mCurrentSortThread.startThread(); if(synchronous) { try { mCurrentSortThread.thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
Source:
<code>public void fill(Composite parent) { <START> if (!checkWidget(parent)) { <END> return; } int flags = SWT.PUSH; if (action != null) { if (action.getStyle() == IAction.AS_CHECK_BOX) { flags = SWT.TOGGLE; } if (action.getStyle() == IAction.AS_RADIO_BUTTON) { flags = SWT.RADIO; } } Button b = new Button(parent, flags); b.setData(this); b.addListener(SWT.Dispose, getButtonListener()); b.addListener(SWT.Selection, getButtonListener()); if (action.getHelpListener() != null) { b.addHelpListener(action.getHelpListener()); } widget = b; update(null); action.addPropertyChangeListener(propertyListener); if (action != null) { String commandId = action.getActionDefinitionId(); ExternalActionManager.ICallback callback = ExternalActionManager.getInstance().getCallback(); if ((callback != null) && (commandId != null)) { callback.addPropertyChangeListener(commandId, actionTextListener); } } }</code><technical_language>I find this highly confusing. "checkWidget" left puzzled -- check a widget if create it? wait, checking parent. checkWidget checks widget == null... clearer if condition simply inlined: if (widget != null || parent == null) { return; } a reader understand this right away: "ah yes, if created widget is parent, do anything"</technical_language>

Target:
public void fill(Composite parent) { if (widget != null || parent == null) { return; } int flags = SWT.PUSH; if (action != null) { if (action.getStyle() == IAction.AS_CHECK_BOX) { flags = SWT.TOGGLE; } if (action.getStyle() == IAction.AS_RADIO_BUTTON) { flags = SWT.RADIO; } } Button b = new Button(parent, flags); b.setData(this); b.addListener(SWT.Dispose, getButtonListener()); b.addListener(SWT.Selection, getButtonListener()); if (action.getHelpListener() != null) { b.addHelpListener(action.getHelpListener()); } widget = b; update(null); action.addPropertyChangeListener(propertyListener); if (action != null) { String commandId = action.getActionDefinitionId(); ExternalActionManager.ICallback callback = ExternalActionManager.getInstance().getCallback(); if ((callback != null) && (commandId != null)) { callback.addPropertyChangeListener(commandId, actionTextListener); } } }
Source:
<code>private void scheduleManagerUpdate(IContributionManager mgr) { <START> boolean workaroundEnabled = Boolean.getBoolean(ECLIPSE_WORKAROUND_BUG467000); <END> if (!workaroundEnabled) { mgr.update(false); return; } synchronized (mgrToUpdate) { if (this.mgrToUpdate.isEmpty()) { Display display = context.get(Display.class); if (display != null && !display.isDisposed()) { display.timerExec(100, new Runnable() { @Override public void run() { Collection<IContributionManager> toUpdate = new LinkedHashSet<>(); synchronized (mgrToUpdate) { toUpdate.addAll(mgrToUpdate); mgrToUpdate.clear(); } for (IContributionManager mgr : toUpdate) { mgr.update(false); } } }); } this.mgrToUpdate.add(mgr); } } }</code><technical_language>a constant ;-)</technical_language>

Target:
private void scheduleManagerUpdate(IContributionManager mgr) { if (!ECLIPSE_WORKAROUND_BUG467000) { mgr.update(false); return; } synchronized (mgrToUpdate) { if (this.mgrToUpdate.isEmpty()) { Display display = context.get(Display.class); if (display != null && !display.isDisposed()) { display.timerExec(100, new Runnable() { @Override public void run() { Collection<IContributionManager> toUpdate = new LinkedHashSet<>(); synchronized (mgrToUpdate) { toUpdate.addAll(mgrToUpdate); mgrToUpdate.clear(); } for (IContributionManager mgr : toUpdate) { mgr.update(false); } } }); } this.mgrToUpdate.add(mgr); } } }
Source:
<code><START> public void testStarvationDetected() throws Exception { <END> final int stripeIdx = 0; stripedExecSvc.execute(stripeIdx, new TestRunnable(true)); assertFalse(GridTestUtils.waitForCondition(() -> stripedExecSvc.activeStripesCount() == 0, 3000)); stripedExecSvc.execute(stripeIdx, new TestRunnable()); assertTrue(GridTestUtils.waitForCondition(() -> stripedExecSvc.activeStripesCount() == 1, 10000)); assertTrue(stripedExecSvc.isStarvationDetected()); }</code><technical_language>this test is flaky. fail for 1st time fail for 2nd run</technical_language>

Target:
public void testStarvationDetected() throws Exception { final int stripeIdx = 0; stripedExecSvc.execute(stripeIdx, new TestRunnable(true)); sleepASec(); assertFalse(GridTestUtils.waitForCondition(() -> stripedExecSvc.activeStripesCount() == 0, 2000)); stripedExecSvc.execute(stripeIdx, new TestRunnable()); assertTrue(GridTestUtils.waitForCondition(() -> stripedExecSvc.activeStripesCount() == 1, 10000)); assertTrue(stripedExecSvc.detectStarvation()); }
Source:
<code>protected void parse() { enabled = getBooleanFromConfig(ENABLED, true); uiEnabled = getBooleanFromConfig(UI_ENABLED, true); secureOnly = getBooleanFromConfig(SECURE_ONLY, false); disableKey = getBooleanFromConfig(DISABLE_KEY, false); incErrorDetails = getBooleanFromConfig(INC_ERROR_DETAILS, false); autofillKey = getBooleanFromConfig(AUTOFILL_KEY, false); enableJSONP = getBooleanFromConfig(ENABLE_JSONP, false); noKeyForViews = getBooleanFromConfig(NO_KEY_FOR_VIEWS, false); reportPermErrors = getBooleanFromConfig(REPORT_PERM_ERRORS, false); <START> nonceTimeToLiveInSecs = getIntFromConfig(NONCE_TTL_IN_SECS, 5000); <END> try { key = getConfig().getString(API_KEY, ""); } catch (ConversionException e) { LOGGER.warn("Failed to load the option '" + key + "' caused by:", e); key = ""; } loadPermittedAddresses(); try { this.confirmRemovePermittedAddress = getConfig().getBoolean(CONFIRM_REMOVE_EXCLUDED_DOMAIN, true); } catch (ConversionException e) { LOGGER.error("Error while loading the confirm remove permitted address option: " + e.getMessage(), e); } }</code><technical_language>5 (seconds)</technical_language>

Target:
protected void parse() { enabled = getBooleanFromConfig(ENABLED, true); uiEnabled = getBooleanFromConfig(UI_ENABLED, true); secureOnly = getBooleanFromConfig(SECURE_ONLY, false); disableKey = getBooleanFromConfig(DISABLE_KEY, false); incErrorDetails = getBooleanFromConfig(INC_ERROR_DETAILS, false); autofillKey = getBooleanFromConfig(AUTOFILL_KEY, false); enableJSONP = getBooleanFromConfig(ENABLE_JSONP, false); noKeyForSafeOps = getBooleanFromConfig(NO_KEY_FOR_SAFE_OPS, false); reportPermErrors = getBooleanFromConfig(REPORT_PERM_ERRORS, false); nonceTimeToLiveInSecs = getIntFromConfig(NONCE_TTL_IN_SECS, DEFAULT_NONCE_TTL_IN_SECS); try { key = getConfig().getString(API_KEY, ""); } catch (ConversionException e) { LOGGER.warn("Failed to load the option '" + key + "' caused by:", e); key = ""; } loadPermittedAddresses(); try { this.confirmRemovePermittedAddress = getConfig().getBoolean(CONFIRM_REMOVE_EXCLUDED_DOMAIN, true); } catch (ConversionException e) { LOGGER.error("Error while loading the confirm remove permitted address option: " + e.getMessage(), e); } }
Source:
<code>public boolean verifyToken(JWT token, RSAPublicKey publicKey) throws TokenServiceException { boolean rc; PublicKey key; try { if (publicKey == null) { <START> key = ks.getSigningKeystore().getCertificate(getSigningKeyAlias(null)).getPublicKey(); <END> } else { key = publicKey; } JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) key); rc = token.verify(verifier); } catch (KeyStoreException | KeystoreServiceException e) { throw new TokenServiceException("Cannot verify token.", e); } return rc; }</code><technical_language>Is null correct here? weird..</technical_language>

Target:
public boolean verifyToken(JWT token, RSAPublicKey publicKey) throws TokenServiceException { boolean rc; PublicKey key; try { if (publicKey == null) { key = ks.getSigningKeystore().getCertificate(getSigningKeyAlias()).getPublicKey(); } else { key = publicKey; } JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) key); rc = token.verify(verifier); } catch (KeyStoreException | KeystoreServiceException e) { throw new TokenServiceException("Cannot verify token.", e); } return rc; }
Source:
<code>public void start(final BundleContext bundleContext) { WebAppConfigurationService webAppConfigurationService = new WebAppConfigurationDataHolder(); bundleContext.registerService(WebAppConfigurationService.class.getName(), webAppConfigurationService, null); <START> log.debug("WebappConfigService was registered!"); <END> if (!CarbonUtils.isRunningInStandaloneMode()) { Thread th = new Thread() { public void run() { try { bundleContext.getBundle().uninstall(); } catch (Throwable e) { log.warn("Error occurred while uninstalling webapp-mgt UI bundle", e); } } }; try { th.join(); } catch (InterruptedException ignored) { } th.start(); } }</code><technical_language>need check debug is enabled</technical_language>

Target:
public void start(final BundleContext bundleContext) { WebAppConfigurationService webAppConfigurationService = new WebAppConfigurationDataHolder(); bundleContext.registerService(WebAppConfigurationService.class.getName(), webAppConfigurationService, null); if (log.isDebugEnabled()) { log.debug("WebappConfigService was registered!"); } if (!CarbonUtils.isRunningInStandaloneMode()) { Thread th = new Thread() { public void run() { try { bundleContext.getBundle().uninstall(); } catch (Throwable e) { log.warn("Error occurred while uninstalling webapp-mgt UI bundle", e); } } }; try { th.join(); } catch (InterruptedException ignored) { } th.start(); } }
Source:
<code>public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if (maxConnections > 0) { if (numConnections.incrementAndGet() > maxConnections) { ctx.getChannel().close(); <START> numConnections.decrementAndGet(); <END> log.info("Accepted connection above limit ({}). Dropping.", maxConnections); } } super.channelOpen(ctx, e); }</code><technical_language>this a double-decrement</technical_language>

Target:
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if (maxConnections > 0) { if (numConnections.incrementAndGet() > maxConnections) { ctx.getChannel().close(); log.info("Accepted connection above limit ({}). Dropping.", maxConnections); } } super.channelOpen(ctx, e); }
Source:
<code>private Stream<VirtualMachineLease> groupEvaluator(Set<VirtualMachineLease> groupCandidates) { Map<VirtualMachineLease, Double> scores = new HashMap<>(); scoringEvaluators.forEach(e -> { Optional<? super Object> optionalContext = Optional.empty(); for (VirtualMachineLease lease : groupCandidates) { double currentScore = scores.getOrDefault(lease, 0.0); if (currentScore != NOT_REMOVABLE_MARKER) { ScaleDownConstraintEvaluator.Result result = e.evaluate(lease, optionalContext); double newScore = result.getScore(); if (newScore == 0) { scores.put(lease, NOT_REMOVABLE_MARKER); } else { <START> scores.put(lease, currentScore + newScore); <END> } optionalContext = result.getContext(); } } }); return scores.entrySet().stream() .filter(e -> e.getValue() != NOT_REMOVABLE_MARKER) .sorted((e1, e2) -> Double.compare(e2.getValue(), e1.getValue())) .map(Map.Entry::getKey); }</code><technical_language>This evaluators treated equal. wanted weights for combining scores. done here</technical_language>

Target:
private Stream<VirtualMachineLease> groupEvaluator(Set<VirtualMachineLease> groupCandidates) { Map<VirtualMachineLease, Double> scores = new HashMap<>(); scoringEvaluators.forEach((e, weight) -> { Optional<? super Object> optionalContext = Optional.empty(); for (VirtualMachineLease lease : groupCandidates) { double currentScore = scores.getOrDefault(lease, 0.0); if (currentScore != NOT_REMOVABLE_MARKER) { ScaleDownConstraintEvaluator.Result result = e.evaluate(lease, optionalContext); double newScore = result.getScore() * weight; if (newScore == 0) { scores.put(lease, NOT_REMOVABLE_MARKER); } else { scores.put(lease, currentScore + newScore); } optionalContext = result.getContext(); } } }); return scores.entrySet().stream() .filter(e -> e.getValue() != NOT_REMOVABLE_MARKER) .sorted((e1, e2) -> Double.compare(e2.getValue(), e1.getValue())) .map(Map.Entry::getKey); }
Source:
<code>private Iterable<String> createSinglyIterable(final List<String> values) { return new Iterable<String>() { private boolean isIteratorCreated = false; @Override public Iterator<String> iterator() { if (isIteratorCreated) throw new IllegalArgumentException("Cannot create two iterators on a singly-iterable sequence"); isIteratorCreated = true; return new Iterator<String>() { <START> private final Iterator<String> l_it = values.iterator(); <END> @Override public boolean hasNext() { return l_it.hasNext(); } @Override public String next() { return l_it.next(); } }; } }; }</code><technical_language>rename listIterator</technical_language>

Target:
private Iterable<String> createSinglyIterable(final List<String> values) { return new Iterable<String>() { private boolean isIteratorCreated = false; @Override public Iterator<String> iterator() { if (isIteratorCreated) throw new IllegalArgumentException("Cannot create two iterators on a singly-iterable sequence"); isIteratorCreated = true; return new Iterator<String>() { private final Iterator<String> listIterator = values.iterator(); @Override public boolean hasNext() { return listIterator.hasNext(); } @Override public String next() { return listIterator.next(); } }; } }; }
Source:
<code>public AmbryRequests(StorageManager storageManager, RequestResponseChannel requestResponseChannel, ClusterMap clusterMap, DataNodeId nodeId, MetricRegistry registry, FindTokenFactory findTokenFactory, NotificationSystem operationNotification, ReplicationManager replicationManager, StoreKeyFactory storeKeyFactory) { this.storageManager = storageManager; this.requestResponseChannel = requestResponseChannel; this.clusterMap = clusterMap; this.currentNode = nodeId; this.metrics = new ServerMetrics(registry); this.messageFormatMetrics = new MessageFormatMetrics(registry); this.findTokenFactory = findTokenFactory; this.notification = operationNotification; this.replicationManager = replicationManager; this.storeKeyFactory = storeKeyFactory; requestsDisableInfo.put(RequestOrResponseType.PutRequest, Collections.newSetFromMap(new ConcurrentHashMap<>())); requestsDisableInfo.put(RequestOrResponseType.GetRequest, Collections.newSetFromMap(new ConcurrentHashMap<>())); requestsDisableInfo.put(RequestOrResponseType.DeleteRequest, Collections.newSetFromMap(new ConcurrentHashMap<>())); requestsDisableInfo.put(RequestOrResponseType.ReplicaMetadataRequest, Collections.newSetFromMap(new ConcurrentHashMap<>())); Set<PartitionId> partitionIds = new HashSet<>(); for (ReplicaId replicaId : clusterMap.getReplicaIds(currentNode)) { partitionIds.add(replicaId.getPartitionId()); } <START> partitionsInCurrentNode = Collections.unmodifiableList(new ArrayList<>(partitionIds)); <END> }</code><technical_language>Is for this remain a Collection/Set instead of copied a List? I a methods in this class in List rely iterable (I missed something, though)</technical_language>

Target:
public AmbryRequests(StorageManager storageManager, RequestResponseChannel requestResponseChannel, ClusterMap clusterMap, DataNodeId nodeId, MetricRegistry registry, FindTokenFactory findTokenFactory, NotificationSystem operationNotification, ReplicationManager replicationManager, StoreKeyFactory storeKeyFactory) { this.storageManager = storageManager; this.requestResponseChannel = requestResponseChannel; this.clusterMap = clusterMap; this.currentNode = nodeId; this.metrics = new ServerMetrics(registry); this.messageFormatMetrics = new MessageFormatMetrics(registry); this.findTokenFactory = findTokenFactory; this.notification = operationNotification; this.replicationManager = replicationManager; this.storeKeyFactory = storeKeyFactory; requestsDisableInfo.put(RequestOrResponseType.PutRequest, Collections.newSetFromMap(new ConcurrentHashMap<>())); requestsDisableInfo.put(RequestOrResponseType.GetRequest, Collections.newSetFromMap(new ConcurrentHashMap<>())); requestsDisableInfo.put(RequestOrResponseType.DeleteRequest, Collections.newSetFromMap(new ConcurrentHashMap<>())); requestsDisableInfo.put(RequestOrResponseType.ReplicaMetadataRequest, Collections.newSetFromMap(new ConcurrentHashMap<>())); Set<PartitionId> partitionIds = new HashSet<>(); for (ReplicaId replicaId : clusterMap.getReplicaIds(currentNode)) { partitionIds.add(replicaId.getPartitionId()); } partitionsInCurrentNode = Collections.unmodifiableSet(partitionIds); }
Source:
<code>private String describeNote() { <START> return String.join("\n", this.notes); <END> }</code><technical_language>exception of constructors, non-static classes setters this key word needed</technical_language>

Target:
private String describeNote() { return String.join("\n", notes); }
Source:
<code>void gc() { LOG.info("Starting garbage collecting ledger storage."); <START> LOG.info("Garbage collecting deleted ledgers' index files."); <END> doGcLedgers(); LOG.info("Scanning entry log files to extract metadata and delete empty entry logs if possible."); entryLogMetaMap = extractMetaFromEntryLogs(entryLogMetaMap); if (!running) { return; } LOG.info("Garbage collecting deleted ledgers' index files again just in case ledgers deleted during scanning."); doGcLedgers(); LOG.info("Garbage collecting empty entry log files."); doGcEntryLogs(); }</code><technical_language>this method is job. log.info for entire GC good enough; others downgraded LOG.debug()</technical_language>

Target:
void gc() { LOG.debug("Starting garbage collecting ledger storage."); LOG.debug("Garbage collecting deleted ledgers' index files."); doGcLedgers(); Stopwatch scanStopwatch = new Stopwatch(); scanStopwatch.start(); LOG.debug("Scanning entry log files to extract metadata and delete empty entry logs if possible."); entryLogMetaMap = extractMetaFromEntryLogs(entryLogMetaMap); if (!running) { return; } long elapsedTimeOnScan = scanStopwatch.elapsedMillis(); if (elapsedTimeOnScan >= gcWaitTime) { LOG.debug("Garbage collecting deleted ledgers' index files again just in case ledgers deleted during scanning."); doGcLedgers(); } LOG.debug("Garbage collecting empty entry log files."); doGcEntryLogs(); }
Source:
<code>public void downloadLanguagesFromServer() throws Exception { try { if (BuildConfig.downloadLanguagesFromServer) { Log.i(TAG, "Starting to download Languages From Server"); CredentialsReader credentialsReader = CredentialsReader.getInstance(); IConnectivityManager connectivity = NetworkManagerFactory.getConnectivityManager( activity); ISettingsRepository settingsRepository = new SettingsDataSource(activity); <START> DownloadLanguageTranslationUseCase downloader = <END> new DownloadLanguageTranslationUseCase(credentialsReader, connectivity, settingsRepository); downloader.download(); } } catch (Exception e) { Log.e(TAG, "Unable to download Languages From Server" + e.getMessage()); e.printStackTrace(); showToast(R.string.error_downloading_languages, e); } }</code><technical_language>Pass settingsRepository argument DownloadLanguageTranslationUseCase is necessary</technical_language>

Target:
public void downloadLanguagesFromServer() throws Exception { try { if (BuildConfig.downloadLanguagesFromServer) { Log.i(TAG, "Starting to download Languages From Server"); CredentialsReader credentialsReader = CredentialsReader.getInstance(); IConnectivityManager connectivity = NetworkManagerFactory.getConnectivityManager( activity); DownloadLanguageTranslationUseCase downloader = new DownloadLanguageTranslationUseCase(credentialsReader, connectivity); downloader.download(); } } catch (Exception e) { Log.e(TAG, "Unable to download Languages From Server" + e.getMessage()); e.printStackTrace(); showToast(R.string.error_downloading_languages, e); } }
Source:
<code><START> public LeaderElector getLeaderElector() { <END> return null; }</code><technical_language>is this returning null? return AzureLeaderElector</technical_language>

Target:
public LeaderElector getLeaderElector() throws UnsupportedOperationException { return null; }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Pb("); <START> sb.append((this.id & IProblem.IgnoreCategoriesMask)); <END> sb.append(") "); if (this.message != null) { sb.append(this.message); } else { if (this.arguments != null) { for (int i = 0; i < this.arguments.length; i++) { sb.append(" "); sb.append(this.arguments[i]); } } } return sb.toString(); }</code><technical_language>need extra brackets</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Pb("); sb.append(this.id & IProblem.IgnoreCategoriesMask); sb.append(") "); if (this.message != null) { sb.append(this.message); } else { if (this.arguments != null) { for (int i = 0; i < this.arguments.length; i++) { sb.append(" "); sb.append(this.arguments[i]); } } } return sb.toString(); }
Source:
<code>public void should_cleanup_on_lbp_init_failure() { DriverConfigLoader loader = SessionUtils.configLoaderBuilder() .without(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER) <START> .withClass( <END> DefaultDriverOption.LOAD_BALANCING_POLICY_CLASS, DefaultLoadBalancingPolicy.class) .build(); assertThatThrownBy( () -> CqlSession.builder() .addContactEndPoints(SIMULACRON_RULE.getContactPoints()) .withConfigLoader(loader) .build()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining( "Since you provided explicit contact points, the local DC must be explicitly set"); checkThat(() -> SIMULACRON_RULE.cluster().getConnections().getConnections().isEmpty()) .before(1, SECONDS) .becomesTrue(); }</code><technical_language>This force DSE driver OSS LBP. I instead this test work DSE driver default LBP (DseLoadBalancingPolicy). I do this incriminated test is creating a hard-coded CqlSession line 137. This changed SessionUtils.baseBuilder()</technical_language>

Target:
public void should_cleanup_on_lbp_init_failure() { DriverConfigLoader loader = SessionUtils.configLoaderBuilder() .without(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER) .build(); assertThatThrownBy( () -> SessionUtils.baseBuilder() .addContactEndPoints(SIMULACRON_RULE.getContactPoints()) .withConfigLoader(loader) .build()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining( "Since you provided explicit contact points, the local DC must be explicitly set"); checkThat(() -> SIMULACRON_RULE.cluster().getConnections().getConnections().isEmpty()) .before(1, SECONDS) .becomesTrue(); }
Source:
<code>public void onDisconnectHandler(PlayerList this$0, ITextComponent component) { if (this.player.connection == null) { return; } final Player player = ((Player) this.player); final Text message = SpongeTexts.toText(component); final MessageChannel originalChannel = player.getMessageChannel(); final ClientConnectionEvent.Disconnect event = SpongeEventFactory.createClientConnectionEventDisconnect( Cause.of(NamedCause.source(player)), originalChannel, Optional.of(originalChannel), new MessageEvent.MessageFormatter(message), player, false ); SpongeImpl.postEvent(event); if (!event.isMessageCancelled()) { event.getChannel().ifPresent(channel -> channel.send(player, event.getMessage())); } <START> ((MixinEntityPlayerMP) (Object) this.player).borderListener.onPlayerDisconnect(); <END> }</code><technical_language>here, this cast work. need expose additional interface (check org.spongepowered.common.interfaces for some examples)</technical_language>

Target:
public void onDisconnectHandler(PlayerList this$0, ITextComponent component) { if (this.player.connection == null) { return; } final Player player = ((Player) this.player); final Text message = SpongeTexts.toText(component); final MessageChannel originalChannel = player.getMessageChannel(); final ClientConnectionEvent.Disconnect event = SpongeEventFactory.createClientConnectionEventDisconnect( Cause.of(NamedCause.source(player)), originalChannel, Optional.of(originalChannel), new MessageEvent.MessageFormatter(message), player, false ); SpongeImpl.postEvent(event); if (!event.isMessageCancelled()) { event.getChannel().ifPresent(channel -> channel.send(player, event.getMessage())); } ((IMixinEntityPlayerMP) this.player).getWorldBorderListener().onPlayerDisconnect(); }
Source:
<code>private static ImmutableList<Arguments> getRequiredArgs(final Ds3Request ds3Request) { final ImmutableList.Builder<Arguments> requiredArgsBuilder = ImmutableList.builder(); LOG.debug("Getting required args..."); if (ds3Request.getBucketRequirement() == Requirement.REQUIRED) { LOG.debug("bucket name REQUIRED."); requiredArgsBuilder.add(new Arguments("String", "bucketName")); if (ds3Request.getObjectRequirement() == Requirement.REQUIRED) { <START> LOG.debug("bucket name REQUIRED."); <END> requiredArgsBuilder.add(new Arguments("String", "objectName")); } } LOG.debug("Getting required query params..."); if (ds3Request.getRequiredQueryParams() != null) { for (final Ds3Param ds3Param : ds3Request.getRequiredQueryParams()) { if (ds3Param == null) { break; } LOG.debug(" query param " + ds3Param.getType().toString()); final String paramType = ds3Param.getType().substring(ds3Param.getType().lastIndexOf(".") + 1); LOG.debug("param " + paramType + " is required."); requiredArgsBuilder.add(new Arguments(paramType, ds3Param.getName())); } } return requiredArgsBuilder.build(); }</code><technical_language>this "object name REQUIRED"</technical_language>

Target:
private static ImmutableList<Arguments> getRequiredArgs(final Ds3Request ds3Request) { final ImmutableList.Builder<Arguments> requiredArgsBuilder = ImmutableList.builder(); LOG.debug("Getting required args..."); if (ds3Request.getBucketRequirement() == Requirement.REQUIRED) { LOG.debug("bucket name REQUIRED."); requiredArgsBuilder.add(new Arguments("String", "bucketName")); if (ds3Request.getObjectRequirement() == Requirement.REQUIRED) { LOG.debug("object name REQUIRED."); requiredArgsBuilder.add(new Arguments("String", "objectName")); } } LOG.debug("Getting required query params..."); if (ds3Request.getRequiredQueryParams() != null) { for (final Ds3Param ds3Param : ds3Request.getRequiredQueryParams()) { if (ds3Param == null) { break; } LOG.debug(" query param " + ds3Param.getType().toString()); final String paramType = ds3Param.getType().substring(ds3Param.getType().lastIndexOf(".") + 1); LOG.debug("param " + paramType + " is required."); requiredArgsBuilder.add(new Arguments(paramType, ds3Param.getName())); } } return requiredArgsBuilder.build(); }
Source:
<code>private Map<Class<?>, List<EntityInfo>> groupInfosByIdSpace(EntityInfo[] entityInfos, ObjectInitializationContext objectInitializationContext) { ServiceManager serviceManager = objectInitializationContext.getExtendedSearchintegrator().getServiceManager(); IdUniquenessResolver resolver = serviceManager.requestService( IdUniquenessResolver.class ); SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) objectInitializationContext.getSession().getSessionFactory(); try { Map<Class<?>, List<EntityInfo>> infosByIdSpace = new HashMap<>(); for ( EntityInfo entityInfo : entityInfos ) { boolean addedToExistingGroup = processEntityInfo( infosByIdSpace, resolver, entityInfo ); <START> if ( !addedToExistingGroup ) { <END> List<EntityInfo> infos = new ArrayList<>(); infos.add( entityInfo ); infosByIdSpace.put( getRootEntityType( sessionFactory, entityInfo.getClazz() ), infos ); } } return infosByIdSpace; } finally { serviceManager.releaseService( IdUniquenessResolver.class ); } }</code><technical_language>do need return a boolean processEntityInfo? handle adding of new EntityInfo list in processEntityInfo directly</technical_language>

Target:
private Map<Class<?>, List<EntityInfo>> groupInfosByIdSpace(EntityInfo[] entityInfos, ObjectInitializationContext objectInitializationContext) { ServiceManager serviceManager = objectInitializationContext.getExtendedSearchintegrator().getServiceManager(); IdUniquenessResolver resolver = serviceManager.requestService( IdUniquenessResolver.class ); SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) objectInitializationContext.getSession().getSessionFactory(); try { Map<Class<?>, List<EntityInfo>> idSpaces = new HashMap<>(); for ( EntityInfo entityInfo : entityInfos ) { addToIdSpace( idSpaces, entityInfo, resolver, sessionFactory ); } return idSpaces; } finally { serviceManager.releaseService( IdUniquenessResolver.class ); } }
Source:
<code>public void blockingTimeout() { final FailoverFeignTarget spiedTarget = Mockito.spy(new FailoverFeignTarget<>( SERVERS, 1, Object.class)); for (int i = 0; i < CLUSTER_SIZE; i++) { spiedTarget.url(); spiedTarget.continueOrPropagate(EXCEPTION_WITH_RETRY_AFTER); } ArgumentCaptor<Long> argument = ArgumentCaptor.forClass(Long.class); verify(spiedTarget, times(CLUSTER_SIZE)).pauseForBackoff(any(), argument.capture()); List<Long> arguments = argument.getAllValues(); assertThat(arguments.size()).isEqualTo(CLUSTER_SIZE); <START> for (int i = 0; i < CLUSTER_SIZE - 1; i++) { <END> assertThat(arguments.get(i)).isEqualTo(1L); } assertThat(arguments.get(CLUSTER_SIZE - 1)).isEqualTo(1000L); }</code><technical_language>If a cluster size for this test of 3 (i.e. CLUSTER_SIZE constant), write a single assert verify arguments.containsExactly(1L, 1L, 1000L) (pseudo-test-code, actual method required different)</technical_language>

Target:
public void blockingTimeout() { final FailoverFeignTarget spiedTarget = Mockito.spy(new FailoverFeignTarget<>( SERVERS, 1, Object.class)); for (int i = 0; i < CLUSTER_SIZE; i++) { spiedTarget.url(); spiedTarget.continueOrPropagate(EXCEPTION_WITH_RETRY_AFTER); } ArgumentCaptor<Long> argument = ArgumentCaptor.forClass(Long.class); verify(spiedTarget, times(CLUSTER_SIZE)).pauseForBackoff(any(), argument.capture()); List<Long> arguments = argument.getAllValues(); MatcherAssert.assertThat(arguments, Matchers.contains(1L, 1L, 500L)); }
Source:
<code>public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri uri = Uri.parse(url); if (arrivedAtRedirectUri(uri)) { final String error = uri.getQueryParameter("error"); if (error != null) { <START> Timber.i("got oauth error: " + error); <END> errorHandler.onError(error); requestHandler.onErrorWhenGettingOAuthCode(error); return true; } String oAuthCode = uri.getQueryParameter("code"); requestHandler.onOAuthCodeGot(oAuthCode); return true; } if (getOutOfDomain(uri)) { requestHandler.onErrorWhenGettingOAuthCode("Don't surf away"); return true; } return false; }</code><technical_language>Timber.e :)</technical_language>

Target:
public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri uri = Uri.parse(url); if (arrivedAtRedirectUri(uri)) { final String error = uri.getQueryParameter("error"); if (error != null) { Timber.e("got oauth error: " + error); errorHandler.onError(error); requestHandler.onErrorWhenGettingOAuthCode(error); return true; } String oAuthCode = uri.getQueryParameter("code"); requestHandler.onOAuthCodeGot(oAuthCode); return true; } if (getOutOfDomain(uri)) { requestHandler.onErrorWhenGettingOAuthCode("Don't surf away"); return true; } return false; }