auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static QoS map(QosBase entity, QoS template) { QoS model = template != null ? template : new QoS(); model.setId(entity.getId().toString()); model.setName(entity.getName()); model.setType(org.ovirt.engine.api.model.QosType.fromValue(entity.getQosType().toString()).name().toLowerCase()); model.setDataCenter(new DataCenter()); model.getDataCenter().setId(entity.getStoragePoolId().toString()); model.setDescription(entity.getDescription()); switch (entity.getQosType()) { case STORAGE: StorageQos storageQos = null; if (entity instanceof StorageQos) { storageQos = (StorageQos) entity; } if (storageQos == null) { return model; } model.setMaxThroughput(storageQos.getMaxThroughput()); model.setMaxReadThroughput(storageQos.getMaxReadThroughput()); model.setMaxWriteThroughput(storageQos.getMaxWriteThroughput()); model.setMaxIops(storageQos.getMaxIops()); model.setMaxReadIops(storageQos.getMaxReadIops()); <START> model.setMaxWriteIops(storageQos.getMaxWriteIops()); <END> case CPU: CpuQos cpuQos = null; if (entity instanceof CpuQos) { cpuQos = (CpuQos) entity; } if (cpuQos == null) { return model; } model.setCpuLimit(cpuQos.getCpuLimit()); default: break; } return model; }</code><technical_language>I miss a "break" here</technical_language>

Target:
public static QoS map(QosBase entity, QoS template) { QoS model = template != null ? template : new QoS(); model.setId(entity.getId().toString()); model.setName(entity.getName()); model.setType(org.ovirt.engine.api.model.QosType.fromValue(entity.getQosType().toString()).name().toLowerCase()); model.setDataCenter(new DataCenter()); model.getDataCenter().setId(entity.getStoragePoolId().toString()); model.setDescription(entity.getDescription()); switch (entity.getQosType()) { case STORAGE: StorageQos storageQos = null; if (entity instanceof StorageQos) { storageQos = (StorageQos) entity; } if (storageQos == null) { return model; } model.setMaxThroughput(storageQos.getMaxThroughput()); model.setMaxReadThroughput(storageQos.getMaxReadThroughput()); model.setMaxWriteThroughput(storageQos.getMaxWriteThroughput()); model.setMaxIops(storageQos.getMaxIops()); model.setMaxReadIops(storageQos.getMaxReadIops()); model.setMaxWriteIops(storageQos.getMaxWriteIops()); break; case CPU: CpuQos cpuQos = null; if (entity instanceof CpuQos) { cpuQos = (CpuQos) entity; } if (cpuQos == null) { return model; } model.setCpuLimit(cpuQos.getCpuLimit()); break; default: break; } return model; }
Source:
<code>public void testVirtCanMoveToMaintenance() { VDS vds = new VDS(); vds.getDynamicData().setstatus(VDSStatus.PreparingForMaintenance); <START> vds.getDynamicData().setvm_count(1); <END> assertFalse(virtStrategy.canMoveToMaintenance(vds)); vds.getDynamicData().setvm_count(0); assertTrue(virtStrategy.canMoveToMaintenance(vds)); }</code><technical_language>vds.setvm_count(1);</technical_language>

Target:
public void testVirtCanMoveToMaintenance() { VDS vds = new VDS(); vds.setstatus(VDSStatus.PreparingForMaintenance); vds.setvm_count(1); assertFalse(virtStrategy.canMoveToMaintenance(vds)); vds.setvm_count(0); assertTrue(virtStrategy.canMoveToMaintenance(vds)); }
Source:
<code>public ConfigXml(Context context) throws OpenConfigException { mContext = context; mConfigFile = Constants.getConfigFile(mContext); boolean isFirstStart = !mConfigFile.exists(); if (isFirstStart) { Log.i(TAG, "App started for the first time. Generating keys and config."); generateKeysConfig(context); } readConfig(); if (isFirstStart) { boolean changed = false; changed = changeLocalDeviceName() || changed; changed = changeDefaultFolder() || changed; Element options = (Element) mConfig.getDocumentElement() .getElementsByTagName("options").item(0); changed = setConfigElement(options, "restartOnWakeup", "true") || changed; if (changed) { saveChanges(); <START> } <END> } }</code><technical_language>I change is needed here, this sets default anyway. Also, if decide default other around, isFirstStart is a good idea</technical_language>

Target:
public ConfigXml(Context context) throws OpenConfigException { mContext = context; mConfigFile = Constants.getConfigFile(mContext); boolean isFirstStart = !mConfigFile.exists(); if (isFirstStart) { Log.i(TAG, "App started for the first time. Generating keys and config."); generateKeysConfig(context); } readConfig(); if (isFirstStart) { boolean changed = false; changeLocalDeviceName(); changed = changeDefaultFolder() || changed; if (changed) { saveChanges(); } } }
Source:
<code>public ArticlePageObject clickGetInfoLink() { switchToIFrame(); waitForElementByElement(getInfoLink); getInfoLink.click(); switchOutOfIFrame(); <START> return new ArticlePageObject(driver); <END> }</code><technical_language>in case of switching, in opinion etry/finnally that: switchToIFrame(); try { waitForElementByElement(getInfoLink); //Opens new tab Template namespace getInfoLink.click(); return new ArticlePageObject(driver); }finally { switchOutOfIFrame(); } clearer in reading</technical_language>

Target:
public ArticlePageObject clickGetInfoLink() { switchToIFrame(); try { waitForElementByElement(getInfoLink); getInfoLink.click(); return new ArticlePageObject(driver); } finally { switchOutOfIFrame(); } }
Source:
<code>public String getDescription() { <START> return "Folder"; <END> }</code><technical_language>l10n</technical_language>

Target:
public String getDescription() { return Messages.BuildStatusFolderIcon_Description(); }
Source:
<code>public CompletableFuture<Void> invoke(boolean success) { if (trace) { <START> log.tracef("After completion callback, success=%d", success); <END> } nonTxPutFromLoadInterceptor.endInvalidating(key, lockOwner, success); return null; }</code><technical_language>success=%b</technical_language>

Target:
public CompletableFuture<Void> invoke(boolean success) { if (trace) { log.tracef("After completion callback, success=%b", success); } nonTxPutFromLoadInterceptor.endInvalidating(key, lockOwner, success); return null; }
Source:
<code>public static void main(String[] args) { try { FileInputStream in = new FileInputStream("InputJava7MultiCatch.java"); throw new CustomException(); } catch (FileNotFoundException | CustomException e) { logException(e); } try { FileInputStream in = new FileInputStream("InputJava7MultiCatch.java"); throw new CustomException(); <START> } catch (final FileNotFoundException | CustomException | AnotherCustomException e) { <END> logException(e); } }</code><technical_language>delete package name class. required test a check supports fully-qualified names. In this exact case move this class new line</technical_language>

Target:
public static void main(String[] args) { try { FileInputStream in = new FileInputStream("InputJava7MultiCatch.java"); throw new CustomException(); } catch (FileNotFoundException | CustomException e) { logException(e); } try { FileInputStream in = new FileInputStream("InputJava7MultiCatch.java"); throw new CustomException(); } catch (final FileNotFoundException | CustomException | com.puppycrawl.tools.checkstyle.grammar.InputJava7MultiCatch.AnotherCustomException e) { logException(e); } }
Source:
<code>public final Set<SequenceSegment> getSegments(final int start, final int end) { Set<SequenceSegment> set = new TreeSet<SequenceSegment>(); <START> for (Set<SequenceSegment> bucket : buckets.subList(Math.max(0, start), Math.min(numberBuckets, end))) { <END> set.addAll(bucket); } return set; }</code><technical_language>sublist a vraible for readability line length</technical_language>

Target:
public final Set<SequenceSegment> getSegments(final int start, final int end) { Set<SequenceSegment> set = new TreeSet<SequenceSegment>(); int startBucket = Math.max(0, start); int endBucket = Math.min(numberBuckets, end); for (Set<SequenceSegment> bucket : buckets.subList(startBucket, endBucket)) { set.addAll(bucket); } return set; }
Source:
<code>protected void buildVmFloppy() { List<VmDevice> vmDevices = DbFacade.getInstance() .getVmDeviceDAO() .getVmDeviceByVmIdTypeAndDevice(vm.getId(), VmDeviceType.getName(VmDeviceType.DISK), VmDeviceType.getName(VmDeviceType.FLOPPY)); for (VmDevice vmDevice : vmDevices) { XmlRpcStruct struct = new XmlRpcStruct(); struct.add(VdsProperties.Type, vmDevice.getType()); struct.add(VdsProperties.Device, vmDevice.getDevice()); struct.add(VdsProperties.Index, "0"); addAddress(vmDevice, struct); struct.add(VdsProperties.Iface, "fdc"); struct.add(VdsProperties.PoolId, vm.getstorage_pool_id().toString()); struct.add(VdsProperties.DomainId, DbFacade.getInstance() .getStorageDomainDAO() .getIsoStorageDomainIdForPool(vm.getstorage_pool_id()) .toString()); struct.add(VdsProperties.ImageId, Guid.Empty.toString()); String file = StringUtils.string2Map(vmDevice.getSpecParams()).get("path"); struct.add(VdsProperties.VolumeId, file.substring(file.lastIndexOf('/') + 1)); struct.add(VdsProperties.Path, file); <START> struct.add(VdsProperties.ReadOnly, new Boolean(vmDevice.getIsReadOnly()).toString()); <END> devices.add(struct); break; } }</code><technical_language>please replace String.valueOf(vmDevice.getIsReadOnly())</technical_language>

Target:
protected void buildVmFloppy() { List<VmDevice> vmDevices = DbFacade.getInstance() .getVmDeviceDAO() .getVmDeviceByVmIdTypeAndDevice(vm.getId(), VmDeviceType.getName(VmDeviceType.DISK), VmDeviceType.getName(VmDeviceType.FLOPPY)); for (VmDevice vmDevice : vmDevices) { XmlRpcStruct struct = new XmlRpcStruct(); struct.add(VdsProperties.Type, vmDevice.getType()); struct.add(VdsProperties.Device, vmDevice.getDevice()); struct.add(VdsProperties.Index, "0"); addAddress(vmDevice, struct); struct.add(VdsProperties.Iface, "fdc"); struct.add(VdsProperties.PoolId, vm.getstorage_pool_id().toString()); struct.add(VdsProperties.DomainId, DbFacade.getInstance() .getStorageDomainDAO() .getIsoStorageDomainIdForPool(vm.getstorage_pool_id()) .toString()); struct.add(VdsProperties.ImageId, Guid.Empty.toString()); String file = StringUtils.string2Map(vmDevice.getSpecParams()).get("path"); struct.add(VdsProperties.VolumeId, file.substring(file.lastIndexOf('/') + 1)); struct.add(VdsProperties.Path, file); struct.add(VdsProperties.ReadOnly, String.valueOf(vmDevice.getIsReadOnly())); devices.add(struct); break; } }
Source:
<code>public static void main(String[] args) throws Exception { Options options = new Options(); Option addInstanceOption = Option.builder("addInstance") .desc("addInstance <instance> <password>") .hasArg(true) .numberOfArgs(2) .build(); options.addOption(addInstanceOption); Option removeInstanceOption = Option.builder("removeInstance") .hasArg(true) .build(); <START> options.addOption(removeInstanceOption); <END> CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("addInstance")) { String[] values = cmd.getOptionValues("addInstance"); IdentityService service = getIdentityService(); service.addKieServerInstance(values[0], values[1]); log.infof("Instance <%1$s> added", values[0]); return; } if (cmd.hasOption("removeInstance")) { String value = cmd.getOptionValue("removeInstance"); IdentityService service = getIdentityService(); service.removeKieServerInstance(value); log.infof("Instance <%1$s> removed", value); return; } KieServerRouter router = new KieServerRouter(); router.start(HOST, PORT, PORT_TLS); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { router.stop(); } }); }</code><technical_language>is purpose of this CLI adjustment</technical_language>

Target:
public static void main(String[] args) throws Exception { Options options = new Options(); Option addInstanceOption = Option.builder(CMD_ADD_USER) .desc(CMD_ADD_USER + " <user> <password>") .hasArg(true) .numberOfArgs(2) .build(); options.addOption(addInstanceOption); Option removeInstanceOption = Option.builder(CMD_REMOVE_USER) .desc(CMD_REMOVE_USER + " <user>") .hasArg(true) .build(); options.addOption(removeInstanceOption); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); KieServerRouter router = new KieServerRouter(); if (cmd.hasOption(CMD_ADD_USER)) { String[] values = cmd.getOptionValues(CMD_ADD_USER); router.getIdentityService().addKieServerInstance(values[0], values[1]); log.infof("User <%1$s> added", values[0]); return; } if (cmd.hasOption(CMD_REMOVE_USER)) { String value = cmd.getOptionValue(CMD_REMOVE_USER); router.getIdentityService().removeKieServerInstance(value); log.infof("User <%1$s> removed", value); return; } router.start(HOST, PORT, PORT_TLS); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { router.stop(); } }); }
Source:
<code>public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.TRY_STMT, ctx -> { TryStatement tryStatement = (TryStatement) ctx.syntaxNode(); Set<String> handledInterrupts = new HashSet<>(); boolean isSystemExitHandled = false; for (ExceptClause exceptClause : tryStatement.exceptClauses()) { Expression exceptionExpr = exceptClause.exception(); if (handlePossibleBareException(ctx, exceptClause, isSystemExitHandled)) { <START> break; <END> } Expression exceptionInstance = exceptClause.exceptionInstance(); Symbol exceptionInstanceSymbol = findExceptionInstanceSymbol(exceptionInstance); List<Expression> caughtExceptions = TreeUtils.flattenTuples(exceptionExpr).collect(Collectors.toList()); for (Expression caughtException : caughtExceptions) { isSystemExitHandled |= handleCaughtException(ctx, caughtException, exceptionInstanceSymbol, exceptClause.body(), isSystemExitHandled); } } }); }</code><technical_language>This if a bit weird me. I I prefer like: if (exceptionExpr == null) { handlePossibleBareException(ctx, exceptClause, isSystemExitHandled); break; } handlePossibleBareException simplified if do that</technical_language>

Target:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.TRY_STMT, ctx -> { TryStatement tryStatement = (TryStatement) ctx.syntaxNode(); boolean isSystemExitHandled = false; for (ExceptClause exceptClause : tryStatement.exceptClauses()) { Expression exceptionExpr = exceptClause.exception(); if (exceptionExpr == null) { handlePossibleBareException(ctx, exceptClause, isSystemExitHandled); break; } Expression exceptionInstance = exceptClause.exceptionInstance(); Symbol exceptionInstanceSymbol = findExceptionInstanceSymbol(exceptionInstance); List<Expression> caughtExceptions = TreeUtils.flattenTuples(exceptionExpr).collect(Collectors.toList()); for (Expression caughtException : caughtExceptions) { isSystemExitHandled |= handleCaughtException(ctx, caughtException, exceptionInstanceSymbol, exceptClause.body(), isSystemExitHandled); } } }); }
Source:
<code>public void sendAuthMeBungeecordMessage(MessageType type, String playerName) { if (isEnabled) { if (!plugin.isEnabled()) { ConsoleLogger.debug("Tried to send a " + type + " bungeecord message but the plugin was disabled!"); return; } if (type.isBroadcast()) { sendBungeecordMessage("Forward", "ALL", "AuthMe", type.getId(), playerName.toLowerCase()); } else { <START> sendBungeecordMessage("AuthMe", type.getId(), playerName.toLowerCase()); <END> } } }</code><technical_language>EDIT: Forget it. send BungeeCord channel. fine</technical_language>

Target:
public void sendAuthMeBungeecordMessage(MessageType type, String playerName) { if (isEnabled) { if (!plugin.isEnabled()) { ConsoleLogger.debug("Tried to send a " + type + " bungeecord message but the plugin was disabled!"); return; } if(type.isRequiresCaching() && !dataSource.isCached()) { return; } if (type.isBroadcast()) { sendBungeecordMessage("Forward", "ALL", "AuthMe", type.getId(), playerName.toLowerCase()); } else { sendBungeecordMessage("AuthMe", type.getId(), playerName.toLowerCase()); } } }
Source:
<code><START> public void testGaussian() throws Exception { <END> for (final double mu : Arrays.asList(0, 1)) { for (final double lambda : Arrays.asList(0.1, 1.0)) { final double theoreticalMean = mu; final double theoreticalVariance = 1/lambda; final double standardDeviationOfMean = Math.sqrt(theoreticalVariance / NUM_SAMPLES); final GibbsSampler<DoubleState, EmptyData> sampler = gaussianGibbsSampler(mu, lambda); sampler.runMCMC(); List<Double> samples = sampler.getSamples(DoubleState.PARAMETER_NAME, Double.class, NUM_BURN_IN_STEPS); final double sampleMean = samples.stream().mapToDouble(x -> x).average().getAsDouble(); Assert.assertEquals(sampleMean, theoreticalMean, 10*standardDeviationOfMean); } } }</code><technical_language>Exception is this throwing</technical_language>

Target:
public void testGaussian() { for (final double theoreticalMean : Arrays.asList(0)) { for (final double precision : Arrays.asList(1.0)) { final double variance = 1/precision; final double standardDeviationOfMean = Math.sqrt(variance / NUM_SAMPLES); final Function<Double, Double> logPDF = x -> -(precision/2)*(x-theoreticalMean)*(x-theoreticalMean); final AdaptiveMetropolisSampler sampler = new AdaptiveMetropolisSampler(INITIAL_GAUSSIAN_GUESS, INITIAL_STEP_SIZE, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); final List<Double> samples = sampler.sample(logPDF, NUM_SAMPLES, NUM_BURN_IN_STEPS); final double sampleMean = samples.stream().mapToDouble(x -> x).average().getAsDouble(); final double sampleMeanSquare = samples.stream().mapToDouble(x -> x*x).average().getAsDouble(); final double sampleVariance = (sampleMeanSquare - sampleMean * sampleMean)*NUM_SAMPLES/(NUM_SAMPLES-1); Assert.assertEquals(sampleMean, theoreticalMean, 6 * standardDeviationOfMean); Assert.assertEquals(sampleVariance, variance, variance/10); } } }
Source:
<code>private List<StorageDevice> filterStorageDevices(List<StorageDevice> storageDevices) { <START> List<StorageDevice> filteredStorageDevices = new ArrayList<StorageDevice>(); <END> List<String> mountPointsToFilterOutList = getMountPointsFilter(); List<String> fsTypesToFilterOutList = getFsTypesFilter(); for (StorageDevice device : storageDevices) { if ((device.getMountPoint() != null && mountPointsToFilterOutList.contains(device.getMountPoint())) || (device.getFsType() != null && fsTypesToFilterOutList.contains(device.getFsType()))) { continue; } if (device.getCanCreateBrick() || device.getMountPoint() != null || device.getFsType() != null) { filteredStorageDevices.add(device); } } return filteredStorageDevices; }</code><technical_language>right left type declaration omitted</technical_language>

Target:
private List<StorageDevice> filterStorageDevices(List<StorageDevice> storageDevices) { List<StorageDevice> filteredStorageDevices = new ArrayList<>(); List<String> mountPointsToFilterOutList = getMountPointsFilter(); List<String> fsTypesToFilterOutList = getFsTypesFilter(); for (StorageDevice device : storageDevices) { if ((device.getMountPoint() != null && mountPointsToFilterOutList.contains(device.getMountPoint())) || (device.getFsType() != null && fsTypesToFilterOutList.contains(device.getFsType()))) { continue; } if (device.getCanCreateBrick() || device.getMountPoint() != null || device.getFsType() != null) { filteredStorageDevices.add(device); } } return filteredStorageDevices; }
Source:
<code>private static String toCrontab(String interval) { long millis = toIntervalMillis(interval); if (millis <= TimeUnit2.MINUTES.toMillis(5)) { return "* * * * *"; } if (millis <= TimeUnit2.MINUTES.toMillis(30)) { <START> return "H/12 * * * *"; END> } if (millis <= TimeUnit2.HOURS.toMillis(1)) { return "H/4 * * * *"; } if (millis <= TimeUnit2.HOURS.toMillis(8)) { return "H/2 * * * *"; } if (millis <= TimeUnit2.DAYS.toMillis(1)) { return "H H/6 * * *"; } if (millis <= TimeUnit2.DAYS.toMillis(2)) { return "H H/2 * * *"; } return "H H * * *"; }</code><technical_language>H/12 means "every 12 minutes," "every 5 minutes"</technical_language>

Target:
private static String toCrontab(String interval) { long millis = toIntervalMillis(interval); if (millis <= TimeUnit2.MINUTES.toMillis(5)) { return "* * * * *"; } if (millis <= TimeUnit2.MINUTES.toMillis(30)) { return "H/5 * * * *"; } if (millis <= TimeUnit2.HOURS.toMillis(1)) { return "H/15 * * * *"; } if (millis <= TimeUnit2.HOURS.toMillis(8)) { return "H/30 * * * *"; } if (millis <= TimeUnit2.DAYS.toMillis(1)) { return "H H/4 * * *"; } if (millis <= TimeUnit2.DAYS.toMillis(2)) { return "H H/12 * * *"; } return "H H * * *"; }
Source:
<code>public void attachesBinaryToRelease() throws Exception { final Repo repo = new MkGithub().randomRepo(); <START> final Issue issue = repo.issues().create("", ""); <END> final String tag = "v1.0"; final File dir = this.temp.newFolder(); final String target = "target"; final String name = "name-${tag}.jar"; final File bin = FileUtils.getFile( dir.getAbsolutePath(), "repo", target, name.replace("${tag}", tag) ); Files.createParentDirs(bin); final byte[] content = RandomUtils.nextBytes(Tv.HUNDRED); Files.write(content, bin); final Talk talk = ReleaseBinariesTest.talk(issue, tag, dir); new CommentsTag(repo.github()).execute(talk); new ReleaseBinaries( repo.github(), new Profile.Fixed( new XMLDocument( StringUtils.join( "<p><entry key='release'><entry key='artifacts'>", String.format("%s/%s", target, name), "</entry></entry></p>" ) ) ) ).execute(talk); MatcherAssert.assertThat( IOUtils.toByteArray( new Releases.Smart(repo.releases()).find(tag) .assets().get(0).raw() ), Matchers.equalTo(content) ); }</code><technical_language>this is one-time variable</technical_language>

Target:
public void attachesBinaryToRelease() throws Exception { final Repo repo = new MkGithub().randomRepo(); final String tag = "v1.0"; final File dir = this.temp.newFolder(); final String target = "target"; final String name = "name-${tag}.jar"; final File bin = FileUtils.getFile( dir.getAbsolutePath(), "repo", target, name.replace("${tag}", tag) ); Files.createParentDirs(bin); final byte[] content = RandomUtils.nextBytes(Tv.HUNDRED); Files.write(content, bin); final Talk talk = ReleaseBinariesTest .talk(repo.issues().create("", ""), tag, dir); new CommentsTag(repo.github()).execute(talk); new ReleaseBinaries( repo.github(), new Profile.Fixed( new XMLDocument( StringUtils.join( "<p><entry key='release'><entry key='artifacts'>", String.format("%s/%s", target, name), "</entry></entry></p>" ) ) ) ).execute(talk); MatcherAssert.assertThat( IOUtils.toByteArray( new Releases.Smart(repo.releases()).find(tag) .assets().get(0).raw() ), Matchers.equalTo(content) ); }
Source:
<code>private void assertXMLEquals(String expected, String actual) { <START> if (expected == null || expected.trim().isEmpty()) { <END> assertEquals(XML_INTRO, actual); } else { assertEquals(XML_INTRO_OPEN + expected + XML_INTRO_CLOSE, actual); } }</code><technical_language>This is in a test argument pass (never null) if (expected.isEmpty()) is enough</technical_language>

Target:
private void assertXMLEquals(String expected, String actual) { if (expected.isEmpty()) { assertEquals(XML_INTRO, actual); } else { assertEquals(XML_INTRO_OPEN + expected + XML_INTRO_CLOSE, actual); } }
Source:
<code>@Override public void request(@NonNull Context context, @NonNull WikiSite wiki, int age, @NonNull FeedClient.Callback cb) { <START> if (CARDS == null) { CARDS = getCards(context); } <END> if (CARDS.size() > 0) { Card card = CARDS.remove(0); cb.success(Collections.singletonList(card)); } else { cb.finish(); } }</code><technical_language>list of cards, index age parameter</technical_language>

Target:
@Override public void request(@NonNull Context context, @NonNull WikiSite wiki, int age, @NonNull FeedClient.Callback cb) { List<Card> cards = getCards(context); cb.success(age < cards.size() ? Collections.singletonList(cards.get(age)) : Collections.emptyList()); }
Source:
<code>private void setCurrentSite(final HttpServletRequest req, final String userID) throws DotDataException, DotSecurityException { final HttpSession session = req.getSession(); final User user = APILocator.getUserAPI().loadUserById(userID); final String currentSiteID = (String) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_SELECTED_HOST_ID); Host currentSite = null; try { currentSite = APILocator.getHostAPI().find(currentSiteID, user, false); } catch (DotSecurityException e) { final List<Host> sites = APILocator.getHostAPI().findAll(user, false); <START> currentSite = sites.size() > 0 ? sites.get(0) : APILocator.getHostAPI().findDefaultHost(user, false); <END> } session.setAttribute(com.dotmarketing.util.WebKeys.CMS_SELECTED_HOST_ID, currentSite.getIdentifier()); }</code><technical_language>I need part of if APILocator.getHostAPI().findDefaultHost(user, false); if sites is empty means permissions site including default host. throw error if login user permissions host, meaning login fail scenario</technical_language>

Target:
private void setCurrentSite(final HttpServletRequest req, final String userID) throws DotDataException, DotSecurityException { final HttpSession session = req.getSession(); final User user = APILocator.getUserAPI().loadUserById(userID); final String currentSiteID = (String) session.getAttribute(com.dotmarketing.util.WebKeys.CMS_SELECTED_HOST_ID); Host currentSite = null; try { currentSite = APILocator.getHostAPI().find(currentSiteID, user, false); } catch (DotSecurityException e) { final List<Host> sites = APILocator.getHostAPI().findAll(user, 1,0,null, false); if (sites.isEmpty()) { throw new DotRuntimeException(String.format("The user %s don't have any site", userID)); } currentSite = sites.get(0); } session.setAttribute(com.dotmarketing.util.WebKeys.CMS_SELECTED_HOST_ID, currentSite.getIdentifier()); }
Source:
<code>public static void showDialogDeletePermanently(final Activity activity, final Note note) { new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.Dialog)) .setTitle(R.string.delete_dialog_title) .setMessage(R.string.delete_dialog_message) .setNegativeButton(R.string.no, null) .setPositiveButton( R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (note != null) { note.delete(); if (activity instanceof NotesActivity) { ((NotesActivity) activity).showDetailPlaceholder(); } else if (activity instanceof NoteEditorActivity) { <START> ((NoteEditorActivity) activity).finish(); <END> } } else { showDialogErrorDelete(activity); } } } ) .show(); }</code><technical_language>Minor ( ): Consider removing cast NoteEditorActivity for this case, is needed, it</technical_language>

Target:
public static void showDialogDeletePermanently(final Activity activity, final Note note) { new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.Dialog)) .setTitle(R.string.delete_dialog_title) .setMessage(R.string.delete_dialog_message) .setNegativeButton(R.string.cancel, null) .setPositiveButton( R.string.delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (note != null) { note.delete(); if (activity instanceof NotesActivity) { ((NotesActivity) activity).showDetailPlaceholder(); } else if (activity instanceof NoteEditorActivity) { ((NoteEditorActivity) activity).finish(); } } else { showDialogErrorDelete(activity); } } } ) .show(); }
Source:
<code>public void changeUserPasswordUsingActivationKey(String activationKey, String newPassword) throws APIException { User user = getUserByActivationKey(activationKey); if (user == null) { <START> throw new APIException("activation.key.not.correct", (Object[]) null); <END> } updatePassword(user, newPassword); }</code><technical_language>I add a new exception class throw calling code issue is necessary steps next. a other related password authentication exceptions for example</technical_language>

Target:
public void changeUserPasswordUsingActivationKey(String activationKey, String newPassword) { User user = getUserByActivationKey(activationKey); if (user == null) { throw new InvalidActivationKeyException("activation.key.not.correct"); } updatePassword(user, newPassword); }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CoordinatorEvent that = (CoordinatorEvent) o; <START> return _eventType == that._eventType && _eventMetadata.equals(that._eventMetadata); <END> }</code><technical_language>_eventMetadata null for some events. I suggest comparing Objects.equals()</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CoordinatorEvent that = (CoordinatorEvent) o; return _eventType == that._eventType && Objects.equals(_eventMetadata, that._eventMetadata); }
Source:
<code>public void populateFields(String pubId, ForeignPK fromPK, ForeignPK toPK) { UpdatableProcessInstance currentProcessInstance = (UpdatableProcessInstance) getProcessInstance(); try { PublicationTemplateManager.getInstance().addDynamicPublicationTemplate(targetId + ":" + xmlFormName, xmlFormName + ".xml"); PublicationTemplateImpl pubTemplate = (PublicationTemplateImpl) PublicationTemplateManager.getInstance().getPublicationTemplate(targetId + ":" + xmlFormName); DataRecord record = pubTemplate.getRecordSet().getEmptyRecord(); record.setId(pubId); for (String fieldName : record.getFieldNames()) { Object fieldValue = null; try { Field fieldOfFolder = currentProcessInstance.getField(fieldName); FieldTemplate fieldTemplate = pubTemplate.getRecordTemplate().getFieldTemplate(fieldName); fieldValue = fieldOfFolder.getObjectValue(); if (fieldOfFolder instanceof FileField) { fieldValue = copyFormFile(fromPK, toPK, ((FileField) fieldOfFolder).getAttachmentId()); } else if ("wysiwyg".equals(fieldTemplate.getDisplayerName())) { WysiwygFCKFieldDisplayer displayer = new WysiwygFCKFieldDisplayer(); fieldValue = displayer.duplicateContent(fieldTemplate, fromPK, toPK, I18NHelper.defaultLanguage); } <START> } catch (WorkflowException e) { <END> } record.getField(fieldName).setObjectValue(fieldValue); } pubTemplate.getRecordSet().save(record); } catch (PublicationTemplateException | FormException e) { SilverLogger.getLogger(this).error(e.getMessage(), e); } }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') remove fill this block of code. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private void populateFields(String pubId, ForeignPK fromPK, ForeignPK toPK) { UpdatableProcessInstance currentProcessInstance = (UpdatableProcessInstance) getProcessInstance(); try { PublicationTemplateManager.getInstance().addDynamicPublicationTemplate(targetId + ":" + xmlFormName, xmlFormName + ".xml"); PublicationTemplateImpl pubTemplate = (PublicationTemplateImpl) PublicationTemplateManager.getInstance().getPublicationTemplate(targetId + ":" + xmlFormName); DataRecord record = pubTemplate.getRecordSet().getEmptyRecord(); record.setId(pubId); for (String fieldName : record.getFieldNames()) { Object fieldValue = null; try { Field fieldOfFolder = currentProcessInstance.getField(fieldName); FieldTemplate fieldTemplate = pubTemplate.getRecordTemplate().getFieldTemplate(fieldName); fieldValue = fieldOfFolder.getObjectValue(); if (fieldOfFolder instanceof FileField) { fieldValue = copyFormFile(fromPK, toPK, ((FileField) fieldOfFolder).getAttachmentId()); } else if ("wysiwyg".equals(fieldTemplate.getDisplayerName())) { WysiwygFCKFieldDisplayer displayer = new WysiwygFCKFieldDisplayer(); fieldValue = displayer.duplicateContent(fieldTemplate, fromPK, toPK, I18NHelper.defaultLanguage); } } catch (WorkflowException e) { SilverLogger.getLogger(this).error("Error when populating field : "+fieldName, e); } record.getField(fieldName).setObjectValue(fieldValue); } pubTemplate.getRecordSet().save(record); } catch (PublicationTemplateException | FormException e) { SilverLogger.getLogger(this).error(e.getMessage(), e); } }
Source:
<code><START> protected Table[] doAllTables() throws SQLException { <END> String query = "select rtrim(" + tableNameField + ") from " + systemSchema + ".TABLES where " + tableTypeField + "='" + tableType + "' and " + tableSchemaField + " = ?"; return findTables(query, name); }</code><technical_language>This is working Ok</technical_language>

Target:
protected Table[] doAllTables() throws SQLException { String query = "SELECT RTRIM(" + tableNameField + ") FROM " + tablesTable + " WHERE " + tableTypeField + "='" + tableValue + "' AND " + tableSchemaField + " = ? AND " + systemTable + " <> '" + yesValue + "'"; return findTables(query, name); }
Source:
<code>private CompletableFuture<List<GetResult<V>>> multiget(List<String> keys, boolean withCas) { final int size = keys.size(); if (size == 0) { return CompletableFuture.completedFuture(Collections.<GetResult<V>>emptyList()); } final List<List<String>> keyPartition = Lists.partition(keys, MemcacheEncoder.MAX_MULTIGET_SIZE); final List<CompletableFuture<List<GetResult<byte[]>>>> futuresList = keyPartition.stream() .map(part -> rawMemcacheClient.send(MultigetRequest.create(part, charset, withCas))) .collect(Collectors.toList()); <START> final CompletableFuture<List<GetResult<byte[]>>> futures = <END> futuresList.toArray(new CompletableFuture[keyPartition.size()]); final CompletableFuture<List<GetResult<byte[]>>> future = CompletableFuture .allOf(futures) .thenApply(__ -> Arrays.stream(futures) .map(CompletableFuture::join) .flatMap(List::stream) .collect(Collectors.toList())); metrics.measureMultigetFuture(future); return transformerUtil.decodeList(future); }</code><technical_language><LINK_0> instead</technical_language>

Target:
private CompletionStage<List<GetResult<V>>> multiget(List<String> keys, boolean withCas) { final int size = keys.size(); if (size == 0) { return CompletableFuture.completedFuture(Collections.<GetResult<V>>emptyList()); } final List<List<String>> keyPartition = Lists.partition(keys, MemcacheEncoder.MAX_MULTIGET_SIZE); final List<CompletionStage<List<GetResult<byte[]>>>> futuresList = keyPartition.stream() .map(part -> rawMemcacheClient.send(MultigetRequest.create(part, charset, withCas))) .collect(Collectors.toList()); final CompletableFuture<List<GetResult<byte[]>>> futures = futuresList.toArray(new CompletableFuture[keyPartition.size()]); final CompletableFuture<List<GetResult<byte[]>>> future = CompletableFuture .allOf(futures) .thenApply(__ -> Arrays.stream(futures) .map(CompletableFuture::join) .flatMap(List::stream) .collect(Collectors.toList())); metrics.measureMultigetFuture(future); return transformerUtil.decodeList(future); }
Source:
<code>public void doFilter(final ServletRequest request, final ServletResponse response) throws IOException, ServletException { final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); final ServletRequest oldReq = servletRequestContext.getOriginalRequest(); <START> final ServletResponse oldResp = servletRequestContext.getOriginalResponse(); <END> try { if(!allowNonStandardWrappers) { if(oldReq != request) { if(!(request instanceof ServletRequestWrapper)) { throw UndertowServletMessages.MESSAGES.requestWasNotOriginalOrWrapper(request); } } if(oldResp != response) { if(!(response instanceof ServletResponseWrapper)) { throw UndertowServletMessages.MESSAGES.responseWasNotOriginalOrWrapper(response); } } } servletRequestContext.setServletRequest(request); servletRequestContext.setServletResponse(response); int index = location++; if (index >= filters.size()) { next.handleRequest(exchange); } else { filters.get(index).doFilter(request, response, this); } } catch (IOException e) { throw e; } catch (ServletException e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } finally { location--; if(!request.isAsyncStarted()) { servletRequestContext.setServletRequest(oldReq); servletRequestContext.setServletResponse(oldResp); } } }</code><technical_language>I this is correct. If multiple filters wrap request reset original filter in chain returns</technical_language>

Target:
public void doFilter(final ServletRequest request, final ServletResponse response) throws IOException, ServletException { final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY); final ServletRequest oldReq = servletRequestContext.getServletRequest(); final ServletResponse oldResp = servletRequestContext.getServletResponse(); try { if(!allowNonStandardWrappers) { if(oldReq != request) { if(!(request instanceof ServletRequestWrapper)) { throw UndertowServletMessages.MESSAGES.requestWasNotOriginalOrWrapper(request); } } if(oldResp != response) { if(!(response instanceof ServletResponseWrapper)) { throw UndertowServletMessages.MESSAGES.responseWasNotOriginalOrWrapper(response); } } } servletRequestContext.setServletRequest(request); servletRequestContext.setServletResponse(response); int index = location++; if (index >= filters.size()) { next.handleRequest(exchange); } else { filters.get(index).doFilter(request, response, this); } } catch (IOException e) { throw e; } catch (ServletException e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } finally { location--; } }
Source:
<code>public byte[] getCacheKey() { if (dimensions != null) { byte[] extractionFnBytes = extractionFn == null ? new byte[0] : extractionFn.getCacheKey(); final byte[][] dimensionsBytes = new byte[dimensions.length][]; int dimensionsBytesSize = 0; <START> if (dimensions != null) { <END> for (int i = 0; i < dimensions.length; i++) { dimensionsBytes[i] = StringUtils.toUtf8(dimensions[i]); dimensionsBytesSize += dimensionsBytes[i].length + 1; } } ByteBuffer filterCacheKey = ByteBuffer.allocate(2 + extractionFnBytes.length + dimensionsBytesSize) .put(DimFilterUtils.SELECTOR_CACHE_ID) .put(extractionFnBytes) .put(DimFilterUtils.STRING_SEPARATOR); for (byte[] bytes : dimensionsBytes) { filterCacheKey.put(bytes) .put((byte) 0xFF); } return filterCacheKey.array(); } byte[] dimensionBytes = StringUtils.toUtf8(dimension); byte[] valueBytes = (value == null) ? new byte[]{} : StringUtils.toUtf8(value); byte[] extractionFnBytes = extractionFn == null ? new byte[0] : extractionFn.getCacheKey(); return ByteBuffer.allocate(3 + dimensionBytes.length + valueBytes.length + extractionFnBytes.length) .put(DimFilterUtils.SELECTOR_CACHE_ID) .put(dimensionBytes) .put(DimFilterUtils.STRING_SEPARATOR) .put(valueBytes) .put(DimFilterUtils.STRING_SEPARATOR) .put(extractionFnBytes) .array(); }</code><technical_language>nit: redundant null check</technical_language>

Target:
public byte[] getCacheKey() { byte[] dimensionBytes = StringUtils.toUtf8(dimension); byte[] valueBytes = (value == null) ? new byte[]{} : StringUtils.toUtf8(value); byte[] extractionFnBytes = extractionFn == null ? new byte[0] : extractionFn.getCacheKey(); return ByteBuffer.allocate(3 + dimensionBytes.length + valueBytes.length + extractionFnBytes.length) .put(DimFilterUtils.SELECTOR_CACHE_ID) .put(dimensionBytes) .put(DimFilterUtils.STRING_SEPARATOR) .put(valueBytes) .put(DimFilterUtils.STRING_SEPARATOR) .put(extractionFnBytes) .array(); }
Source:
<code>protected void initProcessor(StreamProcessorDescriptor descriptor) { if (processors.containsKey(descriptor.getId())) { getLog().error("Processor already initialized: " + descriptor.getId()); return; } getLog().info("Init Stream processor: " + descriptor.getId() + " with manager: " + descriptor.config); LogManager manager = getLogManager(descriptor.config); try { Topology topology = descriptor.klass.getDeclaredConstructor().newInstance().getTopology(descriptor.options); StreamProcessor streamProcessor = new LogStreamProcessor(manager); <START> Settings settings = getSettings(descriptor); <END> if (getLog().isDebugEnabled()) { getLog().debug( "Starting computation topology: " + descriptor.getId() + "\n" + topology.toPlantuml(settings)); } streamProcessor.init(topology, settings); processors.put(descriptor.getId(), streamProcessor); } catch (ReflectiveOperationException e) { throw new StreamRuntimeException("Can not create topology for processor: " + descriptor.getId(), e); } }</code><technical_language>restrict scope of try/catch getDeclaredConstructor().newInstance()</technical_language>

Target:
protected void initProcessor(StreamProcessorDescriptor descriptor) { if (processors.containsKey(descriptor.getId())) { getLog().error("Processor already initialized: " + descriptor.getId()); return; } getLog().info("Init Stream processor: " + descriptor.getId() + " with manager: " + descriptor.config); LogManager manager = getLogManager(descriptor.config); Topology topology; try { topology = descriptor.klass.getDeclaredConstructor().newInstance().getTopology(descriptor.options); } catch (ReflectiveOperationException e) { throw new StreamRuntimeException("Can not create topology for processor: " + descriptor.getId(), e); } StreamProcessor streamProcessor = new LogStreamProcessor(manager); Settings settings = getSettings(descriptor); if (getLog().isDebugEnabled()) { getLog().debug( "Starting computation topology: " + descriptor.getId() + "\n" + topology.toPlantuml(settings)); } streamProcessor.init(topology, settings); processors.put(descriptor.getId(), streamProcessor); }
Source:
<code>public String choose(VolumeChooserEnvironment env, String[] options) throws AccumuloException { if (!env.hasTableId() && !env.hasScope()) { <START> log.warn("No table id or scope, so it's not possible to determine preferred volumes. Using all volumes."); <END> return super.choose(env, options); } ServerConfigurationFactory localConf = loadConf(); List<String> volumes; if (env.hasTableId()) { volumes = getPreferredVolumesForTable(env, localConf, options); } else { volumes = getPreferredVolumesForNonTable(env, localConf, options); } String choice = super.choose(env, volumes.toArray(EMPTY_STRING_ARRAY)); if (log.isTraceEnabled()) { log.trace("Choice = " + choice); } return choice; }</code><technical_language>PerTableVolumeChooser, this case default "init" scope</technical_language>

Target:
public String choose(VolumeChooserEnvironment env, String[] options) throws VolumeChooserException { log.trace("{}.choose", getClass().getSimpleName()); String choice = super.choose(env, getPreferredVolumes(env, options)); log.trace("Choice = {}", choice); return choice; }
Source:
<code>private void logStorageDeviceMessage(AuditLogType logType, VDS vds, final StorageDevice device) { logUtil.logAuditMessage(vds.getVdsGroupId(), null, vds, logType, <START> new HashMap<String, String>() { <END> { put("storageDevice", device.getName()); } }); }</code><technical_language>this replaced Collections.singletonMap() ? is a plan modify</technical_language>

Target:
private void logStorageDeviceMessage(AuditLogType logType, VDS vds, final StorageDevice device) { logUtil.logAuditMessage(vds.getVdsGroupId(), null, vds, logType, Collections.singletonMap("storageDevice", device.getName())); }
Source:
<code>public HostNetworkProviderModel() { getNetworkProviders().setIsChangeable(!getUseClusterDefaultNetworkProvider().getEntity()); getUseClusterDefaultNetworkProvider().getEntityChangedEvent().addListener((ev, sender, args) -> getNetworkProviders().setIsChangeable(!getUseClusterDefaultNetworkProvider().getEntity())); <START> getUseClusterDefaultNetworkProvider().getEntityChangedEvent().addListener( <END> (ev, sender, args) -> selectDefaultProvider()); getNetworkProviders().getSelectedItemChangedEvent().addListener((ev, sender, args) -> { Provider<OpenstackNetworkProviderProperties> provider = getNetworkProviders().getSelectedItem(); getNetworkProviderType().setIsAvailable(provider != null); getNetworkProviderType().setSelectedItem(provider == null ? null : provider.getType()); boolean isNeutron = getNetworkProviderType().getSelectedItem() == ProviderType.OPENSTACK_NETWORK; getNeutronAgentModel().init(isNeutron && provider != null ? provider : new Provider<>()); getNeutronAgentModel().setIsAvailable(isNeutron); }); getNetworkProviderType().setIsChangeable(false); getNetworkProviderType().setIsAvailable(false); getNeutronAgentModel().setIsAvailable(false); initNetworkProvidersList(); }</code><technical_language>do need listeners (53-54), please move 'selectDefaultProvider()' callback of listener</technical_language>

Target:
public HostNetworkProviderModel() { getNetworkProviders().setIsChangeable(!getUseClusterDefaultNetworkProvider().getEntity()); getUseClusterDefaultNetworkProvider().getEntityChangedEvent().addListener((ev, sender, args) -> { getNetworkProviders().setIsChangeable(!getUseClusterDefaultNetworkProvider().getEntity()); selectDefaultProvider(); }); getNetworkProviders().getSelectedItemChangedEvent().addListener((ev, sender, args) -> { Provider<OpenstackNetworkProviderProperties> provider = getNetworkProviders().getSelectedItem(); getNetworkProviderType().setIsAvailable(provider != null); getNetworkProviderType().setSelectedItem(provider == null ? null : provider.getType()); boolean isNeutron = getNetworkProviderType().getSelectedItem() == ProviderType.OPENSTACK_NETWORK; getNeutronAgentModel().init(isNeutron && provider != null ? provider : new Provider<>()); getNeutronAgentModel().setIsAvailable(isNeutron); }); getNetworkProviderType().setIsChangeable(false); getNetworkProviderType().setIsAvailable(false); getNeutronAgentModel().setIsAvailable(false); initNetworkProvidersList(); }
Source:
<code>public void testStartKeepaliveWLAN() throws Exception { testConnectEvent(); waitForMs(200); DataServiceManager mockDsm = mock(DataServiceManager.class); replaceInstance(DataConnection.class, "mDataServiceManager", mDc, mockDsm); doReturn(TransportType.WLAN).when(mockDsm).getTransportType(); final int sessionHandle = 0xF00; final int slotId = 3; final int interval = 10; KeepalivePacketData kd = KeepalivePacketData.nattKeepalivePacket( NetworkUtils.numericToInetAddress("1.2.3.4"), 1234, NetworkUtils.numericToInetAddress("8.8.8.8"), 4500); mDc.obtainMessage( DataConnection.EVENT_KEEPALIVE_START_REQUEST, slotId, interval, kd).sendToTarget(); waitForMs(100); try { verify(mSimulatedCommandsVerifier, times(0)) .startNattKeepalive(anyInt(), eq(kd), eq(interval * 1000), any(Message.class)); } finally { <START> restoreInstance(DataConnection.class, "mDataServiceManager", mDc); <END> } }</code><technical_language>This is needed. In super.tearDown(), replaced stuffs restored automatically</technical_language>

Target:
public void testStartKeepaliveWLAN() throws Exception { testConnectEvent(); waitForMs(200); DataServiceManager mockDsm = mock(DataServiceManager.class); doReturn(TransportType.WLAN).when(mockDsm).getTransportType(); replaceInstance(DataConnection.class, "mDataServiceManager", mDc, mockDsm); final int sessionHandle = 0xF00; final int slotId = 3; final int interval = 10; KeepalivePacketData kd = KeepalivePacketData.nattKeepalivePacket( NetworkUtils.numericToInetAddress("1.2.3.4"), 1234, NetworkUtils.numericToInetAddress("8.8.8.8"), 4500); mDc.obtainMessage( DataConnection.EVENT_KEEPALIVE_START_REQUEST, slotId, interval, kd).sendToTarget(); waitForMs(100); verify(mSimulatedCommandsVerifier, times(0)) .startNattKeepalive(anyInt(), eq(kd), eq(interval * 1000), any(Message.class)); }
Source:
<code>private Product applyProvidedProductChanges(Product entity, ProductDTO update, Owner owner) { if (update.getProvidedProducts() != null) { if (update.getProvidedProducts().isEmpty()) { <START> entity.setProvidedProducts(Collections.emptySet()); <END> } else { Set<Product> products = new HashSet<>(); for (ProductDTO providedProductDTO : update.getProvidedProducts()) { if (providedProductDTO != null) { Product newProd = this.ownerProductCurator.getProductById(owner, providedProductDTO.getId()); if (newProd == null) { log.debug("Provided product not found {}", providedProductDTO.getId()); } products.add(newProd); } } entity.setProvidedProducts(products); } } return entity; }</code><technical_language>null instead of Collections.emptySet()</technical_language>

Target:
private Product applyProvidedProductChanges(Product entity, ProductDTO update, Owner owner) { if (update.getProvidedProducts() != null && !update.getProvidedProducts().isEmpty()) { entity.getProvidedProducts().clear(); for (ProductDTO providedProductDTO : update.getProvidedProducts()) { if (providedProductDTO != null && providedProductDTO.getId() != null) { Product newProd = this.ownerProductCurator.getProductById(owner, providedProductDTO.getId()); if (newProd != null) { entity.addProvidedProduct(newProd); } } } } return entity; }