auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public CloneCommand() { super( "clone", "Clones a section of the world.", "/clone <x1> <y1> <z1> <x2> <y2> <z2> <x> <y> <z> [maskMode] [cloneMode] [tileName] [tileData]", Collections.emptyList() ); setPermission("minecraft.command.seed"); }

Target:
public CloneCommand() { super( "clone", "Clones a section of the world.", "/clone <x1> <y1> <z1> <x2> <y2> <z2> <x> <y> <z> [maskMode] [cloneMode] [tileName] [tileData]", Collections.emptyList() ); setPermission("minecraft.command.clone"); }
Source:
public synchronized ApiFuture<Void> add(RowMutationEntry rowMutation) { Preconditions.checkNotNull(rowMutation, "mutation details cannot be null"); final ApiFuture<Void> response = bulkMutateBatcher.add(rowMutation); operationAccountant.registerOperation(ApiFutureUtil.adapt(response)); return response; }

Target:
public synchronized ApiFuture<Void> add(RowMutationEntry rowMutation) { Preconditions.checkNotNull(rowMutation, "mutation details cannot be null"); return bulkMutateBatcher.add(rowMutation); }
Source:
public void close() throws IOException { List<ListenableFuture<Void>> closingChannelsFutures = new ArrayList<>(); ListeningExecutorService listenableBatchPool = MoreExecutors.listeningDecorator(batchPool); for (final Closeable clientCloseHandler : clientCloseHandlers) { closingChannelsFutures.add(listenableBatchPool.submit(new Callable<Void>() { @Override public Void call() throws Exception { clientCloseHandler.close(); return null; } })); } try { Futures.allAsList(closingChannelsFutures).get(); } catch (InterruptedException e) { Thread.interrupted(); throw new IOException("Interrupted while waiting for close", e); } catch (ExecutionException e) { throw new IOException("Exception while waiting for close", e); } elg.shutdownGracefully(); scheduledRetries.shutdown(); awaiteTerminated(scheduledRetries); if (terminateBatchPool) { batchPool.shutdown(); awaiteTerminated(batchPool); } }

Target:
public void close() throws IOException { List<ListenableFuture<Void>> closingChannelsFutures = new ArrayList<>(); ListeningExecutorService listenableBatchPool = MoreExecutors.listeningDecorator(batchPool); for (final Closeable clientCloseHandler : clientCloseHandlers) { closingChannelsFutures.add(listenableBatchPool.submit(new Callable<Void>() { @Override public Void call() throws Exception { clientCloseHandler.close(); return null; } })); } try { Futures.allAsList(closingChannelsFutures).get(); } catch (InterruptedException e) { Thread.interrupted(); throw new IOException("Interrupted while waiting for channels to be closed", e); } catch (ExecutionException e) { throw new IOException("Exception while waiting for channels to be closed", e); } elg.shutdownGracefully(); scheduledRetries.shutdown(); awaiteTerminated(scheduledRetries); if (terminateBatchPool) { batchPool.shutdown(); awaiteTerminated(batchPool); } }
Source:
private CodecConfigurationException getError(final Exception cause) { return new CodecConfigurationException(format("Unable to get value for property '%s' in %s", propertyMetadata.getName(), propertyMetadata.getTypeData().getType()), cause); }

Target:
private CodecConfigurationException getError(final Exception cause) { return new CodecConfigurationException(format("Unable to get value for property '%s' in %s", propertyMetadata.getName(), propertyMetadata.getDeclaringClassName()), cause); }
Source:
public static List<String> getList(RenderingContext ctx, String key) { Object value = ctx.getParameter(key); if (value instanceof String) { return Arrays.asList((String) value); } else if (value instanceof List) { List<?> values = (List<?>) value; List<String> list = new ArrayList<>(values.size()); for (Object val : values) { if (val != null) { list.add(val.toString()); } } return list; } return Collections.emptyList(); }

Target:
public static List<String> getList(RenderingContext ctx, String key) { Object value = ctx.getParameter(key); if (value == null) { return Collections.emptyList(); } return ((List<String>) value).stream().filter(Objects::nonNull).collect(Collectors.toList()); }
Source:
public RitualCreate() { for (Ritual i : BloodMagic.RITUAL_MANAGER.getRituals()) { addSubcommand(new CommandTreeBase() { public Ritual ritual = i; @Override public String getName() { return this.ritual.getName(); } @Override public String getUsage(ICommandSender sender) { return new TextComponentTranslation(this.ritual.getUnlocalizedName() + ".info").getFormattedText(); } @Override public void execute(MinecraftServer server, ICommandSender sender, String... args) throws CommandException { EntityPlayerMP player = args.length < 2 ? getCommandSenderAsPlayer(sender) : getPlayer(server, sender, args[0]); boolean safe = false; if (args.length > 0 && args.length < 3) { int k = args.length - 1; if (args[k].equals("true") || args[k].equals("false")) { safe = Boolean.parseBoolean(args[k]); } else if (args[0].equals("safe")) safe = true; } BlockPos pos = player.getPosition().down(); World world = player.getEntityWorld(); EnumFacing direction = EnumFacing.NORTH; if (RitualHelper.createRitual(world, pos, direction, this.ritual, safe)) sender.sendMessage(new TextComponentTranslation("commands.bloodmagic.success")); else sender.sendMessage(new TextComponentTranslation("commands.bloodmagic.ritual.create.error.outOfWorldBoundaries")); } }); addSubcommand(new CommandTreeHelp(this)); } }

Target:
public RitualCreate() { for (Ritual ritual : BloodMagic.RITUAL_MANAGER.getRituals()) { ritualList.add(BloodMagic.RITUAL_MANAGER.getId(ritual)); } }
Source:
private void getMocksForAnnotatedFields(Class<?> testClass) { for (Field field : testClass.getDeclaredFields()) { if (field.isAnnotationPresent(ReplaceWithMock.class)) { overrideModules.add(new MockitoOverrideModule(field.getAnnotation(ReplaceWithMock.class), field.getType())); } if (field.isAnnotationPresent(WrapWithSpy.class)) { spyTargets.add(Key.get(field.getType())); } } }

Target:
private void getMocksForAnnotatedFields(Class<?> testClass) { for (Field field : testClass.getDeclaredFields()) { if (field.isAnnotationPresent(ReplaceWithMock.class)) { overrideModules.add(new MockitoOverrideModule<>(field.getAnnotation(ReplaceWithMock.class), field.getType())); } if (field.isAnnotationPresent(WrapWithSpy.class)) { WrapWithSpy spyAnnotation = field.getAnnotation(WrapWithSpy.class); if (spyAnnotation.name().isEmpty()) { spyTargets.add(Key.get(field.getType())); } else { spyTargets.add(Key.get(field.getType(), Names.named(spyAnnotation.name()))); } } } }
Source:
public long getEtag(final Organization organization) { final SqlQuery sqlQuery = Ebean.createSqlQuery("SELECT etag from portal.alerts_etags where organization = ?;"); final models.ebean.Organization ebeanOrganization = models.ebean.Organization.findByOrganization(organization); if (ebeanOrganization != null) { sqlQuery.setParameter(1, ebeanOrganization.getId()); final SqlRow row = sqlQuery.findUnique(); if (row != null) { return row.getLong("etag"); } } return 0; }

Target:
public long getEtag(final Organization organization) { return AlertEtags.getEtagByOrganization(organization); }
Source:
public static int maxMemorySizeWithHotplugInMb(int osId, Version compatibilityVersion) { final ConfigValues configValue = getMaxMemConfigValueByOsId(osId); return Config.<Integer>getValue( configValue, (compatibilityVersion != null) ? compatibilityVersion.getValue() : Version.getLast().getValue() ); }

Target:
public static int maxMemorySizeWithHotplugInMb(int osId, Version compatibilityVersion) { final ConfigValues configValue = getMaxMemConfigValueByOsId(osId); return Config.<Integer>getValue( configValue, compatibilityVersion != null ? compatibilityVersion.getValue() : Version.getLast().getValue() ); }
Source:
public void clear() { if (null != writer) { writer.close(); metadata = null; writer = null; } reset(); }

Target:
void clear() { if (nCompletedConcurrentTasks.get() < nEnqueuedConcurrentTasks) { LOG.error().$("new block should have been either committed or cancelled [table=").$(writer.getName()).$(']').$(); completePendingConcurrentTasks(true); } metadata = null; writer = null; partWriter = null; for (int i = 0; i < nextPartitionBlockWriterIndex; i++) { partitionBlockWriters.getQuick(i).clear(); } nextPartitionBlockWriterIndex = 0; partitionBlockWriterByTimestamp.clear(); }
Source:
S3Exception(S3ErrorCode error, String message, Throwable cause, Map<String, String> elements) { super(requireNonNull(message), cause); this.error = requireNonNull(error); this.message = message; this.elements = ImmutableMap.copyOf(elements); }

Target:
S3Exception(S3ErrorCode error, String message, Throwable cause, Map<String, String> elements) { super(requireNonNull(message), cause); this.error = requireNonNull(error); this.elements = ImmutableMap.copyOf(elements); }
Source:
public final FunctionDesc getFunction(final String signature, FunctionType funcType, DataType... paramTypes) throws AmbiguousFunctionException, UndefinedFunctionException { final GetFunctionMetaRequest.Builder builder = GetFunctionMetaRequest.newBuilder(); builder.setSignature(signature); if (funcType != null) { builder.setFunctionType(funcType); } for (DataType type : paramTypes) { builder.addParameterTypes(type); } try { final BlockingInterface stub = getStub(); final FunctionResponse response = stub.getFunctionMeta(null, builder.build()); throwsIfThisError(response.getState(), UndefinedFunctionException.class); throwsIfThisError(response.getState(), AmbiguousFunctionException.class); ensureOk(response.getState()); return new FunctionDesc(response.getFunction()); } catch (ServiceException se) { throw new RuntimeException(se); } catch (ClassNotFoundException e) { throw new TajoInternalError(e); } }

Target:
public final FunctionDesc getFunction(final String signature, FunctionType funcType, DataType... paramTypes) throws AmbiguousFunctionException, UndefinedFunctionException { final GetFunctionMetaRequest.Builder builder = GetFunctionMetaRequest.newBuilder(); builder.setSignature(signature); if (funcType != null) { builder.setFunctionType(funcType); } for (DataType type : paramTypes) { builder.addParameterTypes(type); } try { final BlockingInterface stub = getStub(); final FunctionResponse response = stub.getFunctionMeta(null, builder.build()); throwsIfThisError(response.getState(), UndefinedFunctionException.class); ensureOk(response.getState()); return new FunctionDesc(response.getFunction()); } catch (ServiceException se) { throw new RuntimeException(se); } catch (ClassNotFoundException e) { throw new TajoInternalError(e); } }
Source:
public void absorb(SolGame game, float dmg, Vector2 pos, SolShip ship, DmgType dmgType) { if (!canAbsorb(dmgType) || dmg <= 0) { throw new AssertionError("illegal call to absorb"); } myIdleTime = 0f; if (dmgType == DmgType.BULLET) { dmg *= bulletDmgFactor; } if (dmgType == DmgType.ENERGY) { dmg *= energyDmgFactor; } if (dmgType == DmgType.EXPLOSION) { dmg *= explosionDmgFactor; } myLife -= myLife < dmg ? myLife : dmg; game.getPartMan().shieldSpark(game, pos, ship.getHull(), myConfig.tex, dmg / myConfig.maxLife); float volMul = SolMath.clamp(4 * dmg / myConfig.maxLife); game.getSoundManager().play(game, myConfig.absorbSound, null, ship, volMul); }

Target:
public void absorb(SolGame game, float dmg, Vector2 pos, SolShip ship, DmgType dmgType) { if (!canAbsorb(dmgType) || dmg <= 0) { throw new AssertionError("illegal call to absorb"); } myIdleTime = 0f; if (dmgType == DmgType.BULLET) { dmg *= bulletDmgFactor; } else if (dmgType == DmgType.ENERGY) { dmg *= energyDmgFactor; } else if (dmgType == DmgType.EXPLOSION) { dmg *= explosionDmgFactor; } myLife -= myLife < dmg ? myLife : dmg; game.getPartMan().shieldSpark(game, pos, ship.getHull(), myConfig.tex, dmg / myConfig.maxLife); float volMul = SolMath.clamp(4 * dmg / myConfig.maxLife); game.getSoundManager().play(game, myConfig.absorbSound, null, ship, volMul); }
Source:
public final <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) { Contracts.assertNotNull( beanType, MESSAGES.beanTypeCannotBeNull() ); sanityCheckPropertyPath( propertyName ); sanityCheckGroups( groups ); PathImpl pathFromString = PathImpl.createPathFromString( propertyName ); ValidationContext<T> validationContext = getValidationContextBuilder().forValidateValue( beanType, pathFromString ); if ( !validationContext.getRootBeanMetaData().hasConstraints() ) { return Collections.emptySet(); } ValidationOrder validationOrder = determineGroupValidationOrder( groups ); return validateValueInContext( validationContext, value, pathFromString, validationOrder ); }

Target:
public final <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) { Contracts.assertNotNull( beanType, MESSAGES.beanTypeCannotBeNull() ); sanityCheckPropertyPath( propertyName ); sanityCheckGroups( groups ); PathImpl propertyPath = PathImpl.createPathFromString( propertyName ); BaseBeanValidationContext<T> validationContext = getValidationContextBuilder().forValidateValue( beanType, propertyPath ); if ( !validationContext.getRootBeanMetaData().hasConstraints() ) { return Collections.emptySet(); } ValidationOrder validationOrder = determineGroupValidationOrder( groups ); return validateValueInContext( validationContext, value, propertyPath, validationOrder ); }
Source:
public <T> T getValue(Attribute<T> key) { return null; }

Target:
public <T> T getValue(Attribute<T> key) { return attributes.get(key); }
Source:
public ConfigReposControllerV2(ApiAuthenticationHelper authHelper, ConfigRepoService service, EntityHashingService entityHashingService) { super(ApiVersion.v2, EntityType.ConfigRepo.name(), "20.2.0", "20.5.0", ApiVersion.v3); this.authHelper = authHelper; this.service = service; this.entityHashingService = entityHashingService; }

Target:
public ConfigReposControllerV2(ApiAuthenticationHelper authHelper, ConfigRepoService service, EntityHashingService entityHashingService) { super(ApiVersion.v2); this.authHelper = authHelper; this.service = service; this.entityHashingService = entityHashingService; }
Source:
private void configureJob(Job job, String tableName, String inputQuery, String condition, boolean shouldSplit) throws Exception { try { upsertAndSnapshot(tableName, shouldSplit); result = new ArrayList<>(); job.setMapperClass(TableSnapshotMapper.class); job.setMapOutputKeyClass(ImmutableBytesWritable.class); job.setMapOutputValueClass(NullWritable.class); job.setOutputFormatClass(NullOutputFormat.class); Assert.assertTrue(job.waitForCompletion(true)); Properties props = new Properties(); props.setProperty("CurrentSCN", Long.toString(timestamp)); StringBuilder selectQuery = new StringBuilder("SELECT * FROM " + tableName); if (condition != null) { selectQuery.append(" WHERE " + condition); } if (inputQuery == null) inputQuery = selectQuery.toString(); ResultSet rs = DriverManager.getConnection(getUrl(), props).createStatement().executeQuery(inputQuery); for (List<Object> r : result) { if (rs.next() == false) { System.out.println("Placeholder"); } int i = 0; String field1 = rs.getString(i + 1); assertEquals("Got the incorrect value for field1", r.get(i++), field1); String field2 = rs.getString(i + 1); assertEquals("Got the incorrect value for field2", r.get(i++), field2); int field3 = rs.getInt(i + 1); assertEquals("Got the incorrect value for field3", r.get(i++), field3); } assertFalse("Should only have stored" + result.size() + "rows in the table for the timestamp!", rs.next()); } finally { deleteSnapshot(tableName); } }

Target:
private void configureJob(Job job, String tableName, String inputQuery, String condition, boolean shouldSplit) throws Exception { try { upsertAndSnapshot(tableName, shouldSplit); result = new ArrayList<>(); job.setMapperClass(TableSnapshotMapper.class); job.setMapOutputKeyClass(ImmutableBytesWritable.class); job.setMapOutputValueClass(NullWritable.class); job.setOutputFormatClass(NullOutputFormat.class); Assert.assertTrue(job.waitForCompletion(true)); Properties props = new Properties(); props.setProperty("CurrentSCN", Long.toString(timestamp)); StringBuilder selectQuery = new StringBuilder("SELECT * FROM " + tableName); if (condition != null) { selectQuery.append(" WHERE " + condition); } if (inputQuery == null) inputQuery = selectQuery.toString(); ResultSet rs = DriverManager.getConnection(getUrl(), props).createStatement().executeQuery(inputQuery); for (List<Object> r : result) { assertTrue("No data stored in the table!", rs.next()); int i = 0; String field1 = rs.getString(i + 1); assertEquals("Got the incorrect value for field1", r.get(i++), field1); String field2 = rs.getString(i + 1); assertEquals("Got the incorrect value for field2", r.get(i++), field2); int field3 = rs.getInt(i + 1); assertEquals("Got the incorrect value for field3", r.get(i++), field3); } assertFalse("Should only have stored" + result.size() + "rows in the table for the timestamp!", rs.next()); } finally { deleteSnapshot(tableName); } }
Source:
private ISymbolProviderPreferencePage[] getProviderPages() { List<ISymbolProviderPreferencePage> pages = new ArrayList<>(); ITmfTrace trace = getTrace(); if (trace != null) { for (ITmfTrace subTrace : getTracesToBuild(trace)) { Collection<ISymbolProvider> providers = fSymbolProviders.get(subTrace); if (!providers.isEmpty()) { for (ISymbolProvider provider : providers) { org.eclipse.tracecompass.tmf.ui.symbols.ISymbolProvider provider2 = (org.eclipse.tracecompass.tmf.ui.symbols.ISymbolProvider) provider; ISymbolProviderPreferencePage page = provider2.createPreferencePage(); if (page != null) { pages.add(page); } } } } } return pages.toArray(new ISymbolProviderPreferencePage[pages.size()]); }

Target:
private ISymbolProviderPreferencePage[] getProviderPages() { List<ISymbolProviderPreferencePage> pages = new ArrayList<>(); ITmfTrace trace = getTrace(); if (trace != null) { for (ITmfTrace subTrace : getTracesToBuild(trace)) { for (ISymbolProvider provider : fSymbolProviders.get(subTrace)) { if (provider instanceof org.eclipse.tracecompass.tmf.ui.symbols.ISymbolProvider) { org.eclipse.tracecompass.tmf.ui.symbols.ISymbolProvider provider2 = (org.eclipse.tracecompass.tmf.ui.symbols.ISymbolProvider) provider; ISymbolProviderPreferencePage page = provider2.createPreferencePage(); if (page != null) { pages.add(page); } } } } } return pages.toArray(new ISymbolProviderPreferencePage[pages.size()]); }
Source:
public static List<TurboIssue> getMatchedIssues(List<TurboIssue> issues, String query){ List<String> queries = Arrays.asList(query.split("\\s")); return issues.stream() .filter(i -> Utility.containsIgnoreCaseMultipleWords(i.getTitle() + " " + i.getId(), queries)) .collect(Collectors.toList()); }

Target:
public static List<TurboIssue> getMatchedIssues(List<TurboIssue> issues, String query){ List<String> queries = Arrays.asList(query.split("\\s")); return issues.stream() .filter(i -> Utility.containsIgnoreCase(i.getTitle() + " " + i.getId(), queries)) .collect(Collectors.toList()); }
Source:
void handleContainerStop(String processorId, String containerId, String preferredHost, int exitStatus, Duration preferredHostRetryDelay, ContainerAllocator containerAllocator) { if (getControlActionMetadata(processorId).isPresent()) { LOG.info("Setting the container with processorId stopped to be true because of existing container placement action", processorId); Object activeContainerStopped = getControlActionMetadata(processorId).get().getActiveContainerStopped(); synchronized (activeContainerStopped) { activeContainerStopped.notifyAll(); } } else if (standbyContainerManager.isPresent()) { standbyContainerManager.get() .handleContainerStop(processorId, containerId, preferredHost, exitStatus, containerAllocator, preferredHostRetryDelay); } else { containerAllocator.requestResourceWithDelay(processorId, preferredHost, preferredHostRetryDelay); } }

Target:
void handleContainerStop(String processorId, String containerId, String preferredHost, int exitStatus, Duration preferredHostRetryDelay, ContainerAllocator containerAllocator) { if (hasActiveContainerPlacementAction(processorId)) { ContainerPlacementMetadata metadata = getPlacementActionMetadata(processorId).get(); LOG.info("Setting the container state with Processor ID: to be stopped because of existing ContainerPlacement action: {}", processorId, metadata); metadata.setContainerStatus(ContainerPlacementMetadata.ContainerStatus.STOPPED); } else if (standbyContainerManager.isPresent()) { standbyContainerManager.get() .handleContainerStop(processorId, containerId, preferredHost, exitStatus, containerAllocator, preferredHostRetryDelay); } else { containerAllocator.requestResourceWithDelay(processorId, preferredHost, preferredHostRetryDelay); } }
Source:
public Mono<Response<BlockBlobItem>> uploadWithResponse(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions, BlobHttpHeaders headers, Map<String, String> metadata, AccessTier tier, BlobRequestConditions requestConditions) { return this.uploadWithResponse(new BlobUploadOptions(data) .setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata) .setTier(AccessTier.HOT).setRequestConditions(requestConditions)); }

Target:
public Mono<Response<BlockBlobItem>> uploadWithResponse(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions, BlobHttpHeaders headers, Map<String, String> metadata, AccessTier tier, BlobRequestConditions requestConditions) { return this.uploadWithResponse(new BlobParallelUploadOptions(data) .setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata) .setTier(AccessTier.HOT).setRequestConditions(requestConditions)); }
Source:
public synchronized static <T> Collection<T> getFromExtensions(ExtensionsConfig config, Class<T> clazz) { final TeslaAether aether = getAetherClient(config); final Set<T> retVal = Sets.newHashSet(); final Set<String> extensionNames = Sets.newHashSet(); for (String coordinate : config.getCoordinates()) { log.info("Loading extension[%s] for class[%s]", coordinate, clazz.getName()); try { URLClassLoader loader = getClassLoaderForCoordinates(aether, coordinate, config.getDefaultVersion()); for (T module : ServiceLoader.load(clazz, loader)) { String moduleName = module.getClass().getName(); if (!extensionNames.contains(moduleName)) { log.info("Adding remote extension module[%s] for class[%s]", moduleName, clazz.getName()); extensionNames.add(moduleName); retVal.add(module); } } } catch (Exception e) { throw Throwables.propagate(e); } } if (config.searchCurrentClassloader()) { for (T module : ServiceLoader.load(clazz, Initialization.class.getClassLoader())) { String moduleName = module.getClass().getName(); if (!extensionNames.contains(moduleName)) { log.info("Adding local extension module[%s] for class[%s]", moduleName, clazz.getName()); extensionNames.add(moduleName); retVal.add(module); } } } extensionsMap.put(clazz, retVal); return retVal; }

Target:
public synchronized static <T> Collection<T> getFromExtensions(ExtensionsConfig config, Class<T> clazz) { final TeslaAether aether = getAetherClient(config); final Set<T> retVal = Sets.newHashSet(); final Set<String> extensionNames = Sets.newHashSet(); for (String coordinate : config.getCoordinates()) { log.info("Loading extension[%s] for class[%s]", coordinate, clazz.getName()); try { URLClassLoader loader = getClassLoaderForCoordinates(aether, coordinate, config.getDefaultVersion()); for (T module : ServiceLoader.load(clazz, loader)) { String moduleName = module.getClass().getCanonicalName(); if (moduleName == null) { log.warn( "Extension module [%s] was ignored because it doesn't have a canonical name, is it a local or anonymous class?", module.getClass().getName() ); } else if (!extensionNames.contains(moduleName)) { log.info("Adding remote extension module[%s] for class[%s]", moduleName, clazz.getName()); extensionNames.add(moduleName); retVal.add(module); } } } catch (Exception e) { throw Throwables.propagate(e); } } if (config.searchCurrentClassloader()) { for (T module : ServiceLoader.load(clazz, Initialization.class.getClassLoader())) { String moduleName = module.getClass().getCanonicalName(); if (moduleName == null) { log.warn( "Extension module [%s] was ignored because it doesn't have a canonical name, is it a local or anonymous class?", module.getClass().getName() ); } else if (!extensionNames.contains(moduleName)) { log.info("Adding local extension module[%s] for class[%s]", moduleName, clazz.getName()); extensionNames.add(moduleName); retVal.add(module); } } } extensionsMap.put(clazz, retVal); return retVal; }
Source:
ArrayResult executeOperation() { int[][] resultData = new int[((ArrayInput) this.getReceivedData()).data[0].length] [((ArrayInput) this.getReceivedData()).data.length]; for (int i = 0; i < ((ArrayInput) this.getReceivedData()).data.length; i++) { for (int j = 0; j < ((ArrayInput) this.getReceivedData()).data[0].length; j++) { resultData[j][i] = ((ArrayInput) this.getReceivedData()).data[i][j]; } } ArrayResult result = new ArrayResult(resultData); return result; }

Target:
ArrayResult executeOperation() { int[][] resultData = new int[((ArrayInput) this.getReceivedData()).data[0].length] [((ArrayInput) this.getReceivedData()).data.length]; for (int i = 0; i < ((ArrayInput) this.getReceivedData()).data.length; i++) { for (int j = 0; j < ((ArrayInput) this.getReceivedData()).data[0].length; j++) { resultData[j][i] = ((ArrayInput) this.getReceivedData()).data[i][j]; } } return new ArrayResult(resultData); }
Source:
String getComponent(){ return mComponent; }

Target:
String getComponent() { return component; }
Source:
private JdbcOptions getJdbcOptions(ReadableConfig readableConfig) { final String url = readableConfig.get(URL); final JdbcOptions.Builder builder = JdbcOptions.builder() .setDBUrl(url) .setTableName(readableConfig.get(TABLE_NAME)) .setConnectionCheckTimeoutSeconds((int) readableConfig.get(MAX_RETRY_TIMEOUT).toMillis()) .setDialect(JdbcDialects.get(url).get()); readableConfig.getOptional(DRIVER).ifPresent(builder::setDriverName); readableConfig.getOptional(USERNAME).ifPresent(builder::setUsername); readableConfig.getOptional(PASSWORD).ifPresent(builder::setPassword); return builder.build(); }

Target:
private JdbcOptions getJdbcOptions(ReadableConfig readableConfig) { final String url = readableConfig.get(URL); final JdbcOptions.Builder builder = JdbcOptions.builder() .setDBUrl(url) .setTableName(readableConfig.get(TABLE_NAME)) .setDialect(JdbcDialects.get(url).get()) .setParallelism(readableConfig.getOptional(FactoryUtil.SINK_PARALLELISM).orElse(null)) .setConnectionCheckTimeoutSeconds((int) readableConfig.get(MAX_RETRY_TIMEOUT).getSeconds()); readableConfig.getOptional(DRIVER).ifPresent(builder::setDriverName); readableConfig.getOptional(USERNAME).ifPresent(builder::setUsername); readableConfig.getOptional(PASSWORD).ifPresent(builder::setPassword); return builder.build(); }
Source:
private String enforceNotNullNorEmpty(String str, String propertyName) { checkNotNull(str, "%s can't be null", propertyName); checkArgument(!str.isEmpty(), "%s can't be empty", propertyName); return str; }

Target:
private static String enforceNotNullNorEmpty(String str, String propertyName) { checkNotNull(str, "%s can't be null", propertyName); checkArgument(!str.isEmpty(), "%s can't be empty", propertyName); return str; }
Source:
public IgniteSemaphore semaphore(final String name, @Nullable AtomicConfiguration cfg, final int cnt, final boolean failoverSafe, final boolean create) throws IgniteCheckedException { return getAtomic(new AtomicAccessor<GridCacheSemaphoreEx>() { @Override public T2<GridCacheSemaphoreEx, AtomicDataStructureValue> get(GridCacheInternalKey key, AtomicDataStructureValue val, IgniteInternalCache cache) throws IgniteCheckedException { GridCacheSemaphoreEx sem = cast(dsMap.get(key), GridCacheSemaphoreEx.class); if (sem != null) { assert val != null; return new T2<>(sem, null); } if (val == null && !create) return null; AtomicDataStructureValue retVal = (val == null ? new GridCacheSemaphoreState(cnt, new HashMap<UUID, Integer>(), failoverSafe, ctx.discovery().gridStartTime()) : null); GridCacheSemaphoreEx sem0 = new GridCacheSemaphoreImpl(name, key, cache); if(val!=null){ ctx.closure().callLocalSafe( new Callable<Object>() { @Override public Object call() throws Exception { GridCacheSemaphoreState semState=(GridCacheSemaphoreState)val; for (UUID nodeId : semState.getWaiters().keySet()) { ClusterNode node = ctx.cluster().get().node(nodeId); if (node == null) { sem0.onNodeRemoved(nodeId); if (log.isDebugEnabled()) log.debug("Removed node found to be waiting which is no longer active: " + nodeId); } } return null; }}, false); } return new T2<>(sem0, retVal); } }, cfg, name, SEMAPHORE, create, GridCacheSemaphoreEx.class); }

Target:
public IgniteSemaphore semaphore(final String name, @Nullable AtomicConfiguration cfg, final int cnt, final boolean failoverSafe, final boolean create) throws IgniteCheckedException { return getAtomic(new AtomicAccessor<GridCacheSemaphoreEx>() { @Override public T2<GridCacheSemaphoreEx, AtomicDataStructureValue> get(GridCacheInternalKey key, AtomicDataStructureValue val, IgniteInternalCache cache) throws IgniteCheckedException { GridCacheSemaphoreEx sem = cast(dsMap.get(key), GridCacheSemaphoreEx.class); if (sem != null) { assert val != null; return new T2<>(sem, null); } if (val == null && !create) return null; AtomicDataStructureValue retVal = (val == null ? new GridCacheSemaphoreState(cnt, new HashMap<UUID, Integer>(), failoverSafe, ctx.discovery().gridStartTime()) : null); GridCacheSemaphoreEx sem0 = new GridCacheSemaphoreImpl(name, key, cache); if (val != null && failoverSafe) { GridCacheSemaphoreState semState = (GridCacheSemaphoreState) val; boolean updated = false; Map<UUID,Integer> waiters = semState.getWaiters(); Integer permit = ((GridCacheSemaphoreState) val).getCount(); for (UUID nodeId : new HashSet<>(waiters.keySet())) { ClusterNode node = ctx.cluster().get().node(nodeId); if (node == null) { permit += waiters.get(nodeId); waiters.remove(nodeId); updated = true; } } if (updated) { semState.setWaiters(waiters); semState.setCount(permit); retVal = semState; } } return new T2<>(sem0, retVal); } }, cfg, name, SEMAPHORE, create, GridCacheSemaphoreEx.class); }
Source:
private String getSubmissionFormMobileHtml(String questionNumberString, String responseNumberString, boolean sessionIsOpen, boolean isExistingResponse, FeedbackRubricResponseDetails frd) { StringBuilder mobileHtml = new StringBuilder(); String mobilePanelTemplate = FormTemplates.RUBRIC_SUBMISSION_FORM_MOBILE_PANEL; String mobilePanelFragmentTemplate = FormTemplates.RUBRIC_SUBMISSION_FORM_MOBILE_PANEL_FRAGMENT; for (int i = 0; i < numOfRubricSubQuestions; i++) { StringBuilder panelBody = new StringBuilder(); for (int j = 0; j < numOfRubricChoices; j++) { String panelBodyFragment = Templates.populateTemplate(mobilePanelFragmentTemplate, Slots.QUESTION_INDEX, questionNumberString, Slots.RESPONSE_INDEX, responseNumberString, Slots.COL, Integer.toString(j), Slots.ROW, Integer.toString(i), Slots.DISABLED, sessionIsOpen ? "" : "disabled", "${description}", Sanitizer.sanitizeForHtml(this.getDescription(i, j)), "${checked}", isExistingResponse && frd.getAnswer(i) == j ? "checked" : "", Slots.RUBRIC_CHOICE_VALUE, Sanitizer.sanitizeForHtml(rubricChoices.get(j)), "${Const.ParamsNames.FEEDBACK_QUESTION_RUBRICCHOICE}", Const.ParamsNames.FEEDBACK_QUESTION_RUBRIC_CHOICE); panelBody.append(panelBodyFragment); } String panel = Templates.populateTemplate(mobilePanelTemplate, "${panelBody}", panelBody.toString(), "${subQuestion}", StringHelper.integerToLowerCaseAlphabeticalIndex(i + 1) + ") " + Sanitizer.sanitizeForHtml(rubricSubQuestions.get(i))); mobileHtml.append(panel).append(Const.EOL); } return mobileHtml.toString(); }

Target:
private String getSubmissionFormMobileHtml(String questionNumberString, String responseNumberString, boolean sessionIsOpen, boolean isExistingResponse, FeedbackRubricResponseDetails frd) { StringBuilder mobileHtml = new StringBuilder(); String mobilePanelTemplate = FormTemplates.RUBRIC_SUBMISSION_FORM_MOBILE_PANEL; String mobilePanelFragmentTemplate = FormTemplates.RUBRIC_SUBMISSION_FORM_MOBILE_PANEL_FRAGMENT; for (int i = 0; i < numOfRubricSubQuestions; i++) { StringBuilder panelBody = new StringBuilder(); for (int j = 0; j < numOfRubricChoices; j++) { String panelBodyFragment = Templates.populateTemplate(mobilePanelFragmentTemplate, Slots.QUESTION_INDEX, questionNumberString, Slots.RESPONSE_INDEX, responseNumberString, Slots.COL, Integer.toString(j), Slots.ROW, Integer.toString(i), Slots.DISABLED, sessionIsOpen ? "" : "disabled", Slots.DESCRIPTION, Sanitizer.sanitizeForHtml(this.getDescription(i, j)), Slots.CHECKED, isExistingResponse && frd.getAnswer(i) == j ? "checked" : "", Slots.RUBRIC_CHOICE_VALUE, Sanitizer.sanitizeForHtml(rubricChoices.get(j)), Slots.RUBRIC_PARAM_CHOICE, Const.ParamsNames.FEEDBACK_QUESTION_RUBRIC_CHOICE); panelBody.append(panelBodyFragment); } String panel = Templates.populateTemplate(mobilePanelTemplate, Slots.PANEL_BODY, panelBody.toString(), Slots.SUB_QUESTION, StringHelper.integerToLowerCaseAlphabeticalIndex(i + 1) + ") " + Sanitizer.sanitizeForHtml(rubricSubQuestions.get(i))); mobileHtml.append(panel).append(Const.EOL); } return mobileHtml.toString(); }
Source:
public static String filterAndUpdate(String input, Map<? extends Serializable, ? extends Serializable> variables) { if (input == null || input.isEmpty()) { return input; } String output = input; Map<String, String> substitutes = buildSubstitutes(variables); boolean anyReplacement; int depthCount = 0; do { anyReplacement = false; depthCount++; for (Map.Entry<String, String> replacement : substitutes.entrySet()) { if (replacement.getValue() != null) { String newOutput = output.replace(replacement.getKey(), replacement.getValue()); anyReplacement = anyReplacement || !newOutput.equals(output); output = newOutput; } } } while (anyReplacement && depthCount < 5); return output; }

Target:
public static String filterAndUpdate(String input, Map<? extends Serializable, ? extends Serializable> variables) { if (input == null || input.isEmpty()) { return input; } String output = input; Map<String, String> substitutes = buildSubstitutes(variables); output = replaceRecursively(output, substitutes); return output; }
Source:
public KubernetesNamespace create(String workspaceId) throws InfrastructureException { final String namespaceName; try { namespaceName = evalNamespaceName(workspaceId, EnvironmentContext.getCurrent().getSubject()); } catch (NotFoundException | ServerException | ConflictException | ValidationException e) { throw new InfrastructureException( format("Failed to determine the namespace to put the workspace %s to", workspaceId), e); } KubernetesNamespace namespace = doCreateNamespace(workspaceId, namespaceName); namespace.prepare(); if (isCreatingNamespaces(workspaceId) && !isNullOrEmpty(serviceAccountName)) { KubernetesWorkspaceServiceAccount workspaceServiceAccount = doCreateServiceAccount(workspaceId, namespaceName); workspaceServiceAccount.prepare(); } return namespace; }

Target:
public KubernetesNamespace create(String workspaceId) throws InfrastructureException { final String namespaceName; try { namespaceName = evalNamespaceName(workspaceId, EnvironmentContext.getCurrent().getSubject()); } catch (NotFoundException | ServerException | ConflictException | ValidationException e) { throw new InfrastructureException( format( "Failed to determine the namespace to put the workspace %s to." + " The error message was: %s", workspaceId, e.getMessage()), e); } KubernetesNamespace namespace = doCreateNamespace(workspaceId, namespaceName); namespace.prepare(); if (isCreatingNamespace(workspaceId) && !isNullOrEmpty(serviceAccountName)) { KubernetesWorkspaceServiceAccount workspaceServiceAccount = doCreateServiceAccount(workspaceId, namespaceName); workspaceServiceAccount.prepare(); } return namespace; }
Source:
public void addContactTestWithANullValue() throws XMLStreamException, IOException { Contact contact = getContact(1L, null, "John", "Doe", "5555551212", "Mr."); XMLOutputFactory factory = XMLOutputFactory.newInstance(); StringWriter stringOut = new StringWriter(); XMLStreamWriter writer = factory.createXMLStreamWriter(stringOut); ContactXmlGenerator.addContact(contact, "contact", writer); writer.close(); String expected = "<contact><contactId>1</contactId><firstName>John</firstName><lastName>Doe</lastName><phoneNumber>5555551212</phoneNumber><title>Mr.</title></contact>"; assertEquals(expected, stringOut.toString()); stringOut.close(); }

Target:
public void addContactTestWithANullValue() throws XMLStreamException, IOException { Contact contact = getContact(1L, null, "John", "Doe", "5555551212", "Mr."); XMLOutputFactory factory = XMLOutputFactory.newInstance(); StringWriter stringOut = new StringWriter(); XMLStreamWriter writer = factory.createXMLStreamWriter(stringOut); ContactXmlGenerator.addContact(contact, "contact", writer); writer.close(); String expected = "<contact><contactId>1</contactId><fullName>John</fullName><friendlyName>Doe</friendlyName><phoneNumber>5555551212</phoneNumber><title>Mr.</title></contact>"; assertEquals(expected, stringOut.toString()); stringOut.close(); }
Source:
private void createAndStartCallPeriodicRunnable( StatsService statsService, CallContext callContext, Call call, AccountID accountID) { String conferenceIDPrefix = accountID.getAccountPropertyString( CS_ACC_PROP_CONFERENCE_PREFIX); int interval = accountID.getAccountPropertyInt( CS_ACC_PROP_STATISTICS_INTERVAL, DEFAULT_STAT_INTERVAL); String conferenceName = callContext.getRoomName(); if (conferenceName.contains("@")) { conferenceName = Util.extractCallIdFromResource(conferenceName); } String subDomain = callContext.getSubDomain(); if (!StringUtils.isNullOrEmpty(subDomain) && conferenceIDPrefix != null) { if (!conferenceIDPrefix.endsWith("/")) { conferenceIDPrefix += "/"; } conferenceIDPrefix += subDomain; } CallPeriodicRunnable cpr = new CallPeriodicRunnable( call, interval, statsService, conferenceName, conferenceIDPrefix, DEFAULT_JIGASI_ID + "-" + originID, this.remoteEndpointID); cpr.start(); statisticsProcessors.put(call, cpr); statisticsExecutor.registerRecurringRunnable(cpr); }

Target:
private void createAndStartCallPeriodicRunnable( StatsService statsService, CallContext callContext, Call call, AccountID accountID) { String conferenceIDPrefix = accountID.getAccountPropertyString( CS_ACC_PROP_CONFERENCE_PREFIX); int interval = accountID.getAccountPropertyInt( CS_ACC_PROP_STATISTICS_INTERVAL, DEFAULT_STAT_INTERVAL); String subDomain = callContext.getSubDomain(); if (!StringUtils.isNullOrEmpty(subDomain) && conferenceIDPrefix != null) { if (!conferenceIDPrefix.endsWith("/")) { conferenceIDPrefix += "/"; } conferenceIDPrefix += subDomain; } CallPeriodicRunnable cpr = new CallPeriodicRunnable( call, interval, statsService, callContext.getConferenceName(), conferenceIDPrefix, DEFAULT_JIGASI_ID + "-" + originID, this.remoteEndpointID); cpr.start(); statisticsProcessors.put(call, cpr); statisticsExecutor.registerRecurringRunnable(cpr); }
Source:
public Optional<Predicate<ItemStackSnapshot>> getIngredientPredicate(int x, int y) { if (x < 0 || x >= recipeWidth || y < 0 || y >= recipeHeight) { return Optional.empty(); } int recipeItemIndex = x + y * recipeWidth; ItemStackSnapshot recipeSnapshot = ItemStackUtil.snapshotOf(recipeItems[recipeItemIndex]); return Optional.of(new MatchCraftingVanillaItemStack(recipeSnapshot)); }

Target:
public Predicate<ItemStackSnapshot> getIngredientPredicate(int x, int y) { if (x < 0 || x >= this.recipeWidth || y < 0 || y >= this.recipeHeight) { throw new IndexOutOfBoundsException("Invalid ingredient predicate location"); } int recipeItemIndex = x + y * this.recipeWidth; ItemStackSnapshot recipeSnapshot = ItemStackUtil.snapshotOf(this.recipeItems[recipeItemIndex]); return new MatchCraftingVanillaItemStack(recipeSnapshot); }
Source:
public static void updateToTable(Connection connection, String tableName, Persistable persistable, int id) { String queryStart = "UPDATE " + tableName + " SET " + DatabaseHelper.DATA_COL + " = ? "; String queryEnd = " WHERE " + DatabaseHelper.ID_COL + " = ?;"; HashMap<String, Object> map = DatabaseHelper.getMetaFieldsAndValues(persistable); String[] fieldNames = map.keySet().toArray(new String[map.keySet().size()]); Object[] values = map.values().toArray(new Object[map.values().size()]); StringBuilder stringBuilder = new StringBuilder(queryStart); for(String fieldName: fieldNames){ stringBuilder.append( ", " + fieldName + " = ?"); } String query = stringBuilder.append(queryEnd).toString(); PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(query); byte[] blob = org.commcare.modern.database.TableBuilder.toBlob(persistable); preparedStatement.setBinaryStream(1, new ByteArrayInputStream(blob), blob.length); int i = 2; for(Object obj: values){ if (obj instanceof String) { preparedStatement.setString(i, (String)obj); } else if (obj instanceof Blob) { preparedStatement.setBlob(i, (Blob)obj); } else if (obj instanceof Integer) { preparedStatement.setInt(i, (Integer)obj); } else if (obj instanceof byte[]) { preparedStatement.setBinaryStream(i, new ByteArrayInputStream((byte[])obj), ((byte[])obj).length); } else if (obj == null) { preparedStatement.setNull(i, 0); } i++; } preparedStatement.setInt(i, id); preparedStatement.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } } }

Target:
public static void updateToTable(Connection connection, String tableName, Persistable persistable, int id) { String queryStart = "UPDATE " + tableName + " SET " + DatabaseHelper.DATA_COL + " = ? "; String queryEnd = " WHERE " + DatabaseHelper.ID_COL + " = ?;"; HashMap<String, Object> map = DatabaseHelper.getMetaFieldsAndValues(persistable); String[] fieldNames = map.keySet().toArray(new String[map.keySet().size()]); Object[] values = map.values().toArray(new Object[map.values().size()]); StringBuilder stringBuilder = new StringBuilder(queryStart); for(String fieldName: fieldNames){ stringBuilder.append(", ").append(fieldName).append(" = ?"); } String query = stringBuilder.append(queryEnd).toString(); PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(query); int lastArgIndex = setPreparedStatementArgs(preparedStatement, persistable, values); preparedStatement.setInt(lastArgIndex, id); preparedStatement.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
Source:
public static MonthView create(ViewGroup parent, LayoutInflater inflater, DateFormat weekdayNameFormat, Listener listener, Calendar today) { final MonthView view = (MonthView) inflater.inflate(R.layout.month, parent, false); final int originalDayOfWeek = today.get(Calendar.DAY_OF_WEEK); int firstDayOfWeek = today.getFirstDayOfWeek(); final CalendarRowView headerRow = (CalendarRowView) view.grid.getChildAt(0); for (int c = Calendar.SUNDAY; c <= Calendar.SATURDAY; c++) { today.set(Calendar.DAY_OF_WEEK, firstDayOfWeek + c - 1); final TextView textView = (TextView) headerRow.getChildAt(c - 1); textView.setText(weekdayNameFormat.format(today.getTime())); } today.set(Calendar.DAY_OF_WEEK, originalDayOfWeek); view.listener = listener; return view; }

Target:
public static MonthView create(ViewGroup parent, LayoutInflater inflater, DateFormat weekdayNameFormat, Listener listener, Calendar today) { final MonthView view = (MonthView) inflater.inflate(R.layout.month, parent, false); final int originalDayOfWeek = today.get(Calendar.DAY_OF_WEEK); int firstDayOfWeek = today.getFirstDayOfWeek(); final CalendarRowView headerRow = (CalendarRowView) view.grid.getChildAt(0); for (int offset = 0; offset < 7; offset++) { today.set(Calendar.DAY_OF_WEEK, firstDayOfWeek + offset); final TextView textView = (TextView) headerRow.getChildAt(offset); textView.setText(weekdayNameFormat.format(today.getTime())); } today.set(Calendar.DAY_OF_WEEK, originalDayOfWeek); view.listener = listener; return view; }
Source:
public Optional<SmeltingRecipe> findMatchingRecipe(ItemStackSnapshot ingredient) { checkNotNull(ingredient, "ingredient"); for (SmeltingRecipe customRecipe : customRecipes) { if (customRecipe.isValid(ingredient)) { return Optional.of(customRecipe); } } ItemStack nativeIngredient = ItemStackUtil.fromSnapshotToNative(ingredient); for (Map.Entry<ItemStack, ItemStack> entry : this.smeltingList.entrySet()) { ItemStack nativeIngredientPrecise = entry.getKey(); if (compareItemStacks(nativeIngredient, nativeIngredientPrecise)) { ItemStack nativeExemplaryResult = entry.getValue(); ItemStackSnapshot result = ItemStackUtil.snapshotOf(nativeExemplaryResult); ItemStackSnapshot ingredientPrecise = ItemStackUtil.snapshotOf(nativeIngredientPrecise); Predicate<ItemStackSnapshot> ingredientPredicate = new MatchSmeltingVanillaItemStack(ingredientPrecise); double experience = this.experienceList.get(nativeExemplaryResult); SmeltingRecipe recipe = new SpongeSmeltingRecipe(result, ingredientPrecise, ingredientPredicate, experience); return Optional.of(recipe); } } return Optional.empty(); }

Target:
public Optional<SmeltingRecipe> findMatchingRecipe(ItemStackSnapshot ingredient) { checkNotNull(ingredient, "ingredient"); for (SmeltingRecipe customRecipe : this.customRecipes) { if (customRecipe.isValid(ingredient)) { return Optional.of(customRecipe); } } ItemStack nativeIngredient = ItemStackUtil.fromSnapshotToNative(ingredient); for (Map.Entry<ItemStack, ItemStack> entry : this.smeltingList.entrySet()) { ItemStack nativeIngredientPrecise = entry.getKey(); if (compareItemStacks(nativeIngredient, nativeIngredientPrecise)) { ItemStack nativeExemplaryResult = entry.getValue(); ItemStackSnapshot result = ItemStackUtil.snapshotOf(nativeExemplaryResult); ItemStackSnapshot ingredientPrecise = ItemStackUtil.snapshotOf(nativeIngredientPrecise); Predicate<ItemStackSnapshot> ingredientPredicate = new MatchSmeltingVanillaItemStack(ingredientPrecise); double experience = this.experienceList.get(nativeExemplaryResult); SmeltingRecipe recipe = new SpongeSmeltingRecipe(result, ingredientPrecise, ingredientPredicate, experience); return Optional.of(recipe); } } return Optional.empty(); }
Source:
private void assignActiveRecords(Vector<UserKeyRecord> migratedRecords) { Map<String, List<UserKeyRecord>> usernamesToRecords = new HashMap<>(); for (UserKeyRecord record : migratedRecords) { String username = record.getUsername(); List<UserKeyRecord> recordsForUsername = usernamesToRecords.get(username); if (recordsForUsername == null) { recordsForUsername = new ArrayList<>(); } recordsForUsername.add(record); usernamesToRecords.put(username, recordsForUsername); } for (String username : usernamesToRecords.keySet()) { List<UserKeyRecord> records = usernamesToRecords.get(username); UserKeyRecord activeRecord; if (records.size() == 1) { activeRecord = records.get(0); } else { Collections.sort(records, new Comparator<UserKeyRecord>() { @Override public int compare(UserKeyRecord lhs, UserKeyRecord rhs) { return lhs.getValidTo().compareTo(rhs.getValidTo()); } }); activeRecord = records.get(0); } activeRecord.setActive(); } }

Target:
private void assignActiveRecords(Vector<UserKeyRecord> migratedRecords) { Map<String, List<UserKeyRecord>> usernamesToRecords = new HashMap<>(); for (UserKeyRecord record : migratedRecords) { String username = record.getUsername(); List<UserKeyRecord> recordsForUsername = usernamesToRecords.get(username); if (recordsForUsername == null) { recordsForUsername = new ArrayList<>(); usernamesToRecords.put(username, recordsForUsername); } recordsForUsername.add(record); } for (String username : usernamesToRecords.keySet()) { List<UserKeyRecord> records = usernamesToRecords.get(username); UserKeyRecord activeRecord; if (records.size() == 1) { activeRecord = records.get(0); } else { Collections.sort(records, new Comparator<UserKeyRecord>() { @Override public int compare(UserKeyRecord lhs, UserKeyRecord rhs) { return lhs.getValidTo().compareTo(rhs.getValidTo()); } }); activeRecord = records.get(0); } activeRecord.setActive(); } }