auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public FenixLessonSummary(Shift shift, DateTime lessonDate, Space space, LessonInstance lessonInstance) { this.shift = shift.getExternalId(); this.shiftName = shift.getPresentationName(); this.shiftType = shift.getSortedTypes().first().getFullNameTipoAula(); this.lessonDate = lessonDate.toString("yyyy-MM-dd HH:mm:ss"); this.room = space != null ? new FenixSpace.Room(space) : null; if(lessonInstance != null && lessonInstance.getSummary() != null) { summary = new FenixSummary(lessonInstance.getSummary()); } }

Target:
public FenixLessonSummary(Shift shift, DateTime lessonDate, Space space, LessonInstance lessonInstance) { this.shift = shift.getExternalId(); this.shiftName = shift.getPresentationName(); this.shiftType = !shift.getSortedTypes().isEmpty() ? shift.getSortedTypes().first().getFullNameTipoAula() : null; this.lessonDate = lessonDate.toString("yyyy-MM-dd HH:mm:ss"); this.room = space != null ? new FenixSpace.Room(space) : null; if(lessonInstance != null && lessonInstance.getSummary() != null) { summary = new FenixSummary(lessonInstance.getSummary()); } }
Source:
public void suspendAccepts() { handle.suspend(0); suspendedDueToWatermark = false; }

Target:
public void suspendAccepts() { synchronized (this) { handle.suspend(SelectionKey.OP_ACCEPT); suspended = true; } }
Source:
public Object aggregate(List values) { if (values == null || values.isEmpty()) { return null; } List sorted = (List) values.stream().sorted().collect(Collectors.toList()); Object result = sorted.get(sorted.size()-1); return result instanceof Number ? round((Number) result, precission) : result; }

Target:
public Object aggregate(List values) { if (values == null || values.isEmpty()) { return null; } Comparable result = null; for (Object obj : values) { Comparable val = (Comparable) obj; if (val == null) { continue; } if (result == null || val.compareTo(result) > 0) { result = val; } } return result instanceof Number ? round((Number) result, precission) : result; }
Source:
public void run() { try { if ((!_shouldRefreshCache.isPresent() && ( _clusterEventType.equals(ClusterEventType.PeriodicalRebalance) || _clusterEventType .equals(ClusterEventType.OnDemandRebalance))) || (_shouldRefreshCache.isPresent() && _shouldRefreshCache.get())) { requestDataProvidersFullRefresh(); HelixDataAccessor accessor = _manager.getHelixDataAccessor(); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); Map<String, LiveInstance> liveInstanceMap = accessor.getChildValuesMap(keyBuilder.liveInstances()); if (liveInstanceMap != null && !liveInstanceMap.isEmpty()) { NotificationContext changeContext = new NotificationContext(_manager); changeContext.setType(NotificationContext.Type.CALLBACK); synchronized (_manager) { checkLiveInstancesObservation(new ArrayList<>(liveInstanceMap.values()), changeContext); } } } forceRebalance(_manager, _clusterEventType); } catch (Throwable ex) { logger.error("Time task failed. Rebalance task type: " + _clusterEventType + ", cluster: " + _clusterName, ex); } }

Target:
public void run() { try { if (_shouldRefreshCacheOption.orElse( _clusterEventType.equals(ClusterEventType.PeriodicalRebalance) || _clusterEventType .equals(ClusterEventType.OnDemandRebalance))) { requestDataProvidersFullRefresh(); HelixDataAccessor accessor = _manager.getHelixDataAccessor(); PropertyKey.Builder keyBuilder = accessor.keyBuilder(); Map<String, LiveInstance> liveInstanceMap = accessor.getChildValuesMap(keyBuilder.liveInstances()); if (liveInstanceMap != null && !liveInstanceMap.isEmpty()) { NotificationContext changeContext = new NotificationContext(_manager); changeContext.setType(NotificationContext.Type.CALLBACK); synchronized (_manager) { checkLiveInstancesObservation(new ArrayList<>(liveInstanceMap.values()), changeContext); } } } forceRebalance(_manager, _clusterEventType); } catch (Throwable ex) { logger.error("Time task failed. Rebalance task type: " + _clusterEventType + ", cluster: " + _clusterName, ex); } }
Source:
public Map generateSprite(String[] urls, Map options) throws IOException { options.put("urls", urls); return generateSprite(options); }

Target:
public Map generateSprite(String[] urls, Map options) throws IOException { if (options == null) options = Collections.singletonMap("urls", urls); else options.put("urls", urls); return callApi("sprite", buildGenerateSpriteParams(options), options, null); }
Source:
private static boolean checkDecimal(Number number, BigDecimal min, BigDecimal max) { BigDecimal bigDecimal = null; if (number instanceof Integer || number instanceof Long) { bigDecimal = new BigDecimal(number.doubleValue()); } else if (number instanceof Float || number instanceof Double) { double doubleValue = number.doubleValue(); if (!Double.isNaN(doubleValue) && doubleValue != Double.NEGATIVE_INFINITY && doubleValue != Double.POSITIVE_INFINITY) { bigDecimal = new BigDecimal(doubleValue); } else { return false; } } else if (number instanceof BigInteger) { bigDecimal = new BigDecimal((BigInteger) number); } else if (number instanceof BigDecimal) { bigDecimal = (BigDecimal) number; } else { double doubleValue = number.doubleValue(); if (!Double.isNaN(doubleValue) && doubleValue != Double.NEGATIVE_INFINITY && doubleValue != Double.POSITIVE_INFINITY) { bigDecimal = new BigDecimal(doubleValue); } else { return false; } } { return max.compareTo(bigDecimal) >= 0 && min.compareTo(bigDecimal) <= 0; } }

Target:
private static boolean checkDecimal(Number number, BigDecimal min, BigDecimal max) { BigDecimal bigDecimal = null; if (number instanceof Integer || number instanceof Long) { bigDecimal = new BigDecimal(number.doubleValue()); } else if (number instanceof Float || number instanceof Double) { double doubleValue = number.doubleValue(); if (!Double.isNaN(doubleValue) && !Double.isInfinite(doubleValue)) { bigDecimal = new BigDecimal(doubleValue); } else { return false; } } else if (number instanceof BigInteger) { bigDecimal = new BigDecimal((BigInteger) number); } else if (number instanceof BigDecimal) { bigDecimal = (BigDecimal) number; } else { double doubleValue = number.doubleValue(); if (!Double.isNaN(doubleValue) && !Double.isInfinite(doubleValue)) { bigDecimal = new BigDecimal(doubleValue); } else { return false; } } { return max.compareTo(bigDecimal) >= 0 && min.compareTo(bigDecimal) <= 0; } }
Source:
private boolean isTenantRowCell(Cell cell) { ImmutableBytesWritable key = new ImmutableBytesWritable(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()); return key.get()[key.getOffset()] != QueryConstants.SEPARATOR_BYTE; }

Target:
private boolean isTenantRowCell(Cell cell) { return cell.getRowArray()[cell.getRowOffset()] != QueryConstants.SEPARATOR_BYTE; }
Source:
public void closeAndRecycleState() { prepareClose(true); close(true, true); log.info("Closed clean and recycled state"); }

Target:
public void closeAndRecycleState() { prepareClose(true); if (state() == State.CREATED || state() == State.RUNNING) { stateMgr.checkpoint(Collections.emptyMap()); offsetSnapshotSinceLastCommit = new HashMap<>(stateMgr.changelogOffsets()); stateMgr.recycle(); } else { throw new IllegalStateException("Illegal state " + state() + " while closing standby task " + id); } closeTaskSensor.record(); transitionTo(State.CLOSED); log.info("Closed clean and recycled state"); }
Source:
protected String getProtocol(HttpRequestAttributes attributes) { String protocol = attributes.getScheme(); if (protocol == null) { String uri = attributes.getRequestUri(); Matcher m = Pattern.compile("^(http|https|.+)://.*$").matcher(uri); if (m.matches()) { protocol = m.group(1); } else { protocol = "http"; } } return protocol; }

Target:
protected String getProtocol(HttpRequestAttributes attributes) { String protocol = attributes.getScheme(); return protocol; }
Source:
public Void execute(Context context) { RegistryContext registryContext = (RegistryContext) context; DMNContext dmnContext = registryContext .computeIfAbsent(DMNContext.class, clazz -> DMNFactory.newContext()); dmnContext.set(name, value); return null; }

Target:
public Void execute(Context context) { RegistryContext registryContext = (RegistryContext) context; DMNContext dmnContext = registryContext .computeIfAbsent(DMNContext.class, clazz -> { DMNRuntime dmnRuntime = registryContext.lookup(DMNRuntime.class); return dmnRuntime != null ? dmnRuntime.newContext() : DMNFactory.newContext(); }); dmnContext.set(name, value); return null; }
Source:
public void testDataModelAttributeSerializable() { try { String filename = "DynamicDataModelAttribute.tmp"; IDataModelAttribute dataModelAttribute = new DynamicDataModelAttribute(DataModelConstants.TYPE_NONE); writeObjectToFile(dataModelAttribute, filename); Object readObject = readObjectFromFile(filename); IOUtility.deleteFile(filename); assertTrue(readObject instanceof IDataModelAttribute); assertEquals(((IDataModelAttribute) readObject).getType(), DataModelConstants.TYPE_NONE); } catch (Throwable t) { fail(t.toString()); } }

Target:
public void testDataModelAttributeSerializable() { try { File tmpFile = IOUtility.createTempFile("DynamicDataModelAttribute", "tmp", null); IDataModelAttribute dataModelAttribute = new DynamicDataModelAttribute(DataModelConstants.TYPE_NONE); writeObjectToFile(dataModelAttribute, tmpFile); Object readObject = readObjectFromFile(tmpFile); tmpFile.delete(); assertTrue(readObject instanceof IDataModelAttribute); assertEquals(((IDataModelAttribute) readObject).getType(), DataModelConstants.TYPE_NONE); } catch (Throwable t) { fail(t.toString()); } }
Source:
public TreasureChestItemIterator iterator(ItemType itemType) { return new TreasureChestItemIterator(this, itemType); }

Target:
public Iterator<Item> iterator(ItemType itemType) { return new TreasureChestItemIterator(this, itemType); }
Source:
public Interval liftOver(final Interval interval, final double liftOverMinMatch) { if (interval.length() == 0) { throw new IllegalArgumentException("Zero-length interval cannot be lifted over. Interval: " + interval.getName()); } Chain chainHit = null; TargetIntersection targetIntersection = null; double minMatchSize = liftOverMinMatch * interval.length(); for (final Chain chain : chains.getOverlaps(interval)) { final TargetIntersection candidateIntersection = targetIntersection(chain, interval); if (candidateIntersection != null && candidateIntersection.intersectionLength >= minMatchSize) { if (chainHit != null) { return null; } chainHit = chain; targetIntersection = candidateIntersection; } else if (candidateIntersection != null) { if (logFailedIntervals){ LOG.info("Interval " + interval.getName() + " failed to match chain " + chain.id + " because intersection length " + candidateIntersection.intersectionLength + " < minMatchSize " + minMatchSize + " (" + (candidateIntersection.intersectionLength/(float)interval.length()) + " < " + liftOverMinMatch + ")"); } } } if (chainHit == null) { return null; } return createToInterval(interval.getName(), interval.isNegativeStrand(), targetIntersection); }

Target:
public Interval liftOver(final Interval interval, final double liftOverMinMatch) { if (interval.length() == 0) { throw new IllegalArgumentException("Zero-length interval cannot be lifted over. Interval: " + interval.getName()); } Chain chainHit = null; TargetIntersection targetIntersection = null; double minMatchSize = liftOverMinMatch * interval.length(); boolean hasOverlapBelowThreshold = false; for (final Chain chain : chains.getOverlaps(interval)) { final TargetIntersection candidateIntersection = targetIntersection(chain, interval); if (candidateIntersection != null && candidateIntersection.intersectionLength >= minMatchSize) { if (chainHit != null) { return null; } chainHit = chain; targetIntersection = candidateIntersection; } else if (candidateIntersection != null) { hasOverlapBelowThreshold = true; if (logFailedIntervals) { LOG.info("Interval " + interval.getName() + " failed to match chain " + chain.id + " because intersection length " + candidateIntersection.intersectionLength + " < minMatchSize " + minMatchSize + " (" + (candidateIntersection.intersectionLength/(float)interval.length()) + " < " + liftOverMinMatch + ")"); } } } if (chainHit == null) { if (hasOverlapBelowThreshold) { totalFailedIntervalsBelowThreshold++; } return null; } return createToInterval(interval.getName(), interval.isNegativeStrand(), targetIntersection); }
Source:
public void importKerasConvnetTheanoConfigTest() throws Exception { ClassLoader classLoader = getClass().getClassLoader(); String configFilename = classLoader.getResource("keras/config/cnn_th_config.json").getPath(); importKerasConfigTest(configFilename); }

Target:
public void importKerasConvnetTheanoConfigTest() throws Exception { ClassPathResource resource = new ClassPathResource("keras/config/cnn_th_config.json", ModelConfigurationTest.class.getClassLoader()); String configFilename = resource.getFile().getAbsolutePath(); importKerasConfigTest(configFilename); }
Source:
public static VdsStatic map(Host model, VdsStatic template) { VdsStatic entity = template != null ? template : new VdsStatic(); if (model.isSetId()) { entity.setId(GuidUtils.asGuid(model.getId())); } if (model.isSetName()) { entity.setVdsName(model.getName()); } if (model.isSetCluster() && model.getCluster().isSetId()) { entity.setVdsGroupId(GuidUtils.asGuid(model.getCluster().getId())); } if (model.isSetAddress()) { entity.setHostName(model.getAddress()); } if (model.isSetPort() && model.getPort() > 0) { entity.setPort(model.getPort()); } else { entity.setPort(DEFAULT_VDSM_PORT); } if (model.isSetSsh() && model.getSsh().isSetUser() && model.getSsh().getUser().isSetUserName()) { entity.setSshUsername(model.getSsh().getUser().getUserName()); } else { entity.setSshUsername(DEFAULT_ROOT_USERNAME); } if (model.isSetSsh() && model.getSsh().isSetPort() && model.getSsh().getPort() > 0) { entity.setSshPort(model.getSsh().getPort()); } else { entity.setSshPort(DEFAULT_SSH_PORT); } if (model.isSetSsh() && model.getSsh().isSetFingerprint()) { entity.setSshKeyFingerprint(model.getSsh().getFingerprint()); } if (model.isSetPowerManagement()) { entity = map(model.getPowerManagement(), entity); } if (model.isSetStorageManager()) { if (model.getStorageManager().getPriority() != null) { entity.setVdsSpmPriority(model.getStorageManager().getPriority()); } } if (model.isSetDisplay() && model.getDisplay().isSetAddress()) { entity.setConsoleAddress("".equals(model.getDisplay().getAddress()) ? null : model.getDisplay().getAddress()); } return entity; }

Target:
public static VdsStatic map(Host model, VdsStatic template) { VdsStatic entity = template != null ? template : new VdsStatic(); if (model.isSetId()) { entity.setId(GuidUtils.asGuid(model.getId())); } if (model.isSetName()) { entity.setVdsName(model.getName()); } if (model.isSetCluster() && model.getCluster().isSetId()) { entity.setVdsGroupId(GuidUtils.asGuid(model.getCluster().getId())); } if (model.isSetAddress()) { entity.setHostName(model.getAddress()); } if (model.isSetPort() && model.getPort() > 0) { entity.setPort(model.getPort()); } else { entity.setPort(DEFAULT_VDSM_PORT); } if (model.isSetSsh() && model.getSsh().isSetPort() && model.getSsh().getPort() > 0) { entity.setSshPort(model.getSsh().getPort()); } else { entity.setSshPort(DEFAULT_SSH_PORT); } if (model.isSetSsh() && model.getSsh().isSetFingerprint()) { entity.setSshKeyFingerprint(model.getSsh().getFingerprint()); } if (model.isSetPowerManagement()) { entity = map(model.getPowerManagement(), entity); } if (model.isSetStorageManager()) { if (model.getStorageManager().getPriority() != null) { entity.setVdsSpmPriority(model.getStorageManager().getPriority()); } } if (model.isSetDisplay() && model.getDisplay().isSetAddress()) { entity.setConsoleAddress("".equals(model.getDisplay().getAddress()) ? null : model.getDisplay().getAddress()); } return entity; }
Source:
private void updateMemberDomainsFormat(StorageFormatType targetFormat) { Guid spId = getStoragePool().getId(); StorageDomainStaticDAO sdStatDao = DbFacade.getInstance().getStorageDomainStaticDAO(); List<storage_domain_static> domains = sdStatDao.getAllForStoragePool(spId); for (storage_domain_static domain : domains) { StorageDomainType sdType = domain.getstorage_domain_type(); log.info("Updating storage domain \"" + domain.getId() + "\" (type \"" + sdType + "\") to format \"" + targetFormat + "\""); if (sdType != StorageDomainType.Data && sdType != StorageDomainType.Master) { continue; } domain.setStorageFormat(targetFormat); sdStatDao.update(domain); } }

Target:
private void updateMemberDomainsFormat(StorageFormatType targetFormat) { Guid spId = getStoragePool().getId(); StorageDomainStaticDAO sdStatDao = DbFacade.getInstance().getStorageDomainStaticDAO(); List<storage_domain_static> domains = sdStatDao.getAllForStoragePool(spId); for (storage_domain_static domain : domains) { StorageDomainType sdType = domain.getstorage_domain_type(); log.infoFormat("Updating storage domain {0} (type {1}) to format {2}", domain.getId(), sdType, targetFormat); if (sdType != StorageDomainType.Data && sdType != StorageDomainType.Master) { continue; } domain.setStorageFormat(targetFormat); sdStatDao.update(domain); } }
Source:
void removeReplica(ReplicaId id) { partitionToReplicaMap.remove(id.getPartitionId()); logger.info(id.getPartitionId() + " is removed from StatsManager"); }

Target:
boolean removeReplica(ReplicaId id) { boolean success = partitionToReplicaMap.remove(id.getPartitionId()) != null; if (success) { logger.info(id.getPartitionId() + " is removed from StatsManager"); } else { logger.error("Failed to remove " + id.getPartitionId() + " because it doesn't exist in StatsManager"); } return success; }
Source:
public final void close() throws Exception { if (this.contextManager != null) { this.contextManager.close(); } operatorImplGraph.close(); }

Target:
public void close() throws Exception { if (this.contextManager != null) { this.contextManager.close(); } operatorImplGraph.close(); }
Source:
public void setAttribute(final String key, final Object value) { super.setAttribute(key, value); if (key.equals(SORT_ORDER_TAG) || key.equals(GROUP_ORDER_TAG)) { this.setAttribute(key, value.toString()); } else { super.setAttribute(key, value); } }

Target:
public void setAttribute(final String key, final Object value) { if (key.equals(SORT_ORDER_TAG) || key.equals(GROUP_ORDER_TAG)) { this.setAttribute(key, value.toString()); } else { super.setAttribute(key, value); } }
Source:
public <T> void onProvision(ProvisionInvocation<T> provision) { SingletonScopeInjectorProvider.setCurrentInjector(this.injector); final T injectee = provision.provision(); if (injectee == null) { return; } if (injectee instanceof LifecycleListener) { if (manager == null) { pendingLifecycleListeners.add((LifecycleListener) injectee); } else { manager.addListener((LifecycleListener) injectee); } } }

Target:
public <T> void onProvision(ProvisionInvocation<T> provision) { SingletonScopeInjectorProvider.setCurrentInjectorIfAbsent(this.injector); final T injectee = provision.provision(); if (injectee == null) { return; } if (injectee instanceof LifecycleListener) { if (manager == null) { pendingLifecycleListeners.add((LifecycleListener) injectee); } else { manager.addListener((LifecycleListener) injectee); } } }
Source:
private static void logCreateEntitlementWithAOs(final StringBuilder logLine, final String externalKey, final Iterable<EntitlementSpecifier> entitlementSpecifiers, final LocalDate entitlementDate, final LocalDate billingDate) { if (externalKey != null) { logLine.append("bundle key='") .append(externalKey) .append("'"); } if (entitlementDate != null) { if (externalKey != null) { logLine.append(", "); } logLine.append("entDate='") .append(entitlementDate) .append("'"); } if (billingDate != null) { if (externalKey != null || entitlementDate != null) { logLine.append(", "); } logLine.append("billDate='") .append(billingDate) .append("'"); } if (entitlementSpecifiers != null && entitlementSpecifiers.iterator().hasNext()) { if (externalKey != null || entitlementDate != null || billingDate != null) { logLine.append(", "); } logEntitlementSpecifier(logLine, entitlementSpecifiers); } }

Target:
private static void logCreateEntitlementWithAOs(final StringBuilder logLine, final String externalKey, final Iterable<EntitlementSpecifier> entitlementSpecifiers, final LocalDate entitlementDate, final LocalDate billingDate) { if (externalKey != null) { logLine.append("bundleKey='") .append(externalKey) .append("'"); } if (entitlementDate != null) { if (externalKey != null) { logLine.append(", "); } logLine.append("entDate='") .append(entitlementDate) .append("'"); } if (billingDate != null) { if (externalKey != null || entitlementDate != null) { logLine.append(", "); } logLine.append("billDate='") .append(billingDate) .append("'"); } if (entitlementSpecifiers != null && entitlementSpecifiers.iterator().hasNext()) { if (externalKey != null || entitlementDate != null || billingDate != null) { logLine.append(", "); } logEntitlementSpecifier(logLine, entitlementSpecifiers); } }
Source:
public SpringJdbcTemplateSamlClientDaoImpl(final DataSource dataSource, final LobHandler lobHandler, final String tableName, final String environment) { super(); if (dataSource == null) { throw new IllegalArgumentException("Data source must not be null."); } if (lobHandler == null) { throw new IllegalArgumentException("LOB handler must not be null."); } if (StringUtils.isBlank(tableName)) { throw new IllegalArgumentException("Table name must not be null or empty."); } if (StringUtils.isBlank(environment)) { throw new IllegalArgumentException("Environment must not be null or empty."); } this.onlyNamesRowMapper = new OnlyNamesRowMapper(); this.fullRowMapper = new SamlClientConfigurationRowMapper(lobHandler); this.template = new JdbcTemplate(dataSource); this.environment = environment; this.selectAllNamesSqlText = String.format(SELECT_ALL_NAMES_SQL_TEXT, tableName); this.selectAllClientsSqlText = String.format(SELECT_ALL_CLIENTS_SQL_TEXT, tableName); this.selectSingleClientSqlText = String.format(SELECT_SINGLE_CLIENT_SQL_TEXT, tableName); this.selectAllNamesParameters = new Object[] {environment}; this.selectAllClientsParameters = new Object[] {environment}; this.selectAllNamesParameterTypes = new int[] {Types.VARCHAR}; this.selectAllClientsParameterTypes = new int[] {Types.VARCHAR}; this.selectSingleClientParameterTypes = new int[] {Types.VARCHAR, Types.VARCHAR}; }

Target:
public SpringJdbcTemplateSamlClientDaoImpl(final DataSource dataSource, final LobHandler lobHandler, final String tableName, final String environment) { super(); CommonHelper.assertNotNull("dataSource", dataSource); CommonHelper.assertNotNull("lobHandler", lobHandler); CommonHelper.assertNotBlank("tableName", tableName); CommonHelper.assertNotBlank("environment", environment); this.onlyNamesRowMapper = new OnlyNamesRowMapper(); this.fullRowMapper = new SamlClientConfigurationRowMapper(lobHandler); this.template = new JdbcTemplate(dataSource); this.environment = environment; this.selectAllNamesSqlText = String.format(SELECT_ALL_NAMES_SQL_TEXT, tableName); this.selectAllClientsSqlText = String.format(SELECT_ALL_CLIENTS_SQL_TEXT, tableName); this.selectSingleClientSqlText = String.format(SELECT_SINGLE_CLIENT_SQL_TEXT, tableName); this.selectAllNamesParameters = new Object[] {environment}; this.selectAllClientsParameters = new Object[] {environment}; this.selectAllNamesParameterTypes = new int[] {Types.VARCHAR}; this.selectAllClientsParameterTypes = new int[] {Types.VARCHAR}; this.selectSingleClientParameterTypes = new int[] {Types.VARCHAR, Types.VARCHAR}; }
Source:
public BaseResponseDto getReferrerStatistics(@RequestBody BaseParamDto paramDto){ return mobileAppReferrerStatisticsService.getReferrerStatistics(paramDto); }

Target:
public BaseResponseDto getReferrerStatistics(@RequestBody BaseParamDto paramDto){ paramDto.getBaseParam().setUserId(getLoginName()); return mobileAppReferrerStatisticsService.getReferrerStatistics(paramDto); }
Source:
public void revokeAccessTokens(String id, String token) { AccessToken accessToken = new AccessToken.Builder(token).build(); try { connector.revokeAllAccessTokens(id, accessToken); } catch (ConnectionInitializationException e) { LOGGER.warn(String.format("Unable to revoke access token on auth-server %s: %s", authServerHome, e.getMessage())); throw e; } catch(OsiamRequestException e) { LOGGER.warn("Error when revoking all access tokens", e); throw e; } }

Target:
public void revokeAccessTokens(String id, String token) { AccessToken accessToken = new AccessToken.Builder(token).build(); try { connector.revokeAllAccessTokens(id, accessToken); } catch (ConnectionInitializationException e) { LOGGER.warn(String.format("Unable to revoke access token on auth-server %s: %s", authServerHome, e.getMessage())); throw e; } catch(OsiamRequestException e) { LOGGER.warn("Error revoking all access tokens", e); throw e; } }
Source:
static String trimTrailingWhitespaces(String s) { if (hasLength(s) == false) { return s; } int endIdx = -1; for (int i = s.length() - 1; (i >= 0) && (endIdx < 0); i--) { if (Character.isWhitespace(s.charAt(i)) == false) { endIdx = i; } } if (endIdx < 0) { return EMPTY; } return s.substring(0, endIdx + 1); }

Target:
static String trimTrailingWhitespaces(String s) { if (hasLength(s) == false) { return s; } int i = s.length() - 1; while (i >= 0 && Character.isWhitespace(s.charAt(i))) { i--; } return s.substring(0, i + 1); }
Source:
private CompletableFuture<CallFilteringResult> scheduleFilter(CallFilter filter, BlockingQueue<CallFilter> filtersQueue) { CallFilteringResult result = new CallFilteringResult.Builder() .setShouldAllowCall(true) .setShouldReject(false) .setShouldSilence(false) .setShouldAddToCallLog(true) .setShouldShowNotification(true) .setCall(mCall) .build(); for (CallFilter dependencyFilter : filter.getDependencies()) { result = result.combine(mResults.get(dependencyFilter)); } final CallFilteringResult input = result; CompletableFuture<CallFilteringResult> startFuture = CompletableFuture.supplyAsync(() -> input); PostFilterTask postFilterTask = new PostFilterTask(filter, filtersQueue, mResults); CompletableFuture<CallFilteringResult> future = startFuture .thenApplyAsync(filter::startFilterLookup) .thenApplyAsync(postFilterTask::whenDone); return future; }

Target:
private CompletableFuture<CallFilteringResult> scheduleFilter(CallFilter filter, BlockingQueue<CallFilter> filtersQueue) { CallFilteringResult result = new CallFilteringResult.Builder() .setShouldAllowCall(true) .setShouldReject(false) .setShouldSilence(false) .setShouldAddToCallLog(true) .setShouldShowNotification(true) .setCall(mCall) .build(); for (CallFilter dependencyFilter : filter.getDependencies()) { result = result.combine(dependencyFilter.getResult()); } final CallFilteringResult input = result; CompletableFuture<CallFilteringResult> startFuture = CompletableFuture.supplyAsync(() -> input); PostFilterTask postFilterTask = new PostFilterTask(filter); return startFuture .thenApplyAsync(filter::startFilterLookup) .thenApplyAsync(postFilterTask::whenDone); }
Source:
public void provisionSnapshotTrash(String[] argv) throws IOException { Path p = new Path(argv[1]); final HdfsAdmin admin = new HdfsAdmin(p.toUri(), getConf()); try { admin.provisionSnapshottableDirTrash(p); } catch (SnapshotException e) { throw new RemoteException(e.getClass().getName(), e.getMessage()); } System.out.println("Provision of snapshot trash in " + argv[1] + " succeeded"); }

Target:
public void provisionSnapshotTrash(String[] argv) throws IOException { Path p = new Path(argv[1]); final HdfsAdmin admin = new HdfsAdmin(p.toUri(), getConf()); Path trashRoot; try { trashRoot = admin.provisionSnapshotTrash(p); } catch (SnapshotException e) { throw new RemoteException(e.getClass().getName(), e.getMessage()); } System.out.println("Successfully provisioned snapshot trash at " + trashRoot); }
Source:
public void run() { long current = new Date().getTime(); Date otherCutoff = new Date(current - MAIN_TABLES_AGE_LIMIT_SECONDS.getValue() * SECOND_MILLIS); cleanupLabelTables(otherCutoff); cleanupExternalHandlerExternalHandlerProcessMapTables(otherCutoff); cleanupTableByQuery(MOUNT_DELETE_QUERY, "mount", otherCutoff); cleanupTableByQuery(SECRET_CLEANUP_VSPM_QUERY, "volume_storage_pool_map", otherCutoff); cleanupTableByQuery(SECRET_CLEAUP_VOLUME_QUERY, "volume", otherCutoff); Date processInstanceCutoff = new Date(current - PROCESS_INSTANCE_AGE_LIMIT_SECONDS.get() * SECOND_MILLIS); cleanup("process_instance", processInstanceTables, processInstanceCutoff); Date eventTableCutoff = new Date(current - EVENT_AGE_LIMIT_SECONDS.get() * SECOND_MILLIS); cleanupServiceEventTable(eventTableCutoff); cleanup("event", eventTables, eventTableCutoff); Date auditLogCutoff = new Date(current - AUDIT_LOG_AGE_LIMIT_SECONDS.get() * SECOND_MILLIS); cleanup("audit_log", auditLogTables, auditLogCutoff); Date serviceLogCutoff = new Date(current - SERVICE_LOG_AGE_LIMIT_SECONDS.get() * SECOND_MILLIS); cleanup("service_log", serviceLogTables, serviceLogCutoff); cleanup("main", otherTables, otherCutoff); }

Target:
public void run() { long current = new Date().getTime(); Date otherCutoff = new Date(current - MAIN_TABLES_AGE_LIMIT_SECONDS.getValue() * SECOND_MILLIS); cleanupLabelTables(otherCutoff); cleanupExternalHandlerExternalHandlerProcessMapTables(otherCutoff); cleanupTableByQuery(MOUNT_DELETE_QUERY, "mount", otherCutoff); Date processInstanceCutoff = new Date(current - PROCESS_INSTANCE_AGE_LIMIT_SECONDS.get() * SECOND_MILLIS); cleanup("process_instance", processInstanceTables, processInstanceCutoff); Date eventTableCutoff = new Date(current - EVENT_AGE_LIMIT_SECONDS.get() * SECOND_MILLIS); cleanupServiceEventTable(eventTableCutoff); cleanup("event", eventTables, eventTableCutoff); Date auditLogCutoff = new Date(current - AUDIT_LOG_AGE_LIMIT_SECONDS.get() * SECOND_MILLIS); cleanup("audit_log", auditLogTables, auditLogCutoff); Date serviceLogCutoff = new Date(current - SERVICE_LOG_AGE_LIMIT_SECONDS.get() * SECOND_MILLIS); cleanup("service_log", serviceLogTables, serviceLogCutoff); cleanup("main", otherTables, otherCutoff); cleanupTableByQuery(SECRET_CLEANUP_VSPM_QUERY, "volume_storage_pool_map", otherCutoff); cleanupTableByQuery(SECRET_CLEAUP_VOLUME_QUERY, "volume", otherCutoff); }
Source:
public void executeATakesAsAServlet() throws Exception { final String name = "webapp"; final HttpServer server = HttpServer.createSimpleServer("./", 18080); final WebappContext context = new WebappContext(name); final ServletRegistration servlet = context.addServlet( "takes", SrvTake.class ); servlet.setInitParameter("take", TkServletApp.class.getName()); servlet.addMapping("/test"); context.deploy(server); server.start(); new JdkRequest("http://localhost:18080/test") .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .assertBody( new StringContains( new FormattedText( "Hello servlet! Using [%s] ServletContext.", name ).asString() ) ); server.shutdownNow(); }

Target:
public void executeATakesAsAServlet() throws Exception { final String name = "webapp"; final HttpServer server = HttpServer.createSimpleServer("./", 18080); final WebappContext context = new WebappContext(name); final ServletRegistration servlet = context.addServlet( "takes", SrvTake.class ); servlet.setInitParameter("take", TkApp.class.getName()); servlet.addMapping("/test"); context.deploy(server); server.start(); new JdkRequest("http://localhost:18080/test") .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .assertBody( new StringContains( new FormattedText( SrvTakeTest.MSG, name ).asString() ) ); server.shutdownNow(); }
Source:
public static Object createProxy(final Class<?> type, final IProxyTargetLocator locator) { if (PRIMITIVES.contains(type) || Enum.class.isAssignableFrom(type)) { return locator.locateProxyTarget(); } else if (type.isInterface()) { JdkHandler handler = new JdkHandler(type, locator); try { return Proxy.newProxyInstance(resolveClassLoader(), new Class[] { type, Serializable.class, ILazyInitProxy.class, IWriteReplace.class }, handler); } catch (IllegalArgumentException e) { return Proxy.newProxyInstance(LazyInitProxyFactory.class.getClassLoader(), new Class[] { type, Serializable.class, ILazyInitProxy.class, IWriteReplace.class }, handler); } } else { CGLibInterceptor handler = new CGLibInterceptor(type, locator) { @Override public Object intercept(Object object, Method method, Object[] args, MethodProxy proxy) throws Throwable { return super.intercept(object, method, args, proxy); } }; Callback[] callbacks = new Callback[2]; callbacks[CGLIB_CALLBACK_NO_OVERRIDE] = new SerializableNoOpCallback(); callbacks[CGLIB_CALLBACK_HANDLER] = handler; Enhancer e = new Enhancer(); e.setClassLoader(resolveClassLoader()); e.setInterfaces(new Class[] { Serializable.class, ILazyInitProxy.class, IWriteReplace.class }); e.setSuperclass(type); e.setCallbackFilter(new CGLibCallbackFilter()); e.setCallbacks(callbacks); e.setNamingPolicy(WicketNamingPolicy.INSTANCE); return e.create(); } }

Target:
public static Object createProxy(final Class<?> type, final IProxyTargetLocator locator) { if (PRIMITIVES.contains(type) || Enum.class.isAssignableFrom(type)) { return locator.locateProxyTarget(); } else if (type.isInterface()) { JdkHandler handler = new JdkHandler(type, locator); try { return Proxy.newProxyInstance(resolveClassLoader(), new Class[] { type, Serializable.class, ILazyInitProxy.class, IWriteReplace.class }, handler); } catch (IllegalArgumentException e) { return Proxy.newProxyInstance(LazyInitProxyFactory.class.getClassLoader(), new Class[] { type, Serializable.class, ILazyInitProxy.class, IWriteReplace.class }, handler); } } else { CGLibInterceptor handler = new CGLibInterceptor(type, locator); Callback[] callbacks = new Callback[2]; callbacks[CGLIB_CALLBACK_NO_OVERRIDE] = new SerializableNoOpCallback(); callbacks[CGLIB_CALLBACK_HANDLER] = handler; Enhancer e = new Enhancer(); e.setClassLoader(resolveClassLoader()); e.setInterfaces(new Class[] { Serializable.class, ILazyInitProxy.class, IWriteReplace.class }); e.setSuperclass(type); e.setCallbackFilter(new NoOpForProtectedMethodsCGLibCallbackFilter()); e.setCallbacks(callbacks); e.setNamingPolicy(WicketNamingPolicy.INSTANCE); return e.create(); } }
Source:
public void clearSwapDir() throws IOException { if (! m_blockPathMap.isEmpty()) { throw new IllegalStateException("Attempt to clear swap directory when " + "there are still managed blocks; use releaseAllBlocks() instead"); } try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(m_largeQuerySwapPath)) { Iterator<Path> it = dirStream.iterator(); while (it.hasNext()) { Path path = it.next(); VoltFile.recursivelyDelete(path.toFile()); } } }

Target:
private void clearSwapDir() throws IOException { if (! m_blockPathMap.isEmpty()) { throw new IllegalStateException("Attempt to clear swap directory when " + "there are still managed blocks; use releaseAllBlocks() instead"); } try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(m_largeQuerySwapPath)) { Iterator<Path> it = dirStream.iterator(); while (it.hasNext()) { Path path = it.next(); VoltFile.recursivelyDelete(path.toFile()); } } }
Source:
protected ToStringHelper string() { ToStringHelper toString = Objects.toStringHelper("").omitNullValues(); toString.add("keyName", keyName); if (securityGroupNames.size() > 0) toString.add("securityGroupNames", securityGroupNames); if (metadata.size() > 0) toString.add("metadata", metadata); if (personality.size() > 0) toString.add("personality", personality); if (adminPass != null) toString.add("adminPassPresent", true); if (diskConfig != null) toString.add("diskConfig", diskConfig); toString.add("userData", userData == null ? null : new String(userData)); if (!networks.isEmpty()) toString.add("networks", networks); toString.add("availability_zone", availabilityZone == null ? null : availabilityZone); toString.add("configDrive", configDrive); if (!blockDeviceMapping.isEmpty()) toString.add("blockDeviceMapping", blockDeviceMapping); return toString; }

Target:
protected ToStringHelper string() { ToStringHelper toString = MoreObjects.toStringHelper("").omitNullValues(); toString.add("keyName", keyName); if (!securityGroupNames.isEmpty()) toString.add("securityGroupNames", securityGroupNames); if (!metadata.isEmpty()) toString.add("metadata", metadata); if (!personality.isEmpty()) toString.add("personality", personality); if (adminPass != null) toString.add("adminPassPresent", true); if (diskConfig != null) toString.add("diskConfig", diskConfig); toString.add("userData", userData == null ? null : new String(userData)); if (!networks.isEmpty()) toString.add("networks", networks); toString.add("availability_zone", availabilityZone == null ? null : availabilityZone); toString.add("configDrive", configDrive); if (!blockDeviceMapping.isEmpty()) toString.add("blockDeviceMapping", blockDeviceMapping); return toString; }
Source:
public static Slice stInteriorRingN(@SqlType(GEOMETRY_TYPE_NAME) Slice input, @SqlType(INTEGER) long index) { OGCGeometry geometry = deserialize(input); validateType("ST_InteriorRingN", geometry, EnumSet.of(POLYGON)); if (geometry.isEmpty()) { return null; } OGCPolygon polygon = (OGCPolygon) geometry; if (index < 1 || index > polygon.numInteriorRing()) { return null; } OGCGeometry interiorRing = polygon.interiorRingN((int) index - 1); return serialize(interiorRing); }

Target:
public static Slice stInteriorRingN(@SqlType(GEOMETRY_TYPE_NAME) Slice input, @SqlType(INTEGER) long index) { OGCGeometry geometry = deserialize(input); validateType("ST_InteriorRingN", geometry, EnumSet.of(POLYGON)); OGCPolygon polygon = (OGCPolygon) geometry; if (index < 1 || index > polygon.numInteriorRing()) { return null; } OGCGeometry interiorRing = polygon.interiorRingN(toIntExact(index) - 1); return serialize(interiorRing); }
Source:
protected void processAffinityGroup(AffinityGroupVMMapVO vmGroupMapping, DeploymentPlan plan, VirtualMachine vm) { if (vmGroupMapping != null) { AffinityGroupVO group = _affinityGroupDao.findById(vmGroupMapping.getAffinityGroupId()); s_logger.debug("Processing affinity group " + group.getName() + " for VM Id: " + vm.getId()); List<Long> groupVMIds = _affinityGroupVMMapDao.listVmIdsByAffinityGroup(group.getId()); groupVMIds.remove(vm.getId()); List<Long> preferredHosts = getPreferredHostsFromGroupVMIds(groupVMIds); plan.setPreferredHosts(preferredHosts); } }

Target:
protected void processAffinityGroup(AffinityGroupVMMapVO vmGroupMapping, DeploymentPlan plan, VirtualMachine vm) { AffinityGroupVO group = _affinityGroupDao.findById(vmGroupMapping.getAffinityGroupId()); s_logger.debug("Processing affinity group " + group.getName() + " for VM Id: " + vm.getId()); List<Long> groupVMIds = _affinityGroupVMMapDao.listVmIdsByAffinityGroup(group.getId()); groupVMIds.remove(vm.getId()); List<Long> preferredHosts = getPreferredHostsFromGroupVMIds(groupVMIds); plan.setPreferredHosts(preferredHosts); }
Source:
public ByteBufferReadableStreamChannel(List<ByteBuffer> bufferList) { if (bufferList != null) { buffers = bufferList; } else { buffers = new ArrayList<>(); } buffers.add(null); size = computeSize(bufferList); }

Target:
public ByteBufferReadableStreamChannel(List<ByteBuffer> bufferList) { if (bufferList == null || bufferList.isEmpty()) { throw new IllegalArgumentException( "Input List of ByteBuffer cannot be null/empty for ByteBufferReadableStreamChannel"); } buffers = bufferList; size = computeSize(bufferList); }
Source:
public static @NonNull JsReplyProxyImpl forInvocationHandler( @NonNull InvocationHandler invocationHandler) { final JsReplyProxyBoundaryInterface boundaryInterface = BoundaryInterfaceReflectionUtil.castToSuppLibClass( JsReplyProxyBoundaryInterface.class, invocationHandler); return (JsReplyProxyImpl) boundaryInterface.getOrCreatePeer( () -> new JsReplyProxyImpl(boundaryInterface)); }

Target:
public static JsReplyProxyImpl forInvocationHandler( @NonNull InvocationHandler invocationHandler) { final JsReplyProxyBoundaryInterface boundaryInterface = BoundaryInterfaceReflectionUtil.castToSuppLibClass( JsReplyProxyBoundaryInterface.class, invocationHandler); return (JsReplyProxyImpl) boundaryInterface.getOrCreatePeer( () -> new JsReplyProxyImpl(boundaryInterface)); }
Source:
public void all_validUsers() { UserStore userStore = new SharedPrefsUserStore(InstrumentationRegistry.getContext()); SyncManager.setUserStore(userStore); userStore.put(UserStore.CURRENT_USER_KEY, SyncTestUtils.createTestUser(Long.MIN_VALUE)); userStore.put(UserStore.CURRENT_USER_KEY, SyncTestUtils.createTestUser(Long.MAX_VALUE)); Collection<User> users = User.all(); assertEquals(1, users.size()); }

Target:
public void all_validUsers() { UserStore userStore = new SharedPrefsUserStore(InstrumentationRegistry.getContext()); SyncManager.setUserStore(userStore); userStore.put(UserStore.CURRENT_USER_KEY, SyncTestUtils.createTestUser(Long.MIN_VALUE)); userStore.put(UserStore.CURRENT_USER_KEY, SyncTestUtils.createTestUser(Long.MAX_VALUE)); Collection<User> users = User.all(); assertEquals(1, users.size()); assertTrue(users.iterator().next().isValid()); }
Source:
ResponseEntity<Object> ImportThumbnail(@PathVariable("pid") String pid, @RequestParam("file") MultipartFile thumbnailFile) throws Exception { AgentPrincipals agent = AgentPrincipals.createFromThread(); String mimeType = thumbnailFile.getContentType(); Map<String, Object> result = new HashMap<>(); result.put("action", "editThumbnail"); result.put("username", agent.getUsername()); try (InputStream importStream = thumbnailFile.getInputStream()) { service.run(importStream, agent, pid, mimeType); } catch (IOException e) { log.error("Failed to get submitted file", e); result.put("error", e.getMessage()); return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR); } catch (IllegalArgumentException e) { log.error("Error queueing the job", e); result.put("error", e.getMessage()); return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR); } result.put("destination", pid); return new ResponseEntity<>(result, HttpStatus.OK); }

Target:
ResponseEntity<Object> ImportThumbnail(@PathVariable("pid") String pid, @RequestParam("file") MultipartFile thumbnailFile) throws Exception { AgentPrincipals agent = AgentPrincipals.createFromThread(); String mimeType = thumbnailFile.getContentType(); Map<String, Object> result = new HashMap<>(); result.put("action", "editThumbnail"); result.put("username", agent.getUsername()); try (InputStream importStream = thumbnailFile.getInputStream()) { service.run(importStream, agent, pid, mimeType); } catch (IOException e) { log.error("Failed to get submitted file", e); result.put("error", e.getMessage()); return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR); } catch (IllegalArgumentException e) { log.error("Error queueing the job", e); result.put("error", e.getMessage()); return new ResponseEntity<>(result, HttpStatus.UNSUPPORTED_MEDIA_TYPE); } result.put("destination", pid); return new ResponseEntity<>(result, HttpStatus.OK); }
Source:
public DLNAThumbnailInputStream getThumbnailInputStream() throws IOException { if (thumbURL != null) { return DLNAThumbnailInputStream.toThumbnailInputStream( FileUtil.isUrl(thumbURL) ? downloadAndSend(thumbURL, true) : new FileInputStream(thumbURL) ); } else { try (DLNAThumbnailInputStream dtis = super.getThumbnailInputStream()) { return dtis; } } }

Target:
public DLNAThumbnailInputStream getThumbnailInputStream() throws IOException { if (thumbURL != null) { return DLNAThumbnailInputStream.toThumbnailInputStream( FileUtil.isUrl(thumbURL) ? downloadAndSend(thumbURL, true) : new FileInputStream(thumbURL) ); } else { DLNAThumbnailInputStream dtis = super.getThumbnailInputStream(); return dtis; } }
Source:
private static Map<RuleKey, RuleDefinitionDto> buildDbRulesByDbDeprecatedKey(Set<SingleDeprecatedRuleKey> dbDeprecatedKeys, Map<RuleKey, RuleDefinitionDto> dbRules) { Map<Integer, Set<SingleDeprecatedRuleKey>> dbDeprecatedKeysById = dbDeprecatedKeys.stream() .collect(Collectors.groupingBy(SingleDeprecatedRuleKey::getRuleId, Collectors.toSet())); Map<Integer, RuleDefinitionDto> dbRulesByRuleId = dbRules.values().stream() .collect(uniqueIndex(RuleDefinitionDto::getId)); ImmutableMap.Builder<RuleKey, RuleDefinitionDto> builder = ImmutableMap.builder(); for (Map.Entry<Integer, Set<SingleDeprecatedRuleKey>> entry : dbDeprecatedKeysById.entrySet()) { Integer ruleId = entry.getKey(); RuleDefinitionDto rule = dbRulesByRuleId.get(ruleId); if (rule == null) { LOG.warn("Could not retrieve rule with id %s referenced by a deprecated rule key. " + "The following deprecated rule keys seem to be referencing a non-existing rule", ruleId, entry.getValue()); } else { entry.getValue().forEach(d -> builder.put(d.getOldRuleKeyAsRuleKey(), rule)); } } return builder.build(); }

Target:
private static Map<RuleKey, RuleDefinitionDto> buildDbRulesByDbDeprecatedKey(Set<SingleDeprecatedRuleKey> dbDeprecatedKeys, Map<RuleKey, RuleDefinitionDto> dbRules) { Map<Integer, RuleDefinitionDto> dbRulesByRuleId = dbRules.values().stream() .collect(uniqueIndex(RuleDefinitionDto::getId)); ImmutableMap.Builder<RuleKey, RuleDefinitionDto> builder = ImmutableMap.builder(); for (SingleDeprecatedRuleKey entry : dbDeprecatedKeys) { Integer ruleId = entry.getRuleId(); RuleDefinitionDto rule = dbRulesByRuleId.get(ruleId); if (rule == null) { LOG.warn("Could not retrieve rule with id %s referenced by a deprecated rule key. " + "The following deprecated rule keys seem to be referencing a non-existing rule", ruleId, entry); } else { builder.put(entry.getOldRuleKeyAsRuleKey(), rule); } } return builder.build(); }
Source:
public void addPartition(String partitionName) { ReplicaId localReplica = storeManager.getReplica(partitionName); List<? extends ReplicaId> leaderReplicas = localReplica.getPartitionId().getReplicaIdsByState(ReplicaState.LEADER, null); List<ReplicaId> peerLeaderReplicas = new ArrayList<>(); for (ReplicaId leaderReplica : leaderReplicas) { if (leaderReplica.getDataNodeId() != localReplica.getDataNodeId()) { peerLeaderReplicas.add(leaderReplica); logger.info("Partition on node instance is leader in remote dc {}", partitionName, getInstanceName(leaderReplica.getDataNodeId().getHostname(), leaderReplica.getDataNodeId().getPort()), leaderReplica.getDataNodeId().getDatacenterName()); } } rwLock.writeLock().lock(); try { peerLeaderReplicasByPartition.put(partitionName, new HashSet<>(peerLeaderReplicas)); } finally { rwLock.writeLock().unlock(); } }

Target:
public void addPartition(String partitionName) { ReplicaId localReplica = storeManager.getReplica(partitionName); rwLock.writeLock().lock(); try { List<? extends ReplicaId> leaderReplicas = localReplica.getPartitionId().getReplicaIdsByState(ReplicaState.LEADER, null); Set<ReplicaId> peerLeaderReplicas = new HashSet<>(); for (ReplicaId leaderReplica : leaderReplicas) { if (leaderReplica.getDataNodeId() != localReplica.getDataNodeId()) { peerLeaderReplicas.add(leaderReplica); logger.info("Partition on node instance is leader in remote dc {}", partitionName, getInstanceName(leaderReplica.getDataNodeId().getHostname(), leaderReplica.getDataNodeId().getPort()), leaderReplica.getDataNodeId().getDatacenterName()); } } peerLeaderReplicasByPartition.put(partitionName, peerLeaderReplicas); } finally { rwLock.writeLock().unlock(); } }