auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) { if (out.isDirect() && out.order() == ByteOrder.BIG_ENDIAN) { IconvProvider.release(iconv_tPointer); this.iconv_tPointer = IconvProvider.initConversion(((IconvCharset) charset()).getIconvName(), "UTF-16BE"); if (this.iconv_tPointer < 10) { return CoderResult.malformedForLength(1); } } IconvResult result = IconvProvider.decode(iconv_tPointer, in, out); switch (result.getResultCode()) { case OUTPUT_BUFFER_TOO_SMALL: return CoderResult.OVERFLOW; case ILLEGAL_SEQUENCE: return CoderResult.unmappableForLength(result.getBytesWrittenFromSource()); case INCOMPLETE_SEQUENCE: return CoderResult.malformedForLength(result.getBytesWrittenFromSource()); case WEIRD_ERROR: return CoderResult.malformedForLength(1); default: <START> break; <END> } return CoderResult.UNDERFLOW; }</code><technical_language>Throw exception IllegalStateException instead of continuing</technical_language>

Target:
protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) { allocateContentDescriptor(out.isDirect(), out.order()); IconvResult result = IconvProvider.decode(iconv_tPointer, in, out); int bytesFromSource = result.getBytesReadFromSource(); switch (result.getResultCode()) { case CONVERSION_OK: return CoderResult.UNDERFLOW; case OUTPUT_BUFFER_TOO_SMALL: return CoderResult.OVERFLOW; case ILLEGAL_SEQUENCE: return CoderResult.unmappableForLength(bytesFromSource); case INCOMPLETE_SEQUENCE: return CoderResult.UNDERFLOW; default: throw new IllegalStateException(); } }
Source:
<code><START> static void populateKiePMMLFieldOperatorValueListWithSimplePredicates(final List<KiePMMLFieldOperatorValue> toPopulate, final CompoundPredicate.BooleanOperator booleanOperator, final Map<String, List<SimplePredicate>> predicatesByField, final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap) { <END> switch (booleanOperator) { case AND: predicatesByField.forEach((fieldName, predicates) -> toPopulate.add(getConstraintEntryFromSimplePredicates(fieldName, "&&", predicates, fieldTypeMap))); break; case OR: predicatesByField.forEach((fieldName, predicates) -> toPopulate.add(getConstraintEntryFromSimplePredicates(fieldName, "||", predicates, fieldTypeMap))); break; default: throw new IllegalStateException(String.format("CompoundPredicate.booleanOperator should never be %s at this point", booleanOperator)); } }</code><technical_language>split this signature in multiple lines for readability</technical_language>

Target:
static void populateKiePMMLFieldOperatorValueListWithSimplePredicates(final List<KiePMMLFieldOperatorValue> toPopulate, final CompoundPredicate.BooleanOperator booleanOperator, final Map<String, List<SimplePredicate>> predicatesByField, final Map<String, KiePMMLOriginalTypeGeneratedType> fieldTypeMap) { switch (booleanOperator) { case AND: predicatesByField.forEach((fieldName, predicates) -> toPopulate.add(getConstraintEntryFromSimplePredicates(fieldName, BOOLEAN_OPERATOR.AND, predicates, fieldTypeMap))); break; case OR: predicatesByField.forEach((fieldName, predicates) -> toPopulate.add(getConstraintEntryFromSimplePredicates(fieldName, BOOLEAN_OPERATOR.OR, predicates, fieldTypeMap))); break; default: throw new IllegalStateException(String.format("CompoundPredicate.booleanOperator should never be %s at this point", booleanOperator)); } }
Source:
<code>public void inflateSubmissionDate() { mfDatePicker = MFDatePicker.newInsance(this); tvSubmittedonDate.setText(MFDatePicker.getDatePickedAsString()); <START> tvSubmittedonDate.setOnClickListener(new View.OnClickListener() { <END> @Override public void onClick(View view) { issubmittedDate = true; mfDatePicker.show(getActivity().getSupportFragmentManager(), FragmentConstants .DFRAG_DATE_PICKER); } }); }</code><technical_language>ButterKnife @onClick Annotation instead of implementing OnClickListener</technical_language>

Target:
public void inflateSubmissionDate() { mfDatePicker = MFDatePicker.newInsance(this); tvSubmittedonDate.setText(MFDatePicker.getDatePickedAsString()); }
Source:
<code>private ListenableFuture<ResultSet> selectPeersFuture(final Connection connection) { <START> String query = <END> cluster.configuration.getProtocolOptions().isAllowHostPortDiscovery() ? SELECT_PEERS_V2 : SELECT_PEERS; DefaultResultSetFuture peersFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(query)); connection.write(peersFuture); return peersFuture; }</code><technical_language>is fall system peers query if get invalid query request back. I in specific case sane fall peers query</technical_language>

Target:
private ListenableFuture<ResultSet> selectPeersFuture(final Connection connection) { if (isPeersV2) { DefaultResultSetFuture peersV2Future = new DefaultResultSetFuture( null, cluster.protocolVersion(), new Requests.Query(SELECT_PEERS_V2)); connection.write(peersV2Future); final SettableFuture<ResultSet> peersFuture = SettableFuture.create(); GuavaCompatibility.INSTANCE.addCallback( peersV2Future, new FutureCallback<ResultSet>() { @Override public void onSuccess(ResultSet result) { peersFuture.set(result); } @Override public void onFailure(Throwable t) { if (t instanceof InvalidQueryException) { isPeersV2 = false; MoreFutures.propagateFuture(peersFuture, selectPeersFuture(connection)); } else { peersFuture.setException(t); } } }); return peersFuture; } else { DefaultResultSetFuture peersFuture = new DefaultResultSetFuture( null, cluster.protocolVersion(), new Requests.Query(SELECT_PEERS)); connection.write(peersFuture); return peersFuture; } }
Source:
<code>private Request.Builder setupRequest(HttpUrl requestUri, String path, RequestParameters params) { if ( path == null ) throw new IllegalArgumentException("path cannot be null"); if ( path.startsWith("/") ) path = path.substring(1); HttpUrl.Builder uri = requestUri.resolve(path).newBuilder(); if ( params != null ) { for ( String key : params.keySet() ) { for ( String value : params.get(key) ) { uri.addQueryParameter(key, value); } } } if ( database != null && ! path.startsWith("config/") ) { uri.addQueryParameter("database", database); } Request.Builder request = new Request.Builder() .url(uri.build()); if(headerValue!=null && headerValue.length()!=0) { <START> String samlHeaderValue = "Authorization: SAML token="+ headerValue; <END> request = request.header(HEADER_AUTHORIZATION, samlHeaderValue); } return request; }</code><technical_language>string concatenation AUTHORIZATION_TYPE_SAML AUTHORIZATION_PARAM_TOKEN constants</technical_language>

Target:
private Request.Builder setupRequest(HttpUrl requestUri, String path, RequestParameters params) { if ( path == null ) throw new IllegalArgumentException("path cannot be null"); if ( path.startsWith("/") ) path = path.substring(1); HttpUrl.Builder uri = requestUri.resolve(path).newBuilder(); if ( params != null ) { for ( String key : params.keySet() ) { for ( String value : params.get(key) ) { uri.addQueryParameter(key, value); } } } if ( database != null && ! path.startsWith("config/") ) { uri.addQueryParameter("database", database); } Request.Builder request = new Request.Builder() .url(uri.build()); return request; }
Source:
<code>public SpecializedSignature getSpecializedSignature() { SpecializedSignature specializedSignature = new SpecializedSignature( signature, argumentNativeContainerTypes, specializedTypeParameters, returnNativeContainerType); return specializedSignature; <START> } <END></code><technical_language>nit: create SpecializedSignature return in step. java return new SpecializedSignature( signature, argumentNativeContainerTypes, specializedTypeParameters, returnNativeContainerType);</technical_language>

Target:
SpecializedSignature getSpecializedSignature() { return new SpecializedSignature( signature, argumentNativeContainerTypes, specializedTypeParameters, returnNativeContainerType); }
Source:
<code>private boolean needsExtendsDecomposing(Node classNode) { checkArgument(classNode.isClass()); if (classNode.getSecondChild().isEmpty() || classNode.getSecondChild().isQualifiedName()) { return false; } Node ancestor = classNode.getParent(); switch (ancestor.getToken()) { case RETURN: ancestor = ancestor.getParent(); break; case NAME: if (ancestor.getParent() != null && NodeUtil.isNameDeclaration(ancestor.getParent()) && ancestor.getParent().hasOneChild()) { ancestor = ancestor.getGrandparent(); } break; case ASSIGN: if (classNode.getPrevious() != null && ancestor.getParent() != null && ancestor.getParent().isExprResult()) { ancestor = ancestor.getGrandparent(); } break; } if (NodeUtil.isStatementParent(ancestor)) { <START> return true; <END> } return false; }</code><technical_language>need check LHS of expression if side-effects: get(x++).foo = class extends get(x++).bar {}</technical_language>

Target:
private boolean needsExtendsDecomposing(Node classNode) { checkArgument(classNode.isClass()); if (classNode.getSecondChild().isEmpty() || classNode.getSecondChild().isQualifiedName()) { return false; } return true; }
Source:
<code>private VenueDTO adapt(Venue venue) { if (venue == null) { <START> return DefaultVenueDTO(); <END> } List<VenueNameInformationDTO> nameInformationDTOs = Lists.newArrayList(); for (VenueNameInformation info : venue.nameInformation) { nameInformationDTOs.add(new VenueNameInformationDTO(info.nameInformation, info.language.code)); } return new VenueDTO(venue.group.name, venue.type.name, nameInformationDTOs); }</code><technical_language>nan</technical_language>

Target:
private VenueDTO adapt(Venue venue) { List<VenueNameDTO> names = Lists.newArrayList(); for (VenueName info : venue.names) { names.add(new VenueNameDTO(info.name, info.language.code)); } return new VenueDTO(venue.group.name, venue.type.name, names); }
Source:
<code>public void setColumn(Function<T, Comparable<?>> column, int idx) { this.func = column; if (idx == this.propertyIndex) { <START> direction = Direction.getDirection(1 - direction.ordinal()); <END> } else { this.propertyIndex = idx; direction = Direction.DESCENDING; } }</code><technical_language>please change direction = direction == ASCENDING ? DESCENDING : ASCENDING; (or add functionality a static in enum Direction). I getDirection return a null, making non-trivial read this code in practice happen</technical_language>

Target:
public void setColumn(Function<T, Comparable<?>> column, int idx) { this.func = column; if (idx == this.propertyIndex) { direction = Direction.toggle(direction); } else { this.propertyIndex = idx; direction = Direction.DESCENDING; } }
Source:
<code>synchronized SchedulerState getState(boolean myJobsOnly) throws NotConnectedException, PermissionException { checkPermission("getState", "You do not have permission to get the state !"); ListeningUser ui = identifications .get(PAActiveObject.getContext().getCurrentRequest().getSourceBodyID()); <START> <END> return myJobsOnly ? sState.filterOnUser(ui.getUser().getUsername()) : sState; }</code><technical_language>afraid, this modification, a user able other users jobs (task list)</technical_language>

Target:
synchronized SchedulerState getState(boolean myJobsOnly) throws NotConnectedException, PermissionException { checkPermission("getState", YOU_DO_NOT_HAVE_PERMISSION_TO_GET_THE_STATE); ListeningUser ui = identifications .get(PAActiveObject.getContext().getCurrentRequest().getSourceBodyID()); return myJobsOnly ? sState.filterOnUser(ui.getUser().getUsername()) : sState; }
Source:
<code>public void sendData(String metricId, RawDataPackageProtos.RawDataPackage metricData) { String messageKey = nodeName + KAFKA_KEY_SEPARATOR + metricId + KAFKA_KEY_SEPARATOR + sentMetricsCounter.getAndIncrement(); ProducerRecord<String, byte[]> producerRecord = new ProducerRecord<>(kafkaTopic, messageKey, metricData.toByteArray()); kafkaProducer.send(producerRecord, (metadata, exception) -> { if (exception == null) LOGGER.debug("Sent: nodeName = {}, metricId = {}, offset = {}", nodeName, metricId, metadata.offset()); else <START> LOGGER.error("Exception on sending message.", exception); <END> }); }</code><technical_language>propose log "Sent: nodeName = {}, metricId = {}, offset = {}" in case of error - easier parse logs metrics lost</technical_language>

Target:
public void sendData(String metricId, RawDataPackageProtos.RawDataPackage metricData) { String messageKey = nodeName + KAFKA_KEY_SEPARATOR + metricId + KAFKA_KEY_SEPARATOR + sentMetricsCounter.getAndIncrement(); ProducerRecord<String, byte[]> producerRecord = new ProducerRecord<>(kafkaTopic, messageKey, metricData.toByteArray()); kafkaProducer.send(producerRecord, (metadata, exception) -> { LOGGER.debug("Sent: nodeName = {}, metricId = {}, offset = {}", nodeName, metricId, metadata.offset()); if (exception != null) LOGGER.error("Exception on sending message.", exception); }); }
Source:
<code>protected void findReferences(ITypeRoot[] roots, Set<String> pkgs, IProgressMonitor monitor, boolean binary) throws JavaModelException { <START> monitor.beginTask("", roots.length); END> for (int i = 0; i < roots.length; i++) { findReferences(roots[i].findPrimaryType(), pkgs, binary); monitor.worked(1); } }</code><technical_language>Convert SubMonitor</technical_language>

Target:
protected void findReferences(ITypeRoot[] roots, Set<String> pkgs, IProgressMonitor monitor, boolean binary) throws JavaModelException { SubMonitor subMonitor = SubMonitor.convert(monitor, roots.length); for (int i = 0; i < roots.length; i++) { findReferences(roots[i].findPrimaryType(), pkgs, binary); subMonitor.worked(1); } }
Source:
<code>private void activateMarkers() { if (!fGerritClient.getRepository().getServerInfo().isAnonymous()) { String value = NLS.bind(Messages.ChangeDetailEditor_EGerriTipValue, <START> fChangeInfo.getUserSelectedRevision().get_number()); <END> UIUtils.showDialogTip(MARKERS_KEY, headerSection.getShell(), Messages.EGerriTip, value); } }</code><technical_language>ChangeDetailEditor_EGerriTipValue more arguments, , need set arguments</technical_language>

Target:
private void activateMarkers() { if (!fGerritClient.getRepository().getServerInfo().isAnonymous()) { UIUtils.showDialogTip(MARKERS_KEY, headerSection.getShell(), Messages.EGerriTip, Messages.ChangeDetailEditor_EGerriTipValue); } }
Source:
<code>public LuceneCollectors build() { if ( luceneCollectors.isEmpty() ) { <START> throw new AssertionFailure( "No collectors have been defined: we need at least one." ); <END> } Collector compositeCollector; if ( luceneCollectors.size() == 1 ) { compositeCollector = topDocsCollector != null ? topDocsCollector : totalHitCountCollector; } else { compositeCollector = MultiCollector.wrap( luceneCollectors ); } return new LuceneCollectors( topDocsCollector, totalHitCountCollector, compositeCollector ); }</code><technical_language>happen projects empty list of projections? Which, granted, useful, happen, especially is number of results. a safer approach a TotalHitCountCollector default</technical_language>

Target:
public LuceneCollectors build() { Collector compositeCollector; if ( luceneCollectors.size() == 1 ) { compositeCollector = luceneCollectors.get( 0 ); } else { compositeCollector = MultiCollector.wrap( luceneCollectors ); } return new LuceneCollectors( topDocsCollector, totalHitCountCollector, compositeCollector ); }
Source:
<code>public void testwithCustomRetryTemplate() { StatefulRetryOperationsInterceptor interceptor = RetryInterceptorBuilder.stateful() .setRetryOperations(new RetryTemplate()) .build(); <START> assertEquals(3, TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")); <END> }</code><technical_language>This test show a difference testBasic() enough this: RetryTemplate retryTemplate = new RetryTemplate(); ... assertSame(retryTemplate, TestUtils.getPropertyValue(interceptor, "retryOperations"));</technical_language>

Target:
public void testwithCustomRetryTemplate() { RetryOperations retryOperations = new RetryTemplate(); StatefulRetryOperationsInterceptor interceptor = RetryInterceptorBuilder.stateful() .retryOperations(retryOperations) .build(); assertEquals(3, TestUtils.getPropertyValue(interceptor, "retryOperations.retryPolicy.maxAttempts")); assertSame(retryOperations, TestUtils.getPropertyValue(interceptor, "retryOperations")); }
Source:
<code><START> public ApplicationFetchException(String apiKey, ErrorCode errorCode) { <END> super(); this.apiKey = apiKey; this.errorCode = errorCode; }</code><technical_language>class is abstract. Constructor protected</technical_language>

Target:
protected ApplicationFetchException(String apiKey, ErrorCode errorCode) { super(); this.apiKey = apiKey; this.errorCode = errorCode; }
Source:
<code>private void downloadMedia() { mDownloadMediaUseCase.execute(new DownloadMediaUseCase.Callback() { @Override public void onError(FileDownloadException ex) { if (ex.getCause() instanceof UserRecoverableAuthIOException) { showToast(ex.getCause().getMessage()); DashboardActivity.dashboardActivity.startActivityForResult( ((UserRecoverableAuthIOException) ex.getCause()).getIntent(), REQUEST_AUTHORIZATION); return; } else if (ex.getCause() instanceof GooglePlayServicesAvailabilityIOException) { showDialog( ((GooglePlayServicesAvailabilityIOException) ex.getCause()) .getConnectionStatusCode()); return; } else if (ex.getCause() instanceof GooglePlayAppNotAvailableException) { GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); final int connectionStatusCode = apiAvailability.isGooglePlayServicesAvailable( PreferencesState.getInstance().getContext()); if (apiAvailability.isUserResolvableError(connectionStatusCode)) { showDialog(connectionStatusCode); } } else { Log.e(this.getClass().getSimpleName(), "Unexpected error to download Media"); } } @Override public void onSuccess(int syncedFiles) { avFragment.reloadData(); if (syncedFiles > 0) { showToast(String.format("%d files synced", syncedFiles)); } } @Override <START> public void onProgress() { <END> avFragment.showProgress(); } }); }</code><technical_language>this callback method receive a parameter for ProgressStatus end</technical_language>

Target:
private void downloadMedia() { mDownloadMediaUseCase.execute(new DownloadMediaUseCase.Callback() { @Override public void onError(FileDownloadException ex) { if (ex.getCause() instanceof UserRecoverableAuthIOException) { showToast(ex.getCause().getMessage()); DashboardActivity.dashboardActivity.startActivityForResult( ((UserRecoverableAuthIOException) ex.getCause()).getIntent(), REQUEST_AUTHORIZATION); return; } else if (ex.getCause() instanceof GooglePlayServicesAvailabilityIOException) { showDialog( ((GooglePlayServicesAvailabilityIOException) ex.getCause()) .getConnectionStatusCode()); return; } else if (ex.getCause() instanceof GooglePlayAppNotAvailableException) { GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); final int connectionStatusCode = apiAvailability.isGooglePlayServicesAvailable( PreferencesState.getInstance().getContext()); if (apiAvailability.isUserResolvableError(connectionStatusCode)) { showDialog(connectionStatusCode); } } else { Log.e(this.getClass().getSimpleName(), ex.getMessage()); } } @Override public void onSuccess(int syncedFiles) { avFragment.reloadData(); if (syncedFiles > 0) { showToast(String.format("%d files synced", syncedFiles)); } } @Override public void onDownloadInProgressChanged(boolean value) { avFragment.showProgress(value); } }); }
Source:
<code>private void executePhotoTask(Task task) { viewHolder.profileImageProgress.setVisibility(View.VISIBLE); <START> if (viewHolder.profileImageProgress.getAnimation() == null) { <END> viewHolder.profileImageProgress.startAnimation( AnimationUtils.loadAnimation(getActivity(), R.anim.rotate)); } if (null != setAccountImageTask) { setAccountImageTask.cancel(true); } setAccountImageTask = task; setAccountImageTask.setProgressCallback(null); task.execute(); }</code><technical_language>IconView built-in support for rotation animation. migrate now</technical_language>

Target:
private void executePhotoTask(Task task) { viewHolder.profileImageProgress.setVisibility(View.VISIBLE); viewHolder.profileImageProgress.setRotating(true); if (null != setAccountImageTask) { setAccountImageTask.cancel(true); } setAccountImageTask = task; setAccountImageTask.setProgressCallback(null); task.execute(); }
Source:
<code>public void requestAccess(final Activity activity, final Callback<String> callback) { OAuth2AuthzSession storedAccount = sessionStore.read(AuthEndPoints.NAME); <START> final String token = storedAccount.getAccessToken(); <END> try { callback.onSuccess(token); } catch (Exception e) { callback.onFailure(e); } }</code><technical_language>final is useless here. Also, consider this. java try { callback.onSuccess(sessionStore.read(AuthEndpoints.NAME).getAccessToken()); } catch (Exception e) { callback.onFailure(e); }</technical_language>

Target:
public void requestAccess(final Activity activity, final Callback<String> callback) { callback.onSuccess(sessionStore.read(AuthData.NAME).getAccessToken()); }
Source:
<code>private void checkToolTokens(User authUser, Long userId, String organization) { List<Token> tokens = tokenDAO.findByUserId(userId); List<Tool> tools = userContainers(authUser, userId); if (organization != null && !organization.isEmpty()) { tools.removeIf(tool -> !tool.getNamespace().equals(organization)); } Token gitLabToken = Helper.extractToken(tokens, TokenType.GITLAB_COM.toString()); Token quayioToken = Helper.extractToken(tokens, TokenType.QUAY_IO.toString()); Set<Registry> uniqueRegistry = new HashSet<>(); tools.forEach(tool -> uniqueRegistry.add(tool.getRegistry())); if (uniqueRegistry.size() == 0 && quayioToken == null) { <START> throw new CustomWebApplicationException("Please add a Quay.io token", HttpStatus.SC_BAD_REQUEST); <END> } if (uniqueRegistry.contains(Registry.QUAY_IO) && quayioToken == null) { throw new CustomWebApplicationException("Have Quay.io tools but no Quay.io token", HttpStatus.SC_BAD_REQUEST); } if (uniqueRegistry.contains(Registry.GITLAB) && gitLabToken == null) { throw new CustomWebApplicationException("Have GitLab tools but no GitLab token", HttpStatus.SC_BAD_REQUEST); } }</code><technical_language>Elaborate</technical_language>

Target:
private void checkToolTokens(User authUser, Long userId, String organization) { List<Token> tokens = tokenDAO.findByUserId(userId); List<Tool> tools = userContainers(authUser, userId); if (organization != null && !organization.isEmpty()) { tools.removeIf(tool -> !tool.getNamespace().equals(organization)); } Token gitLabToken = Helper.extractToken(tokens, TokenType.GITLAB_COM.toString()); Token quayioToken = Helper.extractToken(tokens, TokenType.QUAY_IO.toString()); Set<Registry> uniqueRegistry = new HashSet<>(); tools.forEach(tool -> uniqueRegistry.add(tool.getRegistry())); if (uniqueRegistry.size() == 0 && quayioToken == null) { throw new CustomWebApplicationException("You have no tools and no Quay.io token to automatically add tools. Please add a Quay.io token.", HttpStatus.SC_BAD_REQUEST); } if (uniqueRegistry.contains(Registry.QUAY_IO) && quayioToken == null) { throw new CustomWebApplicationException("You have Quay.io tools but no Quay.io token to refresh the tools with. Please add a Quay.io token.", HttpStatus.SC_BAD_REQUEST); } if (uniqueRegistry.contains(Registry.GITLAB) && gitLabToken == null) { throw new CustomWebApplicationException("You have GitLab tools but no GitLab token to refresh the tools with. Please add a GitLab token", HttpStatus.SC_BAD_REQUEST); } }
Source:
<code>public int read(final char[] buf, final int offset, final int length) throws IOException { if (length == 0) { return 0; } final int len = super.read(buf, offset, length); if (len > 0) { for (int i = offset; i < offset + len; i++) { final char ch = buf[i]; if (ch == LF) { if (CR != (i > 0 ? buf[i - 1] : lastChar)) { eolCounter++; } } else if ((ch == CR) <START> || (ch == END_OF_STREAM && (i > 0 ? buf[i - 1] : lastChar) != LF && (i > 0 ? buf[i - 1] : lastChar) != CR)) { <END> eolCounter++; } } lastChar = buf[offset + len - 1]; } else if (len == -1) { lastChar = END_OF_STREAM; } position += len; return len; }</code><technical_language>code more self-explaining? * i > 0 ? buf[i - 1is times in this code snippet * I is fault intellectually challenged understand condition :-(</technical_language>

Target:
public int read(final char[] buf, final int offset, final int length) throws IOException { if (length == 0) { return 0; } final int len = super.read(buf, offset, length); if (len > 0) { for (int i = offset; i < offset + len; i++) { final char ch = buf[i]; if (ch == LF) { if (CR != (i > 0 ? buf[i - 1] : lastChar)) { eolCounter++; } } else if (ch == CR) { eolCounter++; } } lastChar = buf[offset + len - 1]; } else if (len == -1) { lastChar = END_OF_STREAM; } position += len; return len; }
Source:
<code>public void testWithoutShop() { try { <START> new BuyClientBuilder().shopDomain("").build(); <END> } catch (IllegalArgumentException e) { return; } fail("Expected IllegalArgumentException"); }</code><technical_language>This works this way? order dependant checking, add a non-empty apiKey, appId</technical_language>

Target:
public void testWithoutShop() { try { new BuyClientBuilder() .apiKey("apiKey") .appId("appId") .applicationName("applicationName") .shopDomain("") .build(); } catch (IllegalArgumentException e) { return; } fail("Expected IllegalArgumentException"); }
Source:
<code><START> public int getAvailableConnectionsCount() { <END> int count = 0; for (HostPortPoolManager hostPortPoolManager : hostPortToPoolManager.values()) { count += hostPortPoolManager.getAvailableConnectionsCount(); } return count; }</code><technical_language>if feel this in metrics, I of getAvailableConnectionsCountPerHostPortPair helpful. Isn't</technical_language>

Target:
public int getAvailableConnectionsCount() { if (!isOpen) { throw new IllegalStateException("Connection Manager is closed"); } int count = 0; for (HostPortPoolManager hostPortPoolManager : hostPortToPoolManager.values()) { count += hostPortPoolManager.getAvailableConnectionsCount(); } return count; }
Source:
<code>public void addTags(String remotePath, CVSTag[] tags) { if (tags.length == 0) { <START> return; <END> } addDateTags(tags); addVersionAndBranchTags(remotePath, tags); }</code><technical_language>Yes, if add empty set of tags entry is treated accessed. I correct</technical_language>

Target:
public void addTags(String remotePath, CVSTag[] tags) { addDateTags(tags); addVersionAndBranchTags(remotePath, tags); }
Source:
<code>public void testOutputStreamAsynchronousByteChannel() throws Exception { AsynchronousByteChannel abc = mock(AsynchronousByteChannel.class); OutputStream os = Channels.newOutputStream(abc); Future<Integer> result = mock(Future.class); ArgumentCaptor<ByteBuffer> bbCaptor = ArgumentCaptor.forClass(ByteBuffer.class); final byte[] data = <START> new byte[]{'a', 'a', 'a'}; <END> when(abc.write(bbCaptor.capture())).thenReturn(result); when(result.get()).thenAnswer( new Answer<Integer>() { public Integer answer(InvocationOnMock invocation) { ByteBuffer bb = bbCaptor.getValue(); assertEquals(data.length, bb.remaining()); byte[] readData = new byte[data.length]; bb.get(readData, 0, data.length); for (int i = 0;i < readData.length;++i) { assertEquals(data[i], readData[i]); } return data.length; } }); os.write(data); }</code><technical_language>distinct bytes? E.g. final byte[] bytesToWrite = "Hello, world!".toBytes();</technical_language>

Target:
public void testOutputStreamAsynchronousByteChannel() throws Exception { AsynchronousByteChannel abc = mock(AsynchronousByteChannel.class); OutputStream os = Channels.newOutputStream(abc); Future<Integer> result = mock(Future.class); ArgumentCaptor<ByteBuffer> bbCaptor = ArgumentCaptor.forClass(ByteBuffer.class); final byte[] data = "world".getBytes(); when(abc.write(bbCaptor.capture())).thenReturn(result); when(result.get()).thenAnswer( new Answer<Integer>() { public Integer answer(InvocationOnMock invocation) { ByteBuffer bb = bbCaptor.getValue(); assertEquals(data.length, bb.remaining()); byte[] readData = new byte[data.length]; bb.get(readData); assertTrue(Arrays.equals(data, readData)); return data.length; } }); os.write(data); Mockito.verify(abc).write(isA(ByteBuffer.class)); Mockito.verify(result).get(); }
Source:
<code>public void testIntegerScale_fromDisk() { <START> objectStorage.put("DummyObject", new DummyObject()); <END> DummyObject dummy = objectStorage.get("DummyObject"); Assert.assertEquals(((BigDecimal) dummy.configuration.get("testShort")).scale(), 0); Assert.assertEquals(((BigDecimal) dummy.configuration.get("testInt")).scale(), 0); Assert.assertEquals(((BigDecimal) dummy.configuration.get("testLong")).scale(), 0); Assert.assertEquals(((BigDecimal) dummy.configuration.get("testBigDecimal")).scale(), 0); Assert.assertEquals(((List<BigDecimal>) dummy.configuration.get("multiInt")).get(0).scale(), 0); Assert.assertEquals(((List<BigDecimal>) dummy.configuration.get("multiInt")).get(1).scale(), 0); Assert.assertEquals(((List<BigDecimal>) dummy.configuration.get("multiInt")).get(2).scale(), 0); Assert.assertEquals(((BigDecimal) dummy.channels.get(0).configuration.get("testChildLong")).scale(), 0); }</code><technical_language>If want read disk call persistAndReadAgain get</technical_language>

Target:
public void testIntegerScale_fromDisk() { objectStorage.put("DummyObject", new DummyObject()); persistAndReadAgain(); DummyObject dummy = objectStorage.get("DummyObject"); assertEquals(((BigDecimal) dummy.configuration.get("testShort")).scale(), 0); assertEquals(((BigDecimal) dummy.configuration.get("testInt")).scale(), 0); assertEquals(((BigDecimal) dummy.configuration.get("testLong")).scale(), 0); assertEquals(((BigDecimal) dummy.configuration.get("testBigDecimal")).scale(), 0); assertEquals(((List<BigDecimal>) dummy.configuration.get("multiInt")).get(0).scale(), 0); assertEquals(((List<BigDecimal>) dummy.configuration.get("multiInt")).get(1).scale(), 0); assertEquals(((List<BigDecimal>) dummy.configuration.get("multiInt")).get(2).scale(), 0); assertEquals(((BigDecimal) dummy.channels.get(0).configuration.get("testChildLong")).scale(), 0); }
Source:
<code>private StringBuilder appendToString(final StringBuilder sb, final String fieldName, final Object fieldValue, final boolean hasNext) { sb.append(fieldName).append('=').append(fieldValue).append(System.lineSeparator()); if (hasNext) { <START> sb.append('\t'); <END> } return sb; }</code><technical_language>'\t' is more once. Create a constant for this</technical_language>

Target:
private StringBuilder appendToString(final StringBuilder sb, final String fieldName, final Object fieldValue, final boolean hasNext) { sb.append(fieldName).append('=').append(fieldValue).append(System.lineSeparator()); if (hasNext) { sb.append(TAB_CHAR); } return sb; }
Source:
<code>public void setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { HelixAdmin helixAdmin = manager.getClusterManagmentTool(); InstanceConfig instanceConfig = helixAdmin.getInstanceConfig(clusterName, instanceName); List<String> sealedReplicas = ClusterMapUtils.getSealedReplicas(instanceConfig); if (sealedReplicas == null) sealedReplicas = new ArrayList<>(); if (isSealed) { <START> sealedReplicas.add(replicaId.getPartitionId().toPathString()); <END> } else { sealedReplicas.remove(replicaId.getPartitionId().toPathString()); } instanceConfig.getRecord().setListField(ClusterMapUtils.SEALED_STR, sealedReplicas); helixAdmin.setInstanceConfig(clusterName, instanceName, instanceConfig); }</code><technical_language>if exists? helix dedup? If not, a exists check useful</technical_language>

Target:
public void setReplicaSealedState(ReplicaId replicaId, boolean isSealed) { if (!(replicaId instanceof AmbryReplica)) { throw new IllegalArgumentException( "HelixParticipant only works with the AmbryReplica implementation of ReplicaId"); } HelixAdmin helixAdmin = manager.getClusterManagmentTool(); InstanceConfig instanceConfig = helixAdmin.getInstanceConfig(clusterName, instanceName); List<String> sealedReplicas = ClusterMapUtils.getSealedReplicas(instanceConfig); if (sealedReplicas == null) { sealedReplicas = new ArrayList<>(); } String partitionId = replicaId.getPartitionId().toPathString(); if (!isSealed) { sealedReplicas.remove(partitionId); } else if (!sealedReplicas.contains(partitionId)) { sealedReplicas.add(partitionId); } instanceConfig.getRecord().setListField(ClusterMapUtils.SEALED_STR, sealedReplicas); helixAdmin.setInstanceConfig(clusterName, instanceName, instanceConfig); }
Source:
<code>public void afterPropertiesSet() { if (this.beanName == null) { logger.error("The MessageHandler [" + this.handler + "] will be created without a 'componentName'. " + "Consider specifying the 'beanName' property on this ConsumerEndpointFactoryBean."); } else { try { if (!this.beanName.startsWith("org.springframework")) { MessageHandler targetHandler = this.handler; if (AopUtils.isAopProxy(targetHandler)) { Object target = ((Advised) targetHandler).getTargetSource().getTarget(); if (target instanceof MessageHandler) { targetHandler = (MessageHandler) target; } } if (targetHandler instanceof IntegrationObjectSupport) { ((IntegrationObjectSupport) targetHandler).setComponentName(this.beanName); } } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Could not set component name for handler " + this.handler + " for " + this.beanName + " :" + e.getMessage()); } } } adviceChain(); if (this.channelResolver == null) { <START> this.channelResolver = new BeanFactoryMessageChannelDestinationResolver(this.beanFactory); <END> } initializeEndpoint(); }</code><technical_language>is this a BeanFactoryChannelResolver? a ChannelResolverUtils.getChannelResolver() instead way</technical_language>

Target:
public void afterPropertiesSet() { if (this.beanName == null) { logger.error("The MessageHandler [" + this.handler + "] will be created without a 'componentName'. " + "Consider specifying the 'beanName' property on this ConsumerEndpointFactoryBean."); } else { try { if (!this.beanName.startsWith("org.springframework")) { MessageHandler targetHandler = this.handler; if (AopUtils.isAopProxy(targetHandler)) { Object target = ((Advised) targetHandler).getTargetSource().getTarget(); if (target instanceof MessageHandler) { targetHandler = (MessageHandler) target; } } if (targetHandler instanceof IntegrationObjectSupport) { ((IntegrationObjectSupport) targetHandler).setComponentName(this.beanName); } } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Could not set component name for handler " + this.handler + " for " + this.beanName + " :" + e.getMessage()); } } } adviceChain(); if (this.channelResolver == null) { this.channelResolver = ChannelResolverUtils.getChannelResolver(this.beanFactory); } initializeEndpoint(); }
Source:
<code>public Result close() throws IOException { logout(); <START> LOGGER.info("Has " + getPastForm(sprops.outputAction.getValue()) + successCount + " record" + (successCount == 1 ? "" : "s") <END> + " successfully."); LOGGER.info("Has rejected record{}.", rejectCount, rejectCount == 1 ? "" : "s"); LOGGER.info("Done."); if (logWriter != null) { logWriter.close(); } return new Result(uId, dataCount, successCount, rejectCount); }</code><technical_language>I18N is needed</technical_language>

Target:
public Result close() throws IOException { logout(); LOGGER.info(MESSAGES.getMessage("info.seccessfulRecords", getPastForm(sprops.outputAction.getValue()), successCount)); LOGGER.info(MESSAGES.getMessage("info.rejectedRecords", rejectCount)); LOGGER.info(MESSAGES.getMessage("info.finishMessage")); if (logWriter != null) { logWriter.close(); } return new Result(uId, dataCount, successCount, rejectCount); }
Source:
<code>private boolean areFightingOrSupportingUnitsLeft(final BattleState.Side side) { final boolean hasUnitsThatCanRollLeft; hasUnitsThatCanRollLeft = battleState.getUnits(EnumSet.of(side)).stream() <START> .anyMatch( <END> getActiveUnits() .and( Matches.unitIsSupporterOrHasCombatAbility( side == BattleState.Side.OFFENSE))); return hasUnitsThatCanRollLeft; }</code><technical_language>nit, deeply nested functional chain. Consider decomposing this a bit helper methods. EG: return battleState.getUnits(EnumSet.of(side)).stream() .anyMatch(unitIsActive(BattleState.side.OFFENSE)); I get rid of intermediate variable return result well</technical_language>

Target:
private boolean areFightingOrSupportingUnitsLeft(final BattleState.Side side) { return battleState.getUnits(side).stream().anyMatch(unitIsActiveAndCanFight(side)); }
Source:
<code>JSONObject mesosMasterAddress() { try (CuratorFramework cf = zkClient()) { cf.start(); List<String> children = cf.getChildren().forPath("/mesos"); if (children.isEmpty()) { return null; } JSONObject cfData = null; for (String child : children) { <START> if (child.contains("json.info")) { <END> cfData = new JSONObject( new String(cf.getData().forPath("/mesos/" + child)) ); break; } } if (cfData == null) { LOGGER.error(" object is not available in /mesos znode data"); return null; } return cfData.getJSONObject("address"); } catch (Exception e) { LOGGER.error("Error while obtaining a mesos address from the curator framework: ", e.getLocalizedMessage()); return null; } }</code><technical_language>better: startsWith</technical_language>

Target:
String mesosMasterAddress() { try (CuratorFramework cf = zkClient()) { cf.start(); List<String> children = cf.getChildren().forPath("/mesos"); if (children.isEmpty()) { return null; } JSONObject cfData = null; for (String child : children) { if (child.startsWith("json.info")) { cfData = new JSONObject(new String(cf.getData().forPath("/mesos/" + child))); break; } } if (cfData != null) { JSONObject address = cfData.getJSONObject("address"); return String.format("%s:%d", address.getString("ip"), address.getInt("port")); } } catch (Exception e) { LOGGER.error("Error while obtaining a mesos address from the curator framework: ", e); } return null; }
Source:
<code>public TokenizerClassNameToElasticsearchTypeNameTransformer(Class<?> factoryClass, String parameterName) { <START> super(); <END> this.factoryClass = factoryClass; this.parameterName = parameterName; }</code><technical_language>remove super();</technical_language>

Target:
public TokenizerClassNameToElasticsearchTypeNameTransformer(Class<?> factoryClass, String parameterName) { this.factoryClass = factoryClass; this.parameterName = parameterName; }
Source:
<code>public void testCompanion() throws Exception { Path wd = Files.createTempDirectory(this.getClass().getName()); File outFile = wd.resolve("test.ome.tif").toFile(); File cFile = wd.resolve("test.companion.ome").toFile(); String companion = cFile.getAbsolutePath(); DynamicMetadataOptions options = new DynamicMetadataOptions(); options.set(OMETiffWriter.COMPANION_KEY, companion); int planeCount = WriterUtilities.SIZE_Z * WriterUtilities.SIZE_C * WriterUtilities.SIZE_T; OMETiffWriter cwriter = new OMETiffWriter(); cwriter.setMetadataOptions(options); cwriter.setMetadataRetrieve(metadata); cwriter.setId(outFile.getAbsolutePath()); cwriter.setSeries(0); byte[] img = new byte[WriterUtilities.SIZE_X * WriterUtilities.SIZE_Y]; <START> Arrays.fill(img, (byte) 0); <END> for (int i = 0; i < planeCount; i++) { cwriter.saveBytes(i, img); } cwriter.close(); assertTrue(cFile.exists()); OMETiffReader reader = new OMETiffReader(); reader.setId(companion); assertEquals(reader.getSizeX(), WriterUtilities.SIZE_X); assertEquals(reader.getSizeY(), WriterUtilities.SIZE_Y); assertEquals(reader.getSizeZ(), WriterUtilities.SIZE_Z); assertEquals(reader.getSizeC(), WriterUtilities.SIZE_C); assertEquals(reader.getSizeT(), WriterUtilities.SIZE_T); reader.close(); outFile.deleteOnExit(); cFile.deleteOnExit(); wd.toFile().deleteOnExit(); }</code><technical_language>filled zeroes</technical_language>

Target:
public void testCompanion() throws Exception { Path wd = Files.createTempDirectory(this.getClass().getName()); File outFile = wd.resolve("test.ome.tif").toFile(); File cFile = wd.resolve("test.companion.ome").toFile(); String companion = cFile.getAbsolutePath(); DynamicMetadataOptions options = new DynamicMetadataOptions(); options.set(OMETiffWriter.COMPANION_KEY, companion); int planeCount = WriterUtilities.SIZE_Z * WriterUtilities.SIZE_C * WriterUtilities.SIZE_T; OMETiffWriter cwriter = new OMETiffWriter(); cwriter.setMetadataOptions(options); cwriter.setMetadataRetrieve(metadata); cwriter.setId(outFile.getAbsolutePath()); cwriter.setSeries(0); byte[] img = new byte[WriterUtilities.SIZE_X * WriterUtilities.SIZE_Y]; for (int i = 0; i < planeCount; i++) { cwriter.saveBytes(i, img); } cwriter.close(); assertTrue(cFile.exists()); OMETiffReader reader = new OMETiffReader(); reader.setId(companion); assertEquals(reader.getSizeX(), WriterUtilities.SIZE_X); assertEquals(reader.getSizeY(), WriterUtilities.SIZE_Y); assertEquals(reader.getSizeZ(), WriterUtilities.SIZE_Z); assertEquals(reader.getSizeC(), WriterUtilities.SIZE_C); assertEquals(reader.getSizeT(), WriterUtilities.SIZE_T); reader.close(); outFile.deleteOnExit(); cFile.deleteOnExit(); wd.toFile().deleteOnExit(); }
Source:
<code>public static void readLastMessages(String clientNamePrefix, Set<String> brokerSet, String topic, Map<Integer, Pair<byte[], byte[]>> lastMessages) { TopicMetadata tm = KafkaMetadataUtil.getTopicMetadata(brokerSet, topic); if (tm == null) { throw new RuntimeException("Failed to retrieve topic metadata"); } for (PartitionMetadata pm : tm.partitionsMetadata()) { SimpleConsumer consumer = null; try { String clientName = KafkaMetadataUtil.getClientName(clientNamePrefix, tm.topic(), pm.partitionId()); <START> consumer = createSimpleConsumer(clientName, tm.topic(), pm); <END> long readOffset = KafkaMetadataUtil.getLastOffset(consumer, tm.topic(), pm.partitionId(), kafka.api.OffsetRequest.LatestTime(), clientName); FetchRequest req = new FetchRequestBuilder().clientId(clientName) .addFetch(tm.topic(), pm.partitionId(), readOffset - 1, DEFAULT_FETCH_SIZE).build(); FetchResponse fetchResponse = consumer.fetch(req); if (fetchResponse.hasError()) { logger.error("Error fetching data Offset Data the Broker. Reason: " + fetchResponse.errorCode(topic, pm.partitionId())); return; } for (MessageAndOffset messageAndOffset : fetchResponse.messageSet(tm.topic(), pm.partitionId())) { lastMessages.put(pm.partitionId(), kafkaMessageToPair(messageAndOffset.message())); } } finally { if (consumer != null) { consumer.close(); } } } }</code><technical_language>reuse consumer if reading broker</technical_language>

Target:
public static void readLastMessages(String clientNamePrefix, Set<String> brokerSet, String topic, Map<Integer, Pair<byte[], byte[]>> lastMessages) { TopicMetadata tm = KafkaMetadataUtil.getTopicMetadata(brokerSet, topic); if (tm == null) { throw new RuntimeException("Failed to retrieve topic metadata"); } for (PartitionMetadata pm : tm.partitionsMetadata()) { SimpleConsumer consumer = null; try { String clientName = KafkaMetadataUtil.getClientName(clientNamePrefix, tm.topic(), pm.partitionId()); consumer = getOrCreateSimpleConsumer(clientName, tm.topic(), pm); long readOffset = KafkaMetadataUtil.getLastOffset(consumer, tm.topic(), pm.partitionId(), kafka.api.OffsetRequest.LatestTime(), clientName); FetchRequest req = new FetchRequestBuilder().clientId(clientName) .addFetch(tm.topic(), pm.partitionId(), readOffset - 1, DEFAULT_FETCH_SIZE).build(); FetchResponse fetchResponse = consumer.fetch(req); if (fetchResponse.hasError()) { logger.error("Error fetching data Offset Data the Broker. Reason: " + fetchResponse.errorCode(topic, pm.partitionId())); return; } for (MessageAndOffset messageAndOffset : fetchResponse.messageSet(tm.topic(), pm.partitionId())) { lastMessages.put(pm.partitionId(), kafkaMessageToPair(messageAndOffset.message())); } } finally { if (consumer != null) { consumer.close(); } } } }
Source:
<code>public static IntList fromTo(int from, int to) { <START> return new RangeIntList(from, to); <END> }</code><technical_language>Please add a check <=</technical_language>

Target:
public static IntList fromTo(int from, int to) { Preconditions.checkArgument(from <= to); return new RangeIntList(from, to); }
Source:
<code>static String render(Iterator<Token> tokens) { <START> String renderedText = ""; <END> while (tokens.hasNext()) { renderedText += tokens.next().tokenText(); } return renderedText; }</code><technical_language>StringBuilder more natural for this maybe? Passing in iterable iterator avoid some bugs (since iterator is mutable caller forget a copy)</technical_language>

Target:
static String render(Iterator<Token> tokens) { StringBuilder renderedText = new StringBuilder(); while (tokens.hasNext()) { renderedText.append(tokens.next().tokenText()); } return renderedText.toString(); }
Source:
<code>public String rejectArticle(@PathVariable long articleId, @RequestParam(value = "comment", required = false) String comment) { liCaiQuanArticleService.changeArticleStatus(articleId, ArticleStatus.TO_APPROVE); <START> if (null != comment && !comment.equals("")) { <END> liCaiQuanArticleService.rejectArticle(articleId, comment); } return ""; }</code><technical_language>Strings.isNotEnpty()</technical_language>

Target:
public BaseDto<BaseDataDto> rejectArticle(@PathVariable long articleId, @RequestParam(value = "comment", required = false) String comment) { liCaiQuanArticleService.rejectArticle(articleId, comment); return new BaseDto<>(); }
Source:
<code><START> @Override public ReentrantReadWriteLockWithTracking.WriteLock writeLock() { <END> return writeLock; }</code><technical_language>Do need ReentrantReadWriteLockWithTracking.WriteLock here? sense change java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock</technical_language>

Target:
@Override public ReentrantReadWriteLock.WriteLock writeLock() { return writeLock; }
Source:
<code>public ListenableFuture<Response> handle(QosIoExceptionAwareCall call, QosIoException qosIoException) { return qosIoException.getQosException().accept(new QosException.Visitor<ListenableFuture<Response>>() { @Override public ListenableFuture<Response> visit(QosException.Throttle exception) { <START> Optional<Duration> duration = exception.getRetryAfter(); <END> if (duration.isPresent()) { return executorService.schedule( () -> call.clone().execute(), duration.get().toMillis(), TimeUnit.MILLISECONDS); } else { Optional<Duration> backoff = backoffStrategy.nextBackoff(); if (!backoff.isPresent()) { return Futures.immediateFailedFuture(qosIoException); } else { return executorService.schedule( () -> call.clone().execute(), backoff.get().toMillis(), TimeUnit.MILLISECONDS); } } } @Override public ListenableFuture<Response> visit(QosException.RetryOther exception) { return Futures.immediateFailedFuture(qosIoException); } @Override public ListenableFuture<Response> visit(QosException.Unavailable exception) { Optional<Duration> backoff = backoffStrategy.nextBackoff(); if (!backoff.isPresent()) { return Futures.immediateFailedFuture(qosIoException); } else { return executorService.schedule( () -> call.clone().execute(), backoff.get().toMillis(), TimeUnit.MILLISECONDS); } } }); }</code><technical_language>for obvious style thing, try do more java Optional<Duration> backoff = exception.getRetryAfter().isPresent() ? exception.getRetryAfter() : backoffStrategy.nextBackOff() nested if. However, I spend some more time grokking general picture</technical_language>

Target:
public ListenableFuture<Response> handle(QosIoExceptionAwareCall call, QosIoException qosIoException) { return qosIoException.getQosException().accept(new QosException.Visitor<ListenableFuture<Response>>() { @Override public ListenableFuture<Response> visit(QosException.Throttle exception) { Optional<Duration> backoff = exception.getRetryAfter().isPresent() ? exception.getRetryAfter() : backoffStrategy.nextBackoff(); if (!backoff.isPresent()) { return Futures.immediateFailedFuture(qosIoException); } else { return executorService.schedule( () -> call.clone().execute(), backoff.get().toMillis(), TimeUnit.MILLISECONDS); } } @Override public ListenableFuture<Response> visit(QosException.RetryOther exception) { return Futures.immediateFailedFuture(qosIoException); } @Override public ListenableFuture<Response> visit(QosException.Unavailable exception) { Optional<Duration> backoff = backoffStrategy.nextBackoff(); if (!backoff.isPresent()) { return Futures.immediateFailedFuture(qosIoException); } else { return executorService.schedule( () -> call.clone().execute(), backoff.get().toMillis(), TimeUnit.MILLISECONDS); } } }); }