auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void freeSlot(WorkerSlot slot) { String nodeId = slot.getNodeId(); for (SchedulerAssignmentImpl assignment : assignments.values()) { if (assignment.isSlotOccupied(slot)) { String topologyId = assignment.getTopologyId(); assertValidTopologyForModification(topologyId); assignment.unassignBySlot(slot); topoIdToNodeIdToSlotIdToExecutors.computeIfAbsent(topologyId, Cluster::makeMap).computeIfAbsent(nodeId, Cluster::makeMap) .computeIfAbsent(slot.getId(), Cluster::makeSet) .clear(); TopologyDetails td = topologies.getById(topologyId); assignment.setTotalSharedOffHeapNodeMemory( nodeId, calculateSharedOffHeapNodeMemory(nodeId, assignment, td)); nodeToScheduledResourcesCache.computeIfAbsent(nodeId, Cluster::makeMap).put(slot, new NormalizedResourceRequest()); nodeToUsedSlotsCache.computeIfAbsent(nodeId, Cluster::makeSet).remove(slot); } } totalResourcesPerNodeCache.remove(slot.getNodeId()); }

Target:
public void freeSlot(WorkerSlot slot) { final String nodeId = slot.getNodeId(); for (SchedulerAssignmentImpl assignment : assignments.values()) { if (assignment.isSlotOccupied(slot)) { final String topologyId = assignment.getTopologyId(); assertValidTopologyForModification(topologyId); assignment.unassignBySlot(slot); topoIdToNodeIdToSlotIdToExecutors.computeIfAbsent(topologyId, Cluster::makeMap).computeIfAbsent(nodeId, Cluster::makeMap) .computeIfAbsent(slot.getId(), Cluster::makeSet) .clear(); TopologyDetails td = topologies.getById(topologyId); assignment.setTotalSharedOffHeapNodeMemory( nodeId, calculateSharedOffHeapNodeMemory(nodeId, assignment, td)); nodeToScheduledResourcesCache.computeIfAbsent(nodeId, Cluster::makeMap).put(slot, new NormalizedResourceRequest()); nodeToUsedSlotsCache.computeIfAbsent(nodeId, Cluster::makeSet).remove(slot); } } totalResourcesPerNodeCache.remove(nodeId); }
Source:
private String secondaryMessage(int complexity) { if (complexity == 1) { return "+1"; } else{ return String.format("+%s (incl %s for nesting)", complexity, complexity - 1); } }

Target:
private static String secondaryMessage(int complexity) { if (complexity == 1) { return "+1"; } else{ return String.format("+%s (incl. %s for nesting)", complexity, complexity - 1); } }
Source:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { File originalFile = ServletUtils.getFileFromString(request.getPathInfo(), base); Locale locale = getLocaleFromRequest(request); File file = determineActualFile(request, locale); file = checkForIndex(request, response, file, request.getPathInfo()); if(null == file) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } else if(!response.isCommitted()){ Object languagePageShown = request.getSession(true).getAttribute(LANG_PAGE_SHOWN); if(!file.equals(originalFile)) { String redirect = request.getServletPath() + replaceLocaleWithUSLocale(request.getPathInfo(), locale); if((null == languagePageShown || !Boolean.parseBoolean(languagePageShown.toString()))) { request.getSession(true).setAttribute(LANG_PAGE_SHOWN, true); request.setAttribute(LOCALE, locale); request.setAttribute(ENGLISH_HREF, redirect); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/help/no_lang.jsp"); if (dispatcher != null) { dispatcher.include(request, response); } } else { response.sendRedirect(redirect); } } else { ServletUtils.sendFile(request, response, file, type); } } }

Target:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { File originalFile = ServletUtils.makeFileFromSanePath(request.getPathInfo(), base); Locale locale = getLocaleFromRequest(request); File file = determineActualFile(request, locale); file = checkForIndex(request, response, file, request.getPathInfo()); if(null == file) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } else if(!response.isCommitted()){ Object languagePageShown = request.getSession(true).getAttribute(LANG_PAGE_SHOWN); if(!file.equals(originalFile)) { String redirect = request.getServletPath() + replaceLocaleWithUSLocale(request.getPathInfo(), locale); if((null == languagePageShown || !Boolean.parseBoolean(languagePageShown.toString()))) { request.getSession(true).setAttribute(LANG_PAGE_SHOWN, true); request.setAttribute(LOCALE, locale); request.setAttribute(ENGLISH_HREF, redirect); RequestDispatcher dispatcher = request.getRequestDispatcher(LANG_JSP); if (dispatcher != null) { dispatcher.include(request, response); } } else { response.sendRedirect(redirect); } } else { ServletUtils.sendFile(request, response, file, type); } } }
Source:
public static void waitTillInstancesAreCreated(ColoHelper cluster, Entity entity, String startTime, String endTime) throws InterruptedException, IOException, AuthenticationException, URISyntaxException { int sleep = INSTANCES_CREATED_TIMEOUT * 60 / 5; waitTillInstancesAreCreated(cluster, entity, startTime, endTime, sleep); }

Target:
public static void waitTillInstancesAreCreated(ColoHelper cluster, Entity entity, String startTime, String endTime) throws InterruptedException, IOException, AuthenticationException, URISyntaxException { waitTillInstancesAreCreated(cluster, entity, startTime, endTime, INSTANCES_CREATED_TIMEOUT); }
Source:
public void setUp() throws Exception { FileProvider fileProviderA = new FileProviderImpl("ontent-handler-a"); handlerA = new MockFileContentReferenceHandlerImpl("content-handler-a"); ((FileContentReferenceHandlerImpl) handlerA).setFileProvider(fileProviderA); FileProvider fileProviderB = new FileProviderImpl("content-handler-b"); handlerB = new MockFileContentReferenceHandlerImpl("content-handler-b"); ((FileContentReferenceHandlerImpl) handlerB).setFileProvider(fileProviderB); ArrayList<ContentReferenceHandler> delegates = new ArrayList<ContentReferenceHandler>(); delegates.add(handlerA); delegates.add(handlerB); delegatingHandler = new DelegatingContentHandlerImpl(); ((DelegatingContentHandlerImpl) delegatingHandler).setDelegates(delegates); contentReferenceFile1a = getTextReference("/content-handler-a/file-a-1.txt"); contentReferenceFile1b = getTextReference("/content-handler-b/file-b-1.txt"); contentReferenceFile1c = getTextReference("/content-handler-c/file-c-1.txt"); }

Target:
public void setUp() throws Exception { FileProvider fileProviderA = new FileProviderImpl("content-handler-a"); handlerA = new MockFileContentReferenceHandlerImpl("content-handler-a"); ((FileContentReferenceHandlerImpl) handlerA).setFileProvider(fileProviderA); FileProvider fileProviderB = new FileProviderImpl("content-handler-b"); handlerB = new MockFileContentReferenceHandlerImpl("content-handler-b"); ((FileContentReferenceHandlerImpl) handlerB).setFileProvider(fileProviderB); ArrayList<ContentReferenceHandler> delegates = new ArrayList<ContentReferenceHandler>(); delegates.add(handlerA); delegates.add(handlerB); delegatingHandler = new DelegatingContentHandlerImpl(); ((DelegatingContentHandlerImpl) delegatingHandler).setDelegates(delegates); contentReferenceFile1a = getTextReference("/content-handler-a/file-a-1.txt"); contentReferenceFile1b = getTextReference("/content-handler-b/file-b-1.txt"); contentReferenceFile1c = getTextReference("/content-handler-c/file-c-1.txt"); }
Source:
protected Guid getImageGroupId() { if (_imageGroupId.equals(Guid.Empty)) { _imageGroupId = getDiskImage().getId() != null ? getDiskImage().getId() : Guid.Empty; } return _imageGroupId; }

Target:
protected Guid getImageGroupId() { if (imageGroupId.equals(Guid.Empty)) { imageGroupId = getDiskImage().getId() != null ? getDiskImage().getId() : Guid.Empty; } return imageGroupId; }
Source:
public void testResponseTimeout() throws Exception { setServerResponse(false); testWithErrorCodes(Collections.singletonMap(ServerErrorCode.No_Error, 9), serverLayout, RouterErrorCode.OperationTimedOut, new ErrorCodeChecker() { @Override public void check(RouterErrorCode expectedError) throws Exception { future = router.deleteBlob(blobIdString, new ClientCallback()); do { mockTime.sleep(1000); } while (!operationCompleteLatch.await(10, TimeUnit.MILLISECONDS)); checkErrorCode(future, expectedError); } }); }

Target:
public void testResponseTimeout() throws Exception { setServerResponse(false); testWithErrorCodes(Collections.singletonMap(ServerErrorCode.No_Error, 9), serverLayout, RouterErrorCode.OperationTimedOut, new ErrorCodeChecker() { @Override public void testAndAssert(RouterErrorCode expectedError) throws Exception { CountDownLatch operationCompleteLatch = new CountDownLatch(1); future = router.deleteBlob(blobIdString, new ClientCallback(operationCompleteLatch)); do { mockTime.sleep(1000); } while (!operationCompleteLatch.await(10, TimeUnit.MILLISECONDS)); assertFailureAndCheckErrorCode(future, expectedError); } }); }
Source:
private void initializeConfigRepositories() { if (this.hasConfigRepoInitializationCompleted) { return; } if (!this.isConfigLoaded) { return; } List<String> inUseConfigRepoPlugins = this.configRepoService.getConfigRepos().stream().map(RuleAwarePluginProfile::getPluginId).collect(Collectors.toList()); if (this.loadedConfigRepoPlugins.containsAll(inUseConfigRepoPlugins)) { LOGGER.info("[Config Repository Initializer] Start initializing all the config repositories"); this.configRepoService.getConfigRepos().forEach(this::initializeConfigRepository); LOGGER.info("[Config Repository Initializer] Done initializing all the config repositories"); this.hasConfigRepoInitializationCompleted = true; } }

Target:
private void initializeConfigRepositories() { if (!this.isConfigLoaded) { return; } synchronized (this.pluginsQueue) { while (!pluginsQueue.isEmpty()) { String pluginId = pluginsQueue.poll(); LOGGER.info("[Config Repository Initializer] Start initializing the config repositories for plugin '{}' ", pluginId); this.configRepoService.getConfigRepos().stream() .filter(configRepoConfig -> configRepoConfig.getPluginId().equalsIgnoreCase(pluginId)) .forEach(this::initializeConfigRepository); LOGGER.info("[Config Repository Initializer] Done initializing the config repositories for plugin '{}' ", pluginId); } } }
Source:
private List<Future<Void>> executeTasksConcurrently(final List<ConcurrentTestWorker> testWorkers) throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(tasks.size()); final List<Future<Void>> futures = service .invokeAll(testWorkers, iterationTimeoutSeconds * iterations, TimeUnit.SECONDS); service.shutdown(); return futures; }

Target:
private List<Future<Void>> executeTasksConcurrently(final List<ConcurrentTestWorker> testWorkers) throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(tasks.size()); final List<Future<Void>> futures = service .invokeAll(testWorkers, (long) iterationTimeoutSeconds * iterations, TimeUnit.SECONDS); service.shutdown(); return futures; }
Source:
private static byte[] processArrayItem(byte[] bytes) { ArrayList<Byte> boxedBytes = new ArrayList<>(); int start = 0, end = bytes.length - 1; if (bytes[start] == '"') { start += 1; end -= 1; } for (int i = start; i <= end; i++) { if (i < end && (char) bytes[i] == '\\' && ((char) bytes[i + 1] == '\\' || (char) bytes[i + 1] == '\"')) { i++; } boxedBytes.add(bytes[i]); } byte[] unboxedBytes = new byte[boxedBytes.size()]; for (int i = 0; i < boxedBytes.size(); i++) { unboxedBytes[i] = boxedBytes.get(i); } return unboxedBytes; }

Target:
private static byte[] processArrayItem(byte[] bytes) { var itemBytes = new ByteArrayList(); int start = 0, end = bytes.length - 1; if (bytes[start] == '"') { start += 1; end -= 1; } for (int i = start; i <= end; i++) { if (i < end && (char) bytes[i] == '\\' && ((char) bytes[i + 1] == '\\' || (char) bytes[i + 1] == '\"')) { i++; } itemBytes.add(bytes[i]); } return itemBytes.toArray(); }
Source:
public List<TransactionAndImmutableTsLock> setupRunTaskBatchWithConditionThrowOnConflict( List<PreCommitCondition> conditions) { Preconditions.checkArgument(!conditions.isEmpty(), "Trying to start an empty batch"); try (StartIdentifiedAtlasDbTransactionResponseBatch responses = timelockService.startIdentifiedAtlasDbTransactionsBatch(conditions.size())) { if (responses.size() != conditions.size()) { throw new TransactionBatchFailedRetriableException( "The number of transactions started does not match the size of the batch."); } List<TransactionAndImmutableTsLock> transactions = Streams.zip( responses.getResponses().stream(), conditions.stream(), (response, condition) -> wrapResponse(condition, response)).collect(Collectors.toList()); return responses.successful(transactions); } }

Target:
public List<TransactionAndImmutableTsLock> setupRunTaskBatchWithConditionThrowOnConflict( List<PreCommitCondition> conditions) { if (conditions.isEmpty()) { return ImmutableList.of(); } List<StartIdentifiedAtlasDbTransactionResponse> responses = timelockService.startIdentifiedAtlasDbTransactionBatch(conditions.size()); Preconditions.checkState(conditions.size() == responses.size(), "Different number of responses and conditions"); try { long immutableTs = Collections.max(responses.stream() .map(response -> response.immutableTimestamp().getImmutableTimestamp()) .collect(Collectors.toList())); recordImmutableTimestamp(immutableTs); cleaner.punch(responses.get(0).startTimestampAndPartition().timestamp()); return Streams.zip( responses.stream(), conditions.stream(), (response, condition) -> { LockToken immutableTsLock = response.immutableTimestamp().getLock(); Supplier<Long> startTimestampSupplier = Suppliers.ofInstance( response.startTimestampAndPartition().timestamp()); Transaction transaction = createTransaction( immutableTs, startTimestampSupplier, immutableTsLock, condition); return TransactionAndImmutableTsLock.of(transaction, immutableTsLock); }).collect(Collectors.toList()); } catch (Throwable t) { timelockService.tryUnlock( responses.stream() .map(response -> response.immutableTimestamp().getLock()) .collect(Collectors.toSet())); throw Throwables.rewrapAndThrowUncheckedException(t); } }
Source:
public static SleepPeriodResults create(final MainEventTimes mainEventTimes, final Timeline timeline, final SleepScore sleepScore,final SleepStats sleepStats, final OneDaysSensorData sensorData, final TimeZoneOffsetMap timeZoneOffsetMap, final TimelineLog timelineLog, final DataCompleteness dataCompleteness, final boolean processed) { final Results results = new Results(timeline, sleepScore,sleepStats, sensorData, timeZoneOffsetMap); return new SleepPeriodResults(mainEventTimes, Optional.of(results), timelineLog, dataCompleteness, processed); }

Target:
public static SleepPeriodResults create(final MainEventTimes mainEventTimes, final Timeline timeline, final SleepScore sleepScore,final SleepStats sleepStats, final OneDaysSensorData sensorData, final TimeZoneOffsetMap timeZoneOffsetMap, final TimelineLog timelineLog, final DataCompleteness dataCompleteness, final boolean processed) { final Results results = new Results(timeline, sleepScore,sleepStats); final Data data = new Data(sensorData, timeZoneOffsetMap); return new SleepPeriodResults(mainEventTimes, Optional.of(results),Optional.of(data), timelineLog, dataCompleteness, processed); }
Source:
public void addGatewayPublishedAPIArtifacts(String APIId, String gatewayLabel, ByteArrayInputStream bais, int streamLength, String gatewayInstruction, String query) throws APIManagementException { try (Connection connection = GatewayArtifactsMgtDBUtil.getArtifactSynchronizerConnection(); PreparedStatement statement = connection.prepareStatement(query)) { statement.setBinaryStream(1, bais, streamLength); statement.setString(2, gatewayInstruction); statement.setString(3, APIId); statement.setString(4, gatewayLabel); statement.executeUpdate(); } catch (SQLException e) { handleException("Failed to add artifacts for " + APIId, e); } }

Target:
public void addGatewayPublishedAPIArtifacts(String APIId, String gatewayLabel, ByteArrayInputStream bais, int streamLength, String gatewayInstruction, String query) throws APIManagementException { try (Connection connection = GatewayArtifactsMgtDBUtil.getArtifactSynchronizerConnection()) { connection.setAutoCommit(false); try (PreparedStatement statement = connection.prepareStatement(query)) { statement.setBinaryStream(1, bais, streamLength); statement.setString(2, gatewayInstruction); statement.setString(3, APIId); statement.setString(4, gatewayLabel); statement.executeUpdate(); } connection.commit(); } catch (SQLException e) { handleException("Failed to add artifacts for " + APIId, e); } }
Source:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == AppCompatActivity.RESULT_OK) { if (requestCode == REQUEST_ADD_EXCHANGE_RATE) { update(); setResult(RESULT_OK); } } }

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == AppCompatActivity.RESULT_OK) { switch (requestCode) { case REQUEST_ADD_EXCHANGE_RATE: update(); setResult(RESULT_OK); break; default: break; } } }
Source:
private static String getStringValue(ExpressionTree expression) { if (expression.is(Tree.Kind.IDENTIFIER)) { ExpressionTree last = ReassignmentFinder.getClosestReassignmentOrDeclarationExpression(expression, ((IdentifierTree) expression).symbol()); return last == null ? null : getStringValue(last); } return ConstantUtils.resolveAsStringConstant(expression); }

Target:
private static String getStringValue(ExpressionTree expression) { String value = ConstantUtils.resolveAsStringConstant(expression); if (value == null && expression.is(Tree.Kind.IDENTIFIER)) { ExpressionTree last = ReassignmentFinder.getClosestReassignmentOrDeclarationExpression(expression, ((IdentifierTree) expression).symbol()); value = last == null ? null : getStringValue(last); } return value; }
Source:
public long writeTo(WritableByteChannel channel) throws IOException { long written = 0; try { if (sentBytes < sizeInBytes()) { if (bufferToSend == null) { prepareBuffer(); } if (bufferToSend.hasRemaining()) { written = channel.write(bufferToSend); } if (!bufferToSend.hasRemaining() && blob != null) { int totalWrittenBytesForBlob = 0, currentWritten = -1; while (bufferIndex < nioBuffersFromBlob.length && currentWritten != 0) { ByteBuffer byteBuffer = nioBuffersFromBlob[bufferIndex]; currentWritten = channel.write(byteBuffer); totalWrittenBytesForBlob += currentWritten; while (!byteBuffer.hasRemaining()) { bufferIndex++; if (bufferIndex < nioBuffersFromBlob.length) { byteBuffer = nioBuffersFromBlob[bufferIndex]; } else { break; } } } blob.skipBytes(totalWrittenBytesForBlob); written += totalWrittenBytesForBlob; okayToWriteCrc = !blob.isReadable(); } if (okayToWriteCrc && crcBuf.hasRemaining()) { if (blob != null) { blob.release(); blob = null; } written += channel.write(crcBuf); } sentBytes += written; } } catch (Exception e) { if (blob != null) { blob.release(); blob = null; } } return written; }

Target:
public long writeTo(WritableByteChannel channel) throws IOException { long written = 0; try { if (sentBytes < sizeInBytes()) { if (bufferToSend == null) { prepareBuffer(); } if (bufferToSend.hasRemaining()) { written = channel.write(bufferToSend); } if (!bufferToSend.hasRemaining() && blob != null) { int totalWrittenBytesForBlob = 0, currentWritten = -1; while (bufferIndex < nioBuffersFromBlob.length && currentWritten != 0) { currentWritten = -1; ByteBuffer byteBuffer = nioBuffersFromBlob[bufferIndex]; if (!byteBuffer.hasRemaining()) { bufferIndex ++; } else { currentWritten = channel.write(byteBuffer); totalWrittenBytesForBlob += currentWritten; } } blob.skipBytes(totalWrittenBytesForBlob); written += totalWrittenBytesForBlob; okayToWriteCrc = !blob.isReadable(); } if (okayToWriteCrc && crcBuf.hasRemaining()) { if (blob != null) { blob.release(); blob = null; } written += channel.write(crcBuf); } sentBytes += written; } } catch (Exception e) { if (blob != null) { blob.release(); blob = null; } } return written; }
Source:
public void checkStorageDomainNotEqualWithStatusActive() { setStorageDomainStatus(StorageDomainStatus.Active); assertFalse(cmd.checkStorageDomainStatusNotEqual(StorageDomainStatus.Active)); List<String> messages = cmd.getReturnValue().getCanDoActionMessages(); assertEquals(2, messages.size()); assertEquals(messages.get(0), VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2.toString()); assertEquals(messages.get(1), String.format("$status %1$s", StorageDomainStatus.Active)); }

Target:
public void checkStorageDomainNotEqualWithStatusActive() { setStorageDomainStatus(StorageDomainStatus.Active); assertFalse(cmd.checkStorageDomainStatusNotEqual(StorageDomainStatus.Active)); List<String> messages = cmd.getReturnValue().getCanDoActionMessages(); assertEquals(2, messages.size()); assertEquals(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2.toString(), messages.get(0)); assertEquals(String.format("$status %1$s", StorageDomainStatus.Active), messages.get(1)); }
Source:
void findMethodChooseSpecificOverGenericMethod() throws NoSuchMethodException { String methodName = "foo"; Class<?> parameterType = Double.class; Class<?> testClass = InterfaceWithSpecificAndGenericDefaultMethodImpl.class; Method specificMethod = testClass.getMethod(methodName, parameterType); Optional<Method> optional = findMethod(testClass, methodName, parameterType); assertThat(optional).isEqualTo(specificMethod); }

Target:
void findMethodChooseSpecificOverGenericMethod() throws NoSuchMethodException { String methodName = "foo"; Class<?> parameterType = Double.class; Class<?> testClass = InterfaceWithSpecificAndGenericDefaultMethodImpl.class; Method specificMethod = testClass.getMethod(methodName, parameterType); Optional<Method> optional = findMethod(testClass, methodName, parameterType); assertThat(optional).contains(specificMethod); }
Source:
public void testGetFlooders() throws Exception { final EventType eventType = NakadiTestUtils.createEventType(); blacklist(eventType.getName(), BlacklistService.Type.CONSUMER_ET); Thread.sleep(TimeUnit.SECONDS.toMillis(1)); given() .contentType(ContentType.JSON) .get(BLACKLIST_URL) .then() .statusCode(HttpStatus.SC_OK) .content(JSON_HELPER.matchesObject( ImmutableMap.of( "consumers", ImmutableMap.of( "event_types", Collections.singleton(eventType.getName()), "apps", Collections.emptySet()), "producers", ImmutableMap.of( "event_types", Collections.emptySet(), "apps", Collections.emptySet())) ) ); }

Target:
public void testGetFlooders() throws Exception { final EventType eventType = NakadiTestUtils.createEventType(); blacklist(eventType.getName(), BlacklistService.Type.CONSUMER_ET); TestUtils.waitFor(() -> given() .contentType(ContentType.JSON) .get(BLACKLIST_URL) .then() .statusCode(HttpStatus.SC_OK) .content(getFloodersMatcher(eventType)), 1000, 200); }
Source:
private static Event toEvent(IntegrationEvent integrationEvent) { final IntegrationEventContext sourceContext = integrationEvent.getContext(); final EventContext context = EventContext.newBuilder() .setEventId(sourceContext.getEventId()) .setTimestamp(sourceContext.getTimestamp()) .setProducerId(sourceContext.getProducerId()) .setBoundedContextName(sourceContext.getBoundedContextName()) .build(); final Event.Builder result = Event.newBuilder() .setMessage(integrationEvent.getMessage()) .setContext(context); return result.build(); }

Target:
private static Event toEvent(IntegrationEvent integrationEvent) { final IntegrationEventContext sourceContext = integrationEvent.getContext(); final StringValue producerId = newStringValue(sourceContext.getBoundedContextName()); final EventContext context = EventContext.newBuilder() .setEventId(sourceContext.getEventId()) .setTimestamp(sourceContext.getTimestamp()) .setProducerId(toAny(producerId)) .build(); final Event.Builder result = Event.newBuilder() .setMessage(integrationEvent.getMessage()) .setContext(context); return result.build(); }
Source:
public static String getStandardDeviationString(double[] standardDeviationDoubles) { if (standardDeviationDoubles == null) { return null; } StringBuilder standardDeviationString = new StringBuilder(standardDeviationDoubles.length * 9); boolean first = true; for (double standardDeviationDouble : standardDeviationDoubles) { if (first) { first = false; } else { standardDeviationString.append("/"); } String abbreviated = Double.toString(standardDeviationDouble); int dotIndex = abbreviated.lastIndexOf('.'); StringBuilder result = new StringBuilder().append(abbreviated.substring(0, dotIndex < 0 ? abbreviated.length() : dotIndex)); if (dotIndex >= 0) { char[] abbreviatedChars = abbreviated.toCharArray(); for (int i = 0; i < 3; i++) { if (dotIndex + i >= abbreviatedChars.length) { break; } char currentChar = abbreviatedChars[dotIndex + i]; if (Character.isDigit(currentChar) || currentChar == '.') { result = result.append(currentChar); } } int expIndex = abbreviated.lastIndexOf('E'); if (expIndex >= 0) { result = result.append(abbreviated.substring(expIndex)); } } standardDeviationString.append(result.toString()); } return standardDeviationString.toString(); }

Target:
public static String getStandardDeviationString(double[] standardDeviationDoubles) { if (standardDeviationDoubles == null) { return null; } StringBuilder standardDeviationString = new StringBuilder(standardDeviationDoubles.length * 9); DecimalFormat exponentialFormat = new DecimalFormat("0.0#E0"); DecimalFormat decimalFormat = new DecimalFormat("0.0#"); boolean first = true; for (double standardDeviationDouble : standardDeviationDoubles) { if (first) { first = false; } else { standardDeviationString.append("/"); } String abbreviated; if (0.001 <= standardDeviationDouble && standardDeviationDouble <= 10000000.0) { abbreviated = decimalFormat.format(standardDeviationDouble); } else { abbreviated = exponentialFormat.format(standardDeviationDouble); } standardDeviationString.append(abbreviated); } return standardDeviationString.toString(); }
Source:
public String get() { return baseProducer.randomElement("C", "F", "G", "H", "J", "K") + randomNumeric(8); }

Target:
public String get() { return baseProducer.randomElement(PASSPORT_TYPE_LETTERS) + randomNumeric(8); }
Source:
public List<AccountExternalId> byAccountEmail(Account.Id id, String email) { List<AccountExternalId> accIds = byAccountId.get(id).list; ArrayList<AccountExternalId> out = new ArrayList<AccountExternalId>(accIds.size()); for (AccountExternalId extId : accIds){ if(extId.getEmailAddress().equals(email)){ out.add(extId); } } return out; }

Target:
public List<AccountExternalId> byAccountEmail(Account.Id id, String email) { List<AccountExternalId> accIds = byAccountId.get(id).list; ArrayList<AccountExternalId> out = new ArrayList<AccountExternalId>(accIds.size()); for (AccountExternalId extId : accIds) { String accEmail = extId.getEmailAddress(); if (accEmail != null && accEmail.equals(email)) { out.add(extId); } } return out; }
Source:
public boolean onCreateOptionsMenu(Menu menu) { try { if (googleCastDelegate != null && (googleCastDelegate.isConnected() || showGoogleCastButton())) { getMenuInflater().inflate(R.menu.google_cast_menu_item, menu); mediaRouteMenuItem = CastButtonFactory.setUpMediaRouteButton(getApplicationContext(), menu, R.id.media_route_menu_item); if (isInForeground()) { googleCastDelegate.showIntroductoryOverlay(this, mediaRouteMenuItem); } } } catch (Exception e) { logger.error(e); } return super.onCreateOptionsMenu(menu); }

Target:
public boolean onCreateOptionsMenu(Menu menu) { try { if (googleCastDelegate != null && (googleCastDelegate.isConnected() || showGoogleCastButton())) { getMenuInflater().inflate(R.menu.google_cast_menu_item, menu); mediaRouteMenuItem = CastButtonFactory.setUpMediaRouteButton(getApplicationContext(), menu, R.id.media_route_menu_item); if (isInForeground()) { googleCastDelegate.showIntroductoryOverlay(this, mediaRouteMenuItem); } } } catch (Exception e) { logger.error(e, true); } return super.onCreateOptionsMenu(menu); }
Source:
public CalenderModel getCalenderById(Long id) { return modelMapper.getMapper().map(calendarRepo.findById(id), CalenderModel.class); }

Target:
public CalendarModel getCalenderById(Long id) { return modelMapper.getMapper().map(calendarRepo.findById(id), CalendarModel.class); }
Source:
DiskManager(DiskId disk, List<ReplicaId> replicas, StoreConfig config, ScheduledExecutorService scheduler, StorageManagerMetrics metrics, StoreKeyFactory keyFactory, MessageStoreRecovery recovery, MessageStoreHardDelete hardDelete, Time time) { this.disk = disk; this.config = config; this.metrics = metrics; DiskIOScheduler ioScheduler = new DiskIOScheduler(null); for (ReplicaId replica : replicas) { if (disk.equals(replica.getDiskId())) { String storeId = replica.getPartitionId().toString(); BlobStore store = new BlobStore(storeId, config, scheduler, ioScheduler, metrics, replica.getReplicaPath(), replica.getCapacityInBytes(), keyFactory, recovery, hardDelete, time); stores.put(replica.getPartitionId(), store); } } }

Target:
DiskManager(DiskId disk, List<ReplicaId> replicas, StoreConfig config, ScheduledExecutorService scheduler, StorageManagerMetrics metrics, StoreKeyFactory keyFactory, MessageStoreRecovery recovery, MessageStoreHardDelete hardDelete, Time time) { this.disk = disk; this.metrics = metrics; diskIOScheduler = new DiskIOScheduler(null); for (ReplicaId replica : replicas) { if (disk.equals(replica.getDiskId())) { String storeId = replica.getPartitionId().toString(); BlobStore store = new BlobStore(storeId, config, scheduler, diskIOScheduler, metrics, replica.getReplicaPath(), replica.getCapacityInBytes(), keyFactory, recovery, hardDelete, time); stores.put(replica.getPartitionId(), store); } } }
Source:
public EJBClientContext withAddedTransportProviders(EJBTransportProvider... transportProviders) { if (transportProviders == null) { return this; } final int length = transportProviders.length; if (length == 0) { return this; } log.tracef("Creating new EJBClientContext from %s with added transport providers including ", this, transportProviders[0]); final Builder builder = new Builder(this); boolean construct = false; for (EJBTransportProvider transportProvider : transportProviders) { if (transportProvider != null) { builder.addTransportProvider(transportProvider); construct = true; } } return construct ? builder.build() : this; }

Target:
public EJBClientContext withAddedTransportProviders(EJBTransportProvider... transportProviders) { if (transportProviders == null) { return this; } final int length = transportProviders.length; if (length == 0) { return this; } log.tracef("Creating new EJBClientContext from %s with added transport providers including %s", this, transportProviders[0]); final Builder builder = new Builder(this); boolean construct = false; for (EJBTransportProvider transportProvider : transportProviders) { if (transportProvider != null) { builder.addTransportProvider(transportProvider); construct = true; } } return construct ? builder.build() : this; }
Source:
protected void configure() { super.configure(); install(new OkHttpCommandExecutorServiceModule()); bind(new TypeLiteral<Supplier<SSLContext>>() { }).to(new TypeLiteral<SSLContextWithKeysSupplier>() { }); bind(OkHttpClientSupplier.class).to(new TypeLiteral<DockerOkHttpClientSupplier>() {}); }

Target:
protected void configure() { super.configure(); install(new OkHttpCommandExecutorServiceModule()); bind(OkHttpClientSupplier.class).to(DockerOkHttpClientSupplier.class); }
Source:
public SDVariable get(SDIndex... indices){ int ndims = indices.length; int[] begin = new int[ndims]; int[] end = new int[ndims]; int[] strides = new int[ndims]; int[] begin_mask_arr = new int[ndims]; int[] end_mask_arr = new int[ndims]; int[] shrink_axis_mask_arr = new int[ndims]; for(int i=0; i<ndims; i++){ strides[i] = 1; SDIndex index = indices[i]; if(index.indexType == SDIndex.IndexType.ALL){ begin_mask_arr[i] = 1; end_mask_arr[i] = 1; } else if(index.indexType == SDIndex.IndexType.POINT){ if(index.point_index == null){ begin_mask_arr[i] = 1; end_mask_arr[i] = 1; } else { begin[i] = index.point_index; end[i] = index.point_index + 1; shrink_axis_mask_arr[i] = 1; } } else if(index.indexType == SDIndex.IndexType.INTERVAL){ if(index.interval_begin == null){ begin_mask_arr[i] = 1; } else{ begin[i] = index.interval_begin; } if(index.interval_end == null){ end_mask_arr[i] = 1; } else{ end[i] = index.interval_end; } if(index.interval_strides == null){ strides[i] = 1; } else{ strides[i] = index.interval_strides; } } } int begin_mask = binArrToInt(begin_mask_arr); int end_mask = binArrToInt(end_mask_arr); int shrink_axis = binArrToInt(shrink_axis_mask_arr); return this.sameDiff.stridedSlice(this, begin, end, strides, begin_mask, end_mask, 0, 0, shrink_axis); }

Target:
public SDVariable get(SDIndex... indices){ int ndims = indices.length; long[] begin = new long[ndims]; long[] end = new long[ndims]; long[] strides = new long[ndims]; int[] begin_mask_arr = new int[ndims]; int[] end_mask_arr = new int[ndims]; int[] shrink_axis_mask_arr = new int[ndims]; for(int i=0; i<ndims; i++){ strides[i] = 1; SDIndex index = indices[i]; SDIndex.IndexType indexType = index.getIndexType(); if(indexType == SDIndex.IndexType.ALL){ begin_mask_arr[i] = 1; end_mask_arr[i] = 1; } else if(indexType == SDIndex.IndexType.POINT){ long pointIndex = index.getPointIndex(); begin[i] = pointIndex; end[i] = pointIndex + 1; shrink_axis_mask_arr[i] = 1; } else if(indexType == SDIndex.IndexType.INTERVAL){ if(index.getIntervalBegin() == null){ begin_mask_arr[i] = 1; } else{ begin[i] = index.getIntervalBegin(); } if(index.getIntervalEnd() == null){ end_mask_arr[i] = 1; } else{ end[i] = index.getIntervalEnd(); } if(index.getIntervalStrides() == null){ strides[i] = 1; } else{ strides[i] = index.getIntervalStrides(); } } } int begin_mask = binArrToInt(begin_mask_arr); int end_mask = binArrToInt(end_mask_arr); int shrink_axis = binArrToInt(shrink_axis_mask_arr); return this.sameDiff.stridedSlice(this, begin, end, strides, begin_mask, end_mask, 0, 0, shrink_axis); }
Source:
protected Set<String> processPoolUpdates( Map<String, EventBuilder> poolEvents, List<PoolUpdate> updatedPools) { Set<String> entitlementsToRegen = Util.newSet(); for (PoolUpdate updatedPool : updatedPools) { Pool existingPool = updatedPool.getPool(); log.info("Pool changed: {}", updatedPool.toString()); if (!poolCurator.exists(existingPool)) { log.info("Pool has already been deleted from the database."); continue; } if (existingPool.isMarkedForDelete()) { log.warn("Deleting pool as requested by rules: {}", existingPool.getId()); deletePool(existingPool); continue; } this.poolCurator.merge(existingPool); this.poolCurator.flush(); if (updatedPool.getQuantityChanged()) { RevocationPlan revPlan = new RevocationPlan(poolCurator, config); revPlan.setPool(existingPool); revPlan.execute(this); } if (updatedPool.getDatesChanged() || updatedPool.getProductsChanged() || updatedPool.getBrandingChanged()) { List<String> entitlements = poolCurator.retrieveFreeEntitlementIdsOfPool(existingPool); entitlementsToRegen.addAll(entitlements); } EventBuilder builder = poolEvents.get(existingPool.getId()); if (builder != null) { Event event = builder.setNewEntity(existingPool).buildEvent(); sink.queueEvent(event); } else { log.warn("Pool updated without an event builder: {}", existingPool); } } return entitlementsToRegen; }

Target:
protected Set<String> processPoolUpdates( Map<String, EventBuilder> poolEvents, List<PoolUpdate> updatedPools) { Set<String> entitlementsToRegen = Util.newSet(); for (PoolUpdate updatedPool : updatedPools) { Pool existingPool = updatedPool.getPool(); log.info("Pool changed: {}", updatedPool.toString()); if (!poolCurator.exists(existingPool)) { log.info("Pool has already been deleted from the database."); continue; } if (existingPool.isMarkedForDelete()) { log.warn("Deleting pool as requested by rules: {}", existingPool.getId()); deletePool(existingPool); continue; } this.poolCurator.merge(existingPool); this.poolCurator.flush(); if (updatedPool.getQuantityChanged()) { RevocationOp revPlan = new RevocationOp(poolCurator, Collections.singletonList(existingPool)); revPlan.execute(this); } if (updatedPool.getDatesChanged() || updatedPool.getProductsChanged() || updatedPool.getBrandingChanged()) { List<String> entitlements = poolCurator.retrieveOrderedEntitlementIdsOf(existingPool); entitlementsToRegen.addAll(entitlements); } EventBuilder builder = poolEvents.get(existingPool.getId()); if (builder != null) { Event event = builder.setNewEntity(existingPool).buildEvent(); sink.queueEvent(event); } else { log.warn("Pool updated without an event builder: {}", existingPool); } } return entitlementsToRegen; }
Source:
public static MessageNumberSet[] buildMessageNumberSets(@Nullable final String msgNumbers) throws ImapAsyncClientException { if (msgNumbers == null || msgNumbers.isEmpty()) { return null; } final String[] msgSetStrs = msgNumbers.split(","); final MessageNumberSet[] msgSets = new MessageNumberSet[msgSetStrs.length]; int i = 0; for (final String element : msgSetStrs) { if (element.contains(":")) { final String[] elements = element.split(":"); if (elements[1].equals("*")) { msgSets[i] = new MessageNumberSet(Long.valueOf(elements[0]), LastMessage.LAST_MESSAGE); } else { msgSets[i] = new MessageNumberSet(Long.valueOf(elements[0]), Long.valueOf(elements[1])); } } else { if (element.equals("*")) { msgSets[i] = new MessageNumberSet(LastMessage.LAST_MESSAGE); } else { msgSets[i] = new MessageNumberSet(Long.valueOf(element), Long.valueOf(element)); } } i++; } return msgSets; }

Target:
public static MessageNumberSet[] buildMessageNumberSets(@Nullable final String msgNumbers) throws ImapAsyncClientException { if (msgNumbers == null || msgNumbers.isEmpty()) { return null; } final String[] msgSetStrs = msgNumbers.split(","); final MessageNumberSet[] msgSets = new MessageNumberSet[msgSetStrs.length]; int i = 0; for (final String element : msgSetStrs) { if (element.contains(":")) { final String[] elements = element.split(":"); if (elements[1].equals("*")) { msgSets[i] = new MessageNumberSet(Long.parseLong(elements[0]), LastMessage.LAST_MESSAGE); } else if (elements[0].equals("*")) { msgSets[i] = new MessageNumberSet(Long.parseLong(elements[1]), LastMessage.LAST_MESSAGE); } else { msgSets[i] = new MessageNumberSet(Long.parseLong(elements[0]), Long.parseLong(elements[1])); } } else { if (element.equals("*")) { msgSets[i] = new MessageNumberSet(LastMessage.LAST_MESSAGE); } else { final long num = Long.parseLong(element); msgSets[i] = new MessageNumberSet(num, num); } } i++; } return msgSets; }
Source:
private List<Input> fetchDefaultBindings(Class<?> event, BindsConfiguration config) { List<Input> defaultInputs = Lists.newArrayList(); Collection<Input> values = config.getBoundInputs(); for (Annotation annotation : event.getAnnotationsByType(DefaultBinding.class)) { DefaultBinding defaultBinding = (DefaultBinding) annotation; Input input = defaultBinding.type().getInput(defaultBinding.id()); if (!values.contains(input)) { defaultInputs.add(input); } else { logger.warn("Input is already registered, can not use it for event {}", input, event); } } return defaultInputs; }

Target:
private List<Input> fetchDefaultBindings(Class<?> event, BindsConfiguration config) { List<Input> defaultInputs = Lists.newArrayList(); Collection<Input> boundInputs = config.getBoundInputs(); for (Annotation annotation : event.getAnnotationsByType(DefaultBinding.class)) { DefaultBinding defaultBinding = (DefaultBinding) annotation; Input defaultInput = defaultBinding.type().getInput(defaultBinding.id()); if (!boundInputs.contains(defaultInput)) { defaultInputs.add(defaultInput); } else { logger.warn("Input is already registered, can not use it as default for event {}", defaultInput, event); } } return defaultInputs; }
Source:
protected void executeVmCommand() { final VmStatic VM = getVmStaticDAO().get(getParameters().getVmId()); addCustomValue("InterfaceType", (VmInterfaceType.forValue(getInterface().getType()).getDescription()).toString()); this.setVmName(VM.getName()); boolean succeeded = false; boolean macAddedToPool = false; try { if (StringUtils.isEmpty(getMacAddress())) { getInterface().setMacAddress(getMacPool().allocateNewMac()); macAddedToPool = true; } else { macAddedToPool = addMacToPool(getMacAddress()); } getInterface().setSpeed(VmInterfaceType.forValue(getInterface().getType()).getSpeed()); getInterface().setId(Guid.newGuid()); getInterface().setVmId(getParameters().getVmId()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addInterfaceToDb(getInterface()); addInterfaceDeviceToDb(); getCompensationContext().stateChanged(); return null; } }); if (getInterface().isPlugged()) { succeeded = activateOrDeactivateNewNic(getInterface(), PlugAction.PLUG); } else { succeeded = true; } } finally { setSucceeded(succeeded); if (macAddedToPool && !succeeded) { getMacPool().freeMac(getMacAddress()); } } }

Target:
protected void executeVmCommand() { addCustomValue("InterfaceType", (VmInterfaceType.forValue(getInterface().getType()).getDescription()).toString()); this.setVmName(getVmStaticDAO().get(getParameters().getVmId()).getName()); boolean succeeded = false; boolean macAddedToPool = false; try { if (StringUtils.isEmpty(getMacAddress())) { getInterface().setMacAddress(getMacPool().allocateNewMac()); macAddedToPool = true; } else { macAddedToPool = addMacToPool(getMacAddress()); } getInterface().setSpeed(VmInterfaceType.forValue(getInterface().getType()).getSpeed()); getInterface().setId(Guid.newGuid()); getInterface().setVmId(getParameters().getVmId()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { addInterfaceToDb(getInterface()); addInterfaceDeviceToDb(); getCompensationContext().stateChanged(); return null; } }); if (getInterface().isPlugged()) { succeeded = activateOrDeactivateNewNic(getInterface(), PlugAction.PLUG); } else { succeeded = true; } } finally { setSucceeded(succeeded); if (macAddedToPool && !succeeded) { getMacPool().freeMac(getMacAddress()); } } }
Source:
public void testSearchWithDateRange() { SearchParameterMap sp = new SearchParameterMap(); sp.setLoadSynchronous(true); sp.setLastUpdated(new DateRangeParam() .setUpperBound(new DateParam("le2019-02-22T17:50:00")) .setLowerBound(new DateParam("ge2019-02-22T13:50:00"))); IBundleProvider retrieved = myMedicationRequestDao.search(sp); List<String> queries = CaptureQueriesListener .getLastNQueries() .stream() .map(t -> t.getSql(true, true)) .collect(Collectors.toList()); ourLog.info("Queries:\n {}", queries.stream().findFirst()); String searchQuery = queries.get(0); assertEquals(searchQuery, 3, StringUtils.countMatches(searchQuery.toUpperCase(), "HFJ_SPIDX_TOKEN")); assertEquals(searchQuery, 5, StringUtils.countMatches(searchQuery.toUpperCase(), "LEFT OUTER JOIN")); }

Target:
public void testSearchWithDateRange() { SearchParameterMap sp = new SearchParameterMap(); sp.setLoadSynchronous(true); sp.add(MedicationRequest.SP_INTENT, new TokenParam("FOO", "BAR")); sp.setLastUpdated(new DateRangeParam() .setUpperBound(new DateParam("le2019-02-22T17:50:00")) .setLowerBound(new DateParam("ge2019-02-22T13:50:00"))); IBundleProvider retrieved = myMedicationRequestDao.search(sp); List<String> queries = CaptureQueriesListener .getLastNQueries() .stream() .map(t -> t.getSql(true, true)) .collect(Collectors.toList()); ourLog.info("Queries:\n {}", queries.stream().findFirst()); String searchQuery = queries.get(0); assertEquals(searchQuery, 1, StringUtils.countMatches(searchQuery.toUpperCase(), "HFJ_SPIDX_TOKEN")); assertEquals(searchQuery, 1, StringUtils.countMatches(searchQuery.toUpperCase(), "LEFT OUTER JOIN")); assertEquals(searchQuery, 2, StringUtils.countMatches(searchQuery.toUpperCase(), "AND RESOURCETA0_.RES_UPDATED")); }
Source:
protected boolean runKerberosLogin() { try { ShellSecurityImpl.createSecureConfiguration(getProperty(), shell); } catch (Exception e) { return false; } return true; }

Target:
protected boolean runKerberosLogin() { try { ShellSecurityImpl.createSecureConfiguration(getProperty(), shell); } catch (Exception e) { LOGGER.error("Unable to run kinit for zeppelin", e); return false; } return true; }
Source:
private String[] getItemStrings(List<TmfEventTableColumn> columns, ITmfEvent event) { if (event == null) { return EMPTY_STRING_ARRAY; } synchronized (columns) { List<String> itemStrings = new ArrayList<>(columns.size()); int columnIndex = 0; for (TmfEventTableColumn column : columns) { ITmfEvent passedEvent = event; if (!(column instanceof TmfMarginColumn) && (event instanceof CachedEvent)) { passedEvent = ((CachedEvent) event).event; } TableColumn viewColumn = fTable.getColumns()[fColumnOrder[columnIndex]]; if (passedEvent == null || (!viewColumn.getResizable() && viewColumn.getWidth() == 0)) { itemStrings.add(EMPTY_STRING); } else { itemStrings.add(column.getItemString(passedEvent)); } columnIndex++; } return itemStrings.toArray(new String[0]); } }

Target:
private String[] getItemStrings(List<TmfEventTableColumn> columns, ITmfEvent event) { if (event == null) { return EMPTY_STRING_ARRAY; } synchronized (columns) { List<String> itemStrings = new ArrayList<>(columns.size()); for (TableColumn viewColumn : fTable.getColumns()) { TmfEventTableColumn column = columns.get((int) viewColumn.getData(Key.INDEX)); ITmfEvent passedEvent = event; if (!(column instanceof TmfMarginColumn) && (event instanceof CachedEvent)) { passedEvent = ((CachedEvent) event).event; } if (passedEvent == null || (!viewColumn.getResizable() && viewColumn.getWidth() == 0)) { itemStrings.add(EMPTY_STRING); } else { itemStrings.add(column.getItemString(passedEvent)); } } return itemStrings.toArray(new String[itemStrings.size()]); } }
Source:
public String getItemString(ITmfEvent event) { final String EMPTY_STRING = ""; String s = NonNullUtils.nullToEmptyString(fAspect.resolve(event)); if (fAspectDuplicate.size() > 1 && s.equals(EMPTY_STRING)) { for (int i = 1; i < fAspectDuplicate.size(); i++) { String eventString = NonNullUtils.nullToEmptyString(fAspectDuplicate.get(i).resolve(event)); if (eventString != EMPTY_STRING) { s = eventString; } } } return s; }

Target:
public String getItemString(ITmfEvent event) { final String EMPTY_STRING = ""; for (ITmfEventAspect<?> aspect : fAspects) { String eventString = NonNullUtils.nullToEmptyString(aspect.resolve(event)); if(eventString != EMPTY_STRING) { return eventString; } } return EMPTY_STRING; }
Source:
public Account getAccountById(short accountId) { Account primaryResult = primaryAccountService.getAccountById(accountId); Account secondaryResult = secondaryAccountService.getAccountById(accountId); if ((++getAccountRequestCount % 100 < config.samplingPercentageForGetAccountConsistencyCheck) && primaryResult != null && !primaryResult.equals(secondaryResult)) { logger.warn("Inconsistency detected between primary and secondary for accountId ={}", accountId); accountServiceMetrics.getAccountDataInconsistencyCount.inc(); } return primaryResult; }

Target:
public Account getAccountById(short accountId) { Account primaryResult = primaryAccountService.getAccountById(accountId); if (shouldCompare()) { Account secondaryResult = secondaryAccountService.getAccountById(accountId); if (primaryResult != null && !primaryResult.equals(secondaryResult)) { logger.warn("Inconsistency detected between primary and secondary for accountId ={}", accountId); accountServiceMetrics.accountDataInconsistencyCount.inc(); } } return primaryResult; }