auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void populateRightPanel(final RightPanelView.Presenter rightPanelPresenter, final ScenarioGridModel scenarioGridModel) { String dmnFilePath = model.getSimulation().getSimulationDescriptor().getDmnFilePath(); if(factModelTreeHolder.getFactModelTuple() != null) { getSuccessCallback(rightPanelPresenter, scenarioGridModel).callback(factModelTreeHolder.getFactModelTuple()); } else { try { dmnTypeService.call(getSuccessCallback(rightPanelPresenter, scenarioGridModel), getErrorCallback(rightPanelPresenter)) .retrieveFactModelTuple(currentPath, dmnFilePath); } catch (Exception e) { eventBus.fireEvent(new ScenarioNotificationEvent("Failed to parse DMN", NotificationEvent.NotificationType.ERROR)); } } }

Target:
public void populateRightPanel(final RightPanelView.Presenter rightPanelPresenter, final ScenarioGridModel scenarioGridModel) { String dmnFilePath = model.getSimulation().getSimulationDescriptor().getDmnFilePath(); if (factModelTreeHolder.getFactModelTuple() != null) { getSuccessCallback(rightPanelPresenter, scenarioGridModel).callback(factModelTreeHolder.getFactModelTuple()); } else { dmnTypeService.call(getSuccessCallback(rightPanelPresenter, scenarioGridModel), getErrorCallback(rightPanelPresenter)) .retrieveFactModelTuple(currentPath, dmnFilePath); } }
Source:
static ResourceResult getResources(Context context, Request data) throws FileNotFoundException { Resources res; int id; if (data.resourceId != 0 || data.uri == null) { res = context.getResources(); id = data.resourceId; return new ResourceResult(res, id); } String pkg = data.uri.getAuthority(); if (pkg == null) throw new FileNotFoundException("No package provided: " + data.uri); try { PackageManager pm = context.getPackageManager(); res = pm.getResourcesForApplication(pkg); } catch (PackageManager.NameNotFoundException e) { throw new FileNotFoundException("Unable to obtain resources for package: " + data.uri); } List<String> segments = data.uri.getPathSegments(); if (segments == null || segments.isEmpty()) { throw new FileNotFoundException("No path segments: " + data.uri); } else if (segments.size() == 1) { try { id = Integer.parseInt(segments.get(0)); } catch (NumberFormatException e) { throw new FileNotFoundException("Last path segment is not a resource ID: " + data.uri); } } else if (segments.size() == 2) { String type = segments.get(0); String name = segments.get(1); id = res.getIdentifier(name, type, pkg); } else { throw new FileNotFoundException("More than two path segments: " + data.uri); } return new ResourceResult(res, id); }

Target:
static Resources getResources(Context context, Request data) throws FileNotFoundException { if (data.resourceId != 0 || data.uri == null) { return context.getResources(); } String pkg = data.uri.getAuthority(); if (pkg == null) throw new FileNotFoundException("No package provided: " + data.uri); try { PackageManager pm = context.getPackageManager(); return pm.getResourcesForApplication(pkg); } catch (PackageManager.NameNotFoundException e) { throw new FileNotFoundException("Unable to obtain resources for package: " + data.uri); } }
Source:
public void testWikiExample() { final CacheManager cacheManager = newCacheManagerBuilder() .withCache("preConfigured", newCacheConfigurationBuilder().buildConfig(Long.class, String.class)) .build(); final Cache<Long, String> preConfigured = cacheManager.getCache("preConfigured", Long.class, String.class); final Cache<Long, String> myCache = cacheManager.createCache("myCache", newCacheConfigurationBuilder().buildConfig(Long.class, String.class)); myCache.put(1L, "da one!"); final String value = myCache.get(1L); cacheManager.removeCache("preConfigured"); final StandaloneCache<Long, String> standaloneCache = newCacheBuilder(Long.class, String.class, LoggerFactory.getLogger(Ehcache.class+"GettingStarted")) .build(); standaloneCache.init(); cacheManager.close(); standaloneCache.close(); }

Target:
public void testWikiExample() { final CacheManager cacheManager = newCacheManagerBuilder() .withCache("preConfigured", newCacheConfigurationBuilder().buildConfig(Long.class, String.class)) .build(); final Cache<Long, String> preConfigured = cacheManager.getCache("preConfigured", Long.class, String.class); final Cache<Long, String> myCache = cacheManager.createCache("myCache", newCacheConfigurationBuilder().buildConfig(Long.class, String.class)); myCache.put(1L, "da one!"); final String value = myCache.get(1L); cacheManager.removeCache("preConfigured"); final StandaloneCache<Long, String> standaloneCache = newCacheBuilder(Long.class, String.class, LoggerFactory.getLogger(Ehcache.class + "-" + "GettingStarted")) .build(); standaloneCache.init(); cacheManager.close(); standaloneCache.close(); }
Source:
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsPlayer) { if (args.length == 0) { return false; } String message = StringUtils.join(args, " "); FUtil.bcastMsg(String.format("[§5[§eTotalFreedom§5] §b:%s] %s", sender.getName(), message)); return true; }

Target:
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsPlayer) { if (args.length == 0) { return false; } String message = StringUtils.join(args, " "); TFM_Util.bcastMsg(TFM_ConfigEntry.ANNOUNCER_PREFIX.getString().replaceAll("&", "§") + message); return true; }
Source:
private boolean isNodeUnavailableForTooLong(RMNode node) { int period = PAResourceManagerProperties.RM_UNAVAILABLE_NODES_MAX_PERIOD.getValueAsInt(); int periodInMilliseconds = period * 60 * 1000; long now = System.currentTimeMillis(); return (node.getState().equals(NodeState.DOWN) || node.getState().equals(NodeState.LOST)) && (now - node.getStateChangeTime() > periodInMilliseconds); }

Target:
private boolean isNodeUnavailableForTooLong(RMNode node) { if (PAResourceManagerProperties.RM_UNAVAILABLE_NODES_MAX_PERIOD.isSet()) { int periodInMinutes = PAResourceManagerProperties.RM_UNAVAILABLE_NODES_MAX_PERIOD.getValueAsInt(); int periodInMilliseconds = periodInMinutes * 60 * 1000; return (node.getState().equals(NodeState.DOWN) || node.getState().equals(NodeState.LOST)) && (node.millisSinceStateChanged() > periodInMilliseconds); } return false; }
Source:
public void reset() { long endSegment = Math.max(logMetadata.getGlobalTail(), 0L) / RECORDS_PER_LOG_FILE; log.warn("Global Tail:{}, endSegment={}", logMetadata.getGlobalTail(), endSegment); closeSegmentHandlers(endSegment); deleteFilesMatchingFilter(file -> { try { String segmentStr = file.getName().split("\\.")[0]; return Long.parseLong(segmentStr) <= endSegment; } catch (Exception e) { log.warn("reset: ignoring file {}", file.getName()); return false; } }); dataStore.resetStartingAddress(); dataStore.resetTailSegment(); logMetadata = new LogMetadata(); logSizeQuota = new ResourceQuota("LogSizeQuota", logSizeLimit); log.info("reset: Completed, end segment {}", endSegment); }

Target:
public void reset() { log.warn("Reset. Global Tail:{}", logMetadata.getGlobalTail()); Lock lock = resetLock.writeLock(); lock.lock(); try { closeAllSegmentHandlers(); deleteFilesMatchingFilter(file -> true); dataStore.resetStartingAddress(); dataStore.resetTailSegment(); logMetadata = new LogMetadata(); logSizeQuota = new ResourceQuota("LogSizeQuota", logSizeLimit); log.info("reset: Completed"); } finally { lock.unlock(); } }
Source:
public static List<String> getFeaturesFromFeatureRepo(String featureFilePath) { XPath xPath = XPathFactory.newInstance().newXPath(); List<String> featureIds = new ArrayList<>(); try (FileInputStream fi = new FileInputStream(new File(featureFilePath))) { Document featuresFile = XMLUtils.getInstance().getSecureDocumentBuilder(false).parse(fi); NodeList features = (NodeList) xPath.compile(FEATURE_XPATH).evaluate(featuresFile, XPathConstants.NODESET); LOGGER.info("Found feature(s)", features.getLength()); for (int i = 0; i < features.getLength(); i++) { NamedNodeMap attributes = features.item(i).getAttributes(); Node name = attributes.getNamedItem("name"); LOGGER.info("name node: {}", name.getNodeValue()); Node version = attributes.getNamedItem("version"); LOGGER.info("version node: {}", version.getNodeValue()); String featureId = String.format("%s/%s", name.getNodeValue(), version.getNodeValue()); LOGGER.info("Found feature id: {}", featureId); featureIds.add(featureId); } } catch (Exception e) { LOGGER.error( "Error encountered using xpath to retrieve names and versions from {}", featureFilePath, e); throw new RuntimeException( "Unable to read features names in feature file at: " + featureFilePath, e); } return featureIds; }

Target:
public static List<String> getFeaturesFromFeatureRepo(String featureFilePath) { XPath xPath = XPathFactory.newInstance().newXPath(); List<String> featureIds = new ArrayList<>(); try (FileInputStream fi = new FileInputStream(new File(featureFilePath))) { Document featuresFile = XMLUtils.getInstance().getSecureDocumentBuilder(false).parse(fi); NodeList features = (NodeList) xPath.compile(FEATURE_XPATH).evaluate(featuresFile, XPathConstants.NODESET); LOGGER.info("Found feature(s)", features.getLength()); for (int i = 0; i < features.getLength(); i++) { NamedNodeMap attributes = features.item(i).getAttributes(); Node name = attributes.getNamedItem("name"); Node version = attributes.getNamedItem("version"); String featureId = String.format("%s/%s", name.getNodeValue(), version.getNodeValue()); LOGGER.info("Found feature id: {}", featureId); featureIds.add(featureId); } } catch (Exception e) { LOGGER.error( "Error encountered using xpath to retrieve names and versions from {}", featureFilePath, e); throw new RuntimeException( "Unable to read features names in feature file at: " + featureFilePath, e); } return featureIds; }
Source:
public void testVarianceTooHigh() { final Long accountId = 999L; final List<Long> wakeTimeList = new ArrayList<>(); Long spread = 500L; wakeTimeList.add(0L); wakeTimeList.add(0L + spread); wakeTimeList.add(0L + spread + spread); Optional<InsightCard> someResult = WakeVariance.processWakeVarianceData(accountId, wakeTimeList, new WakeStdDevData()); assertThat(someResult.isPresent(), is(Boolean.TRUE)); final String expectedTitle = WakeVarianceMsgEN.getWakeVarianceTooHigh(0, 0).title; assertThat(someResult.get().title, is(expectedTitle)); }

Target:
public void testVarianceTooHigh() { final Long accountId = 999L; final List<Integer> wakeTimeList = new ArrayList<>(); final Integer spread = 500; wakeTimeList.add(0); wakeTimeList.add(0 + spread); wakeTimeList.add(0 + spread + spread); final Optional<InsightCard> someResult = WakeVariance.processWakeVarianceData(accountId, wakeTimeList, new WakeStdDevData()); assertThat(someResult.isPresent(), is(Boolean.TRUE)); final String expectedTitle = WakeVarianceMsgEN.getWakeVarianceTooHigh(0, 0).title; assertThat(someResult.get().title, is(expectedTitle)); }
Source:
protected Box finish(MovieHeaderBox mvhd) throws IOException { checkState(!finished, "The muxer track has finished muxing"); if (getEntries().isEmpty()) { if (codec == Codec.H264 && !spsList.isEmpty()) { SeqParameterSet sps = SeqParameterSet.read(spsList.get(0).duplicate()); Size size = H264Utils.getPicSize(sps); VideoCodecMeta meta = createSimpleVideoCodecMeta(size, ColorSpace.YUV420); addVideoSampleEntry(meta); } } setCodecPrivateIfNeeded(); return super.finish(mvhd); }

Target:
protected Box finish(MovieHeaderBox mvhd) throws IOException { checkState(!finished, "The muxer track has finished muxing"); if (getEntries().isEmpty()) { if (codec == Codec.H264 && !spsList.isEmpty()) { SeqParameterSet sps = SeqParameterSet.read(spsList.get(0).duplicate()); Size size = H264Utils.getPicSize(sps); VideoCodecMeta meta = createSimpleVideoCodecMeta(size, ColorSpace.YUV420); addVideoSampleEntry(meta); } else { Logger.warn("CodecMP4MuxerTrack: Creating a track without sample entry"); } } setCodecPrivateIfNeeded(); return super.finish(mvhd); }
Source:
public static boolean isSupported() { if (isSupportedCached == null) { log.debug("Checking if SRA module is supported in that environment"); isSupportedCached = NGS.isSupported(); if (!isSupportedCached) { log.info("SRA is not supported. Will not able to read from SRA"); } else { String versionString = appVersionString == null ? defaultAppVersionString : appVersionString; versionString += " through " + htsJdkVersionString; NGS.setAppVersionString(versionString); } } return isSupportedCached; }

Target:
public static boolean isSupported() { if (isSupportedCached == null) { log.debug("Checking if SRA module is supported in that environment"); isSupportedCached = NGS.isSupported(); if (!isSupportedCached) { log.info("SRA is not supported. Will not be able to read from SRA"); } else { NGS.setAppVersionString(getFullVersionString()); } } return isSupportedCached; }
Source:
public boolean test() { PropertyDialog pd = new PropertyDialog(project.getName()); pd.open(); new WaitUntil(new ShellIsAvailable("Properties for " + projectName), TimePeriod.DEFAULT); new DefaultTreeItem("Project Facets").select(); try { new WaitUntil(new ShellIsAvailable("Setting Java Build Path"), TimePeriod.DEFAULT); new PushButton("Discard").click(); } catch (Exception e) { } boolean result; if (natureParent != null) { result = new DefaultTreeItem(new DefaultTree(1), natureParent, natureID).isChecked(); if (version != null) { result = result && new DefaultTreeItem(new DefaultTree(1), natureParent, natureID).getCell(1).equals(version); } } else { result = new DefaultTreeItem(new DefaultTree(1), natureID).isChecked(); if (version != null) { result = result && new DefaultTreeItem(new DefaultTree(1), natureID).getCell(1).equals(version); } } pd.ok(); new WaitWhile(new ShellIsAvailable("Properties for " + projectName), TimePeriod.DEFAULT); return result; }

Target:
public boolean test() { PropertyDialog pd = new PropertyDialog(project.getName()); pd.open(); new WaitUntil(new ShellIsAvailable("Properties for " + projectName), TimePeriod.DEFAULT); new DefaultTreeItem("Project Facets").select(); if (!JavaVersionHelper.getJavaVersion().equals("1.8")) { try { new DefaultShell("Setting Java Build Path"); new PushButton("Apply").click(); } catch (CoreLayerException e) { } } boolean result; if (natureParent != null) { result = new DefaultTreeItem(new DefaultTree(1), natureParent, natureID).isChecked(); if (version != null) { result = result && new DefaultTreeItem(new DefaultTree(1), natureParent, natureID).getCell(1).equals(version); } } else { result = new DefaultTreeItem(new DefaultTree(1), natureID).isChecked(); if (version != null) { result = result && new DefaultTreeItem(new DefaultTree(1), natureID).getCell(1).equals(version); } } pd.ok(); new WaitWhile(new ShellIsAvailable("Properties for " + projectName), TimePeriod.DEFAULT); return result; }
Source:
public void update() throws BankException, LoginException, BankChoiceException, IOException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText(R.string.invalid_username_password).toString()); } urlopen = login(); String loanName; Matcher matcher; try { matcher = reAccountLink.matcher(this.lastResponse); while (matcher.find()) { accounts.add(new Account( Html.fromHtml(matcher.group(3)).toString().trim(), Helpers.parseBalance(Html.fromHtml(matcher.group(5)).toString()), Html.fromHtml(matcher.group(4)).toString().trim() )); } goToPage(PageType.CREDIT_CARDS); matcher = reCreditCardLink.matcher(this.lastResponse); while (matcher.find()) { accounts.add(new Account( matcher.group(2), Helpers.parseBalance(matcher.group(5)), "c:" + matcher.group(3), -1L, Account.CCARD )); } goToPage(PageType.LOANS); matcher = reLoanLink.matcher(this.lastResponse); while (matcher.find()) { loanName = matcher.group(2) + ' ' + matcher.group(3); accounts.add(new Account( loanName, Helpers.parseBalance(matcher.group(5)), "l:" + matcher.group(3).trim(), -1L, Account.LOANS )); } if (accounts.isEmpty()) { throw new BankException(res.getText(R.string.no_accounts_found).toString()); } } finally { super.updateComplete(); } }

Target:
public void update() throws BankException, LoginException, BankChoiceException, IOException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText(R.string.invalid_username_password).toString()); } urlopen = login(); String loanName; Matcher matcher = reAccountLink.matcher(this.lastResponse); while (matcher.find()) { accounts.add(new Account( Html.fromHtml(matcher.group(3)).toString().trim(), Helpers.parseBalance(Html.fromHtml(matcher.group(5)).toString()), Html.fromHtml(matcher.group(4)).toString().trim() )); } goToPage(PageType.CREDIT_CARDS); matcher = reCreditCardLink.matcher(this.lastResponse); while (matcher.find()) { accounts.add(new Account( matcher.group(2), Helpers.parseBalance(matcher.group(5)), "c:" + matcher.group(3), -1L, Account.CCARD )); } goToPage(PageType.LOANS); matcher = reLoanLink.matcher(this.lastResponse); while (matcher.find()) { loanName = matcher.group(2) + ' ' + matcher.group(3); accounts.add(new Account( loanName, Helpers.parseBalance(matcher.group(5)), "l:" + matcher.group(3).trim(), -1L, Account.LOANS )); } if (accounts.isEmpty()) { throw new BankException(res.getText(R.string.no_accounts_found).toString()); } super.updateComplete(); }
Source:
public void typeInSearchField(String content, int length) { waitForElementVisibleByElement(searchInput); searchInput.sendKeys(content.substring(0, length)); PageObjectLogging.log( "typeInSearchField", "String >>" + content.substring(0, length) + "<< was typed in string field", true ); }

Target:
public void typeInSearchField(String content, int length) { waitForElementVisibleByElement(searchInput); searchInput.sendKeys(content.substring(0, 3)); PageObjectLogging.log( "typeInSearchField", "String >>" + content.substring(0, length) + "<< was typed in string field", true ); }
Source:
void start(Bench bench, String action) { this.currentAction = bench.getName() + ": " + action; this.startTime = System.nanoTime(); }

Target:
void start(Bench bench, String action) { this.currentAction = bench.getName() + ": " + action; this.startTimeNs = System.nanoTime(); }
Source:
public static boolean matchProperties(final Cluster oldEntity, final Cluster newEntity) { Map<String, String> oldProps = new HashMap<String, String>(); Map<String, String> newProps = new HashMap<String, String>(); if (oldEntity.getProperties() != null) { for (Property prop : oldEntity.getProperties().getProperties()) { oldProps.put(prop.getName(), prop.getValue()); } } if (newEntity.getProperties() != null) { for (Property prop : newEntity.getProperties().getProperties()) { newProps.put(prop.getName(), prop.getValue()); } } if (oldProps.keySet().equals(newProps.keySet())) { for (Map.Entry<String, String> keyVals : oldProps.entrySet()) { if (!keyVals.getValue().equals(newProps.get(keyVals.getKey()))) { return false; } } return true; } return false; }

Target:
public static boolean matchProperties(final Cluster oldEntity, final Cluster newEntity) { Map<String, String> oldProps = getClusterProperties(oldEntity); Map<String, String> newProps = getClusterProperties(newEntity); return oldProps.equals(newProps); }
Source:
public final TypeClass asHaskellObject(final Context ctx) { TypeBuilder builder = new TypeBuilder(ctx.typeClasses); TypeClass tc = new TypeClass(this.getName()); for (String instance : this.instances) { Type t = builder.build(instance); if (t instanceof ConstT) tc.getTypes().add((ConstT) t); } return tc; }

Target:
public final TypeClass asHaskellObject(final Context ctx) { TypeBuilder builder = new TypeBuilder(ctx.typeClasses); TypeClass tc = new TypeClass(this.getName()); for (String instance : this.instances) { Type t = builder.build(instance); if (t instanceof ConstT) { tc.getTypes().add((ConstT) t); } } return tc; }
Source:
public void testInfo() throws IOException { SimpleFeatureStore store1 = (SimpleFeatureStore) data.getFeatureSource(first.typeName); ResourceInfo info = store1.getInfo(); assertEquals("sf_roads", info.getName()); assertEquals("Generated from sfRoads", info.getDescription()); assertTrue(info.getKeywords().contains("sfRoads roads")); assertEquals("roads_Type", info.getTitle()); assertEquals("<LINK_0>", info.getSchema().toString()); assertEquals(589242.03, info.getBounds().getMinX(),0.01); assertEquals("EPSG:NAD27 / UTM zone 13N", info.getCRS().getName().toString()); }

Target:
public void testInfo() throws IOException { SimpleFeatureStore store1 = (SimpleFeatureStore) data.getFeatureSource(first.typeName); ResourceInfo info = store1.getInfo(); assertEquals("sf_roads", info.getName()); assertEquals("Generated from sfRoads", info.getDescription()); assertTrue(info.getKeywords().contains("sfRoads roads")); assertEquals("roads_Type", info.getTitle()); assertEquals("<LINK_0>", info.getSchema().toString()); assertEquals(589275.24, info.getBounds().getMinX(), 0.01); assertEquals("EPSG:NAD27 / UTM zone 13N", info.getCRS().getName().toString()); }
Source:
private <T extends Config> T loadConfig(String configDirectory, String configFileName, Class<T> configClass) { FileHelper configFileHelper = new FileHelper(configDirectory, configFileName); String fileContents; if (!configFileHelper.exists()) { fileContents = DEFAULT_FILE_CONTENTS; } else { try { fileContents = configFileHelper.loadFileContents(); } catch (IOException e) { HTLog.error(logger, e); logger.error(e.toString()); fileContents = DEFAULT_FILE_CONTENTS; } } return createConfig(fileContents, configClass); }

Target:
private <T> T loadConfig(String configDirectory, String configFileName, Class<T> configClass) { String fileContents = DEFAULT_FILE_CONTENTS; if (FileHelper.isFileExists(configDirectory, configFileName)) { try { fileContents = FileHelper.getFileContents(configDirectory, configFileName); } catch (IOException e) { HTLog.error(logger, e); logger.error(e.toString()); } } return createConfig(fileContents, configClass); }
Source:
public String call() { StringBuilder result = new StringBuilder(); final File rootPath = new File(this.rootPathName); for (File file : Preconditions.checkNotNull(rootPath.listFiles())) { if (file.isFile()) { try { result.append(Util.getDigestOf(new FileInputStream(file))) .append(" ") .append(file.getName()).append('\n'); } catch (IOException e) { } } } return result.toString(); }

Target:
public String call() { StringBuilder result = new StringBuilder(); final File rootPath = new File(this.rootPathName); for (File file : FileUtils.listFiles(rootPath, null, false)) { if (file.isFile()) { try { result.append(Util.getDigestOf(new FileInputStream(file))) .append(" ") .append(file.getName()).append('\n'); } catch (IOException e) { } } } return result.toString(); }
Source:
public void handleQueryMessage(final long senderHSId, long requestId, long gapStart) { m_es.execute(new Runnable() { @Override public void run() { boolean canCover = canCoverNextSequenceNumber(gapStart); long lastSeq = m_gapTracker.getRangeContaining(gapStart); sendQueryResponse(senderHSId, requestId, canCover, lastSeq); } }); }

Target:
public void handleQueryMessage(final long senderHSId, long requestId, long gapStart) { m_es.execute(new Runnable() { @Override public void run() { long lastSeq = Long.MIN_VALUE; Pair<Long, Long> range = m_gapTracker.getRangeContaining(gapStart); if (range != null) { lastSeq = range.getSecond(); } sendQueryResponse(senderHSId, requestId, lastSeq); } }); }
Source:
static int read(ReadableByteChannel channel, ByteBuffer buffer) throws IOException { int read = channel.read(buffer); if(read < 0) { throw new IOException("Channel has reached EOF"); } return read; }

Target:
static int read(ReadableByteChannel channel, ByteBuffer buffer) throws IOException { int read = channel.read(buffer); if(read < 0) { throw new IOException("I/O thread: reached EOF"); } return read; }
Source:
public Set<Integer> getRemovedPartitions(JobConfig jobConfig, JobContext jobContext, Set<Integer> allPartitions) { Set<Integer> deletedPartitions = new HashSet<>(); for (Integer partition : jobContext.getPartitionSet()) { if (!allPartitions.contains(partition)) { deletedPartitions.add(partition); } } return deletedPartitions; }

Target:
public Set<Integer> getRemovedPartitions(JobConfig jobConfig, JobContext jobContext, Set<Integer> allPartitions) { return jobContext.getPartitionSet().stream().filter(partition -> !allPartitions.contains(partition)).collect( Collectors.toSet()); }
Source:
private boolean updateIsoListFromVDSM(Guid repoStoragePoolId, Guid repoStorageDomainId) { boolean refreshIsoSucceeded = false; if (repoStorageDomainId != null) { try { VDSReturnValue returnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.GetIsoList, new IrsBaseVDSCommandParameters(repoStoragePoolId)); @SuppressWarnings("unchecked") Map<String, Map<String, String>> isoDomainList = (Map<String, Map<String, String>>) returnValue.getReturnValue(); if (returnValue.getSucceeded() && isoDomainList != null) { log.debugFormat("The refresh process from VDSM, for Iso files succeeded."); refreshIsoSucceeded = refreshIsoFileListMetaData(repoStorageDomainId, repoStorageDom, isoDomainList, ImageFileType.ISO); } } catch (Exception e) { refreshIsoSucceeded = false; log.warnFormat("The refresh process from VDSM, for Iso files failed."); log.error(e); } } return refreshIsoSucceeded; }

Target:
private boolean updateIsoListFromVDSM(Guid repoStoragePoolId, Guid repoStorageDomainId) { boolean refreshIsoSucceeded = false; if (repoStorageDomainId != null) { try { VDSReturnValue returnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.GetIsoList, new IrsBaseVDSCommandParameters(repoStoragePoolId)); @SuppressWarnings("unchecked") Map<String, Map<String, String>> fileStats = (Map<String, Map<String, String>>) returnValue.getReturnValue(); if (returnValue.getSucceeded() && fileStats != null) { log.debugFormat("The refresh process from VDSM, for Iso files succeeded."); refreshIsoSucceeded = refreshIsoFileListMetaData(repoStorageDomainId, repoStorageDom, fileStats, ImageFileType.ISO); } } catch (Exception e) { refreshIsoSucceeded = false; log.warnFormat("The refresh process from VDSM, for Iso files failed."); log.error(e); } } return refreshIsoSucceeded; }
Source:
public List<SDVariable> doDiff(List<SDVariable> i_v1) { SDVariable prod = outputVariables()[0]; SDVariable broadcastableGrad = sameDiff.f().reductionBroadcastableWithOrigShape(arg().getShape().length, dimensions, i_v1.get(0)); SDVariable broadcastableProd = sameDiff.f().reductionBroadcastableWithOrigShape(arg().getShape().length, dimensions, prod); SDVariable mul = broadcastableGrad.div(broadcastableProd); SDVariable ret = arg().mul(mul); return Collections.singletonList(ret); }

Target:
public List<SDVariable> doDiff(List<SDVariable> i_v1) { SDVariable prod = outputVariables()[0]; int origRank = Shape.rankFromShape(arg().getShape()); SDVariable broadcastableGrad = sameDiff.f().reductionBroadcastableWithOrigShape(origRank, dimensions, i_v1.get(0)); SDVariable broadcastableProd = sameDiff.f().reductionBroadcastableWithOrigShape(origRank, dimensions, prod); SDVariable mul = broadcastableGrad.div(broadcastableProd); SDVariable ret = arg().mul(mul); return Collections.singletonList(ret); }
Source:
public String getDescription() { return "add network partition deployment"; }

Target:
public String getDescription() { return "Add network partition deployment"; }
Source:
public <D, M> M toAvro(Schema schema, D input) { return ((AvroMapper<D, M>) getMapper(input.getClass())).toAvro(schema, input); }

Target:
public <D, M> M toAvro(Schema schema, D input) { return (M) getMapper((Class<D>) input.getClass()).toAvro(schema, input); }
Source:
public int getHeight() { int height = 0; try { height = ImageUtil.getInstance().getDimension(getFileAsset()).height; } catch(Exception e) { Logger.error(this, e.getMessage()); } return height; }

Target:
public int getHeight() { try { if (fileDimension.height == 0) { fileDimension = ImageUtil.getInstance().getDimension(getFileAsset()); } } catch (Exception e) { Logger.error(this, e.getMessage()); } return fileDimension.height; }
Source:
public static PDPrintStyle getPolygonStyle (JSONObject oskariStyle, PDResources resources) throws IOException { PDPrintStyle style = new PDPrintStyle(); JSONObject stroke = JSONHelper.optJSONObject(oskariStyle, "stroke", () -> new JSONObject()); JSONObject strokeArea = JSONHelper.optJSONObject(stroke, "area", () -> new JSONObject()); setStrokeStyle(style, strokeArea); JSONObject fill = JSONHelper.optJSONObject(oskariStyle, "fill", () -> new JSONObject()); JSONObject fillArea = JSONHelper.optJSONObject(fill, "area", () -> new JSONObject()); int pattern = fillArea.optInt("pattern"); Color color = ColorUtil.parseColor(JSONHelper.optString(fill,"color")); style.setFillColor(color); if (pattern >= 0 && pattern <= 3 && color != null) { style.setFillPattern(createFillPattern(resources, pattern, color)); } setLabelStyle(style, oskariStyle); return style; }

Target:
public static PDPrintStyle getPolygonStyle (JSONObject oskariStyle, PDResources resources) throws IOException { JSONObject stroke = oskariStyle.optJSONObject("stroke"); if (stroke != null) { stroke = stroke.optJSONObject("area"); } PDPrintStyle style = new PDPrintStyle(); setStrokeStyle(style, stroke); setFillStyle(style, oskariStyle, resources); setLabelStyle(style, oskariStyle); return style; }
Source:
private void onDeleteSnapshot() { if (getConfirmWindow() == null) { return; } ConfirmationModel model = (ConfirmationModel) getConfirmWindow(); if (model.getProgress() != null) { return; } List<VdcActionParametersBase> paramsList = new ArrayList<>(); for (GlusterVolumeSnapshotEntity snapshot : (List<GlusterVolumeSnapshotEntity>) getSelectedItems()) { GlusterVolumeSnapshotActionParameters param = new GlusterVolumeSnapshotActionParameters(getEntity().getId(), snapshot.getSnapshotName(), true); paramsList.add(param); } model.startProgress(null); Frontend.getInstance().runMultipleAction(VdcActionType.DeleteGlusterVolumeSnapshot, paramsList, new IFrontendMultipleActionAsyncCallback() { @Override public void executed(FrontendMultipleActionAsyncResult result) { ConfirmationModel localModel = (ConfirmationModel) getConfirmWindow(); localModel.stopProgress(); setConfirmWindow(null); } }, model); }

Target:
private void onDeleteSnapshot() { if (getConfirmWindow() == null) { return; } ConfirmationModel model = (ConfirmationModel) getConfirmWindow(); List<VdcActionParametersBase> paramsList = new ArrayList<>(); for (GlusterVolumeSnapshotEntity snapshot : (List<GlusterVolumeSnapshotEntity>) getSelectedItems()) { GlusterVolumeSnapshotActionParameters param = new GlusterVolumeSnapshotActionParameters(getEntity().getId(), snapshot.getSnapshotName(), true); paramsList.add(param); } model.startProgress(null); Frontend.getInstance().runMultipleAction(VdcActionType.DeleteGlusterVolumeSnapshot, paramsList, new IFrontendMultipleActionAsyncCallback() { @Override public void executed(FrontendMultipleActionAsyncResult result) { ConfirmationModel localModel = (ConfirmationModel) getConfirmWindow(); localModel.stopProgress(); setConfirmWindow(null); } }, model); }
Source:
public TableSaw(Category category, SlimefunItemStack item) { super(category, item, new ItemStack[] { null, null, null, new ItemStack(Material.SMOOTH_STONE_SLAB), new ItemStack(Material.STONECUTTER), new ItemStack(Material.SMOOTH_STONE_SLAB), null, new ItemStack(Material.IRON_BLOCK), null }, BlockFace.SELF); for (Material log : Tag.LOGS.getValues()) { Optional<Material> planks = MaterialConverter.getPlanksFromLog(log); if (planks.isPresent()) { displayedRecipes.add(new ItemStack(log)); displayedRecipes.add(new ItemStack(planks.get(), 8)); } } CustomItem ci = new CustomItem(Material.OAK_PLANKS, "Any Wooden Plank"); displayedRecipes.add(new ItemStack(ci)); displayedRecipes.add(new ItemStack(Material.STICK, 4)); }

Target:
public TableSaw(Category category, SlimefunItemStack item) { super(category, item, new ItemStack[] { null, null, null, new ItemStack(Material.SMOOTH_STONE_SLAB), new ItemStack(Material.STONECUTTER), new ItemStack(Material.SMOOTH_STONE_SLAB), null, new ItemStack(Material.IRON_BLOCK), null }, BlockFace.SELF); for (Material log : Tag.LOGS.getValues()) { Optional<Material> planks = MaterialConverter.getPlanksFromLog(log); if (planks.isPresent()) { displayedRecipes.add(new ItemStack(log)); displayedRecipes.add(new ItemStack(planks.get(), 8)); } } for (Material plank : Tag.PLANKS.getValues()) { displayedRecipes.add(new ItemStack(plank)); displayedRecipes.add(new ItemStack(Material.STICK, 4)); } }
Source:
public void operateList() { final Key key = new Key(args.namespace, args.set, "aoplkey1"); Mono<KeyRecord> mono = reactorClient.delete(key) .switchIfEmpty(Mono.just(key)) .flatMap(key1 -> { List<Value> itemList = new ArrayList<Value>(); itemList.add(Value.get(55)); itemList.add(Value.get(77)); return reactorClient.operate(key, ListOperation.appendItems(binName, itemList), ListOperation.pop(binName, -1), ListOperation.size(binName)); }); StepVerifier.create(mono) .expectNextMatches(keyRecord -> { assertRecordFound(keyRecord.key, keyRecord.record); List<?> list = keyRecord.record.getList(binName); long size = (Long)list.get(0); assertEquals(2, size); long val = (Long)list.get(1); assertEquals(77, val); size = (Long)list.get(2); assertEquals(1, size); return true; }) .verifyComplete(); }

Target:
public void operateList() { final Key key = new Key(args.namespace, args.set, "aoplkey1"); Mono<KeyRecord> mono = reactorClient.delete(key) .switchIfEmpty(Mono.just(key)) .flatMap(key1 -> { List<Value> itemList = new ArrayList<Value>(); itemList.add(Value.get(55)); itemList.add(Value.get(77)); return reactorClient.operate(key, ListOperation.appendItems(binName, itemList), ListOperation.pop(binName, -1), ListOperation.size(binName)); }); StepVerifier.create(mono) .expectNextMatches(keyRecord -> { assertRecordFound(keyRecord.key, keyRecord.record); List<?> list = keyRecord.record.getList(binName); assertThat((Long)list.get(0)).isEqualTo(2); assertThat((Long)list.get(1)).isEqualTo(77); assertThat((Long)list.get(2)).isEqualTo(1); return true; }) .verifyComplete(); }
Source:
public List<String> getRepoTags() { return repoTags; }

Target:
public String[] getRepoTags() { return repoTags; }
Source:
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry) { List<ScalarImplementationChoice> implementationChoices = new ArrayList<>(); for (PolymorphicScalarFunctionChoice choice : choices) { implementationChoices.add(getScalarFunctionImplementationChoice(boundVariables, typeManager, functionRegistry, choice)); } return new ScalarFunctionImplementation(implementationChoices, deterministic); }

Target:
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry) { ImmutableList.Builder<ScalarImplementationChoice> implementationChoices = ImmutableList.builder(); for (PolymorphicScalarFunctionChoice choice : choices) { implementationChoices.add(getScalarFunctionImplementationChoice(boundVariables, typeManager, functionRegistry, choice)); } return new ScalarFunctionImplementation(implementationChoices.build(), deterministic); }
Source:
private String networkVisualization(String networkId, ModelMap model) throws QuadrigaStorageException{ INetwork network = networkManager.getNetwork(networkId); if(network==null){ return "auth/404"; } ITransformedNetwork transformedNetwork= transformationManager.getTransformedNetwork(networkId); String nwId = "\""+networkId+"\""; model.addAttribute("networkid",nwId); model.addAttribute("network", network); String json = null; if(transformedNetwork!=null){ json = d3Creator.getD3JSON(transformedNetwork.getNodes(), transformedNetwork.getLinks()); } model.addAttribute("jsonstring",json); return "auth/networks/visualize"; }

Target:
private String networkVisualization(String networkId, ModelMap model) throws QuadrigaStorageException { INetwork network = networkManager.getNetwork(networkId); if (network == null) { return "auth/404"; } ITransformedNetwork transformedNetwork = transformationManager.getTransformedNetwork(networkId); model.addAttribute("networkid", networkId); model.addAttribute("network", network); String json = null; if (transformedNetwork != null) { json = d3Creator.getD3JSON(transformedNetwork.getNodes(), transformedNetwork.getLinks()); } model.addAttribute("jsonstring", json); return "auth/networks/visualize"; }
Source:
public void onSchemaAddQueryEntity(SchemaAddQueryEntityOperation op) { CacheConfiguration oldCfg = cacheCfg; if (oldCfg != null) { CacheConfiguration newCfg = new CacheConfiguration(oldCfg); newCfg.setQueryEntities(Collections.singletonList(op.entity())); newCfg.setSqlSchema(op.schemaName()); newCfg.setSqlEscapeAll(op.isSqlEscape()); newCfg.setQueryParallelism(op.queryParallelism()); cacheCfg = newCfg; } if (qryMgr != null) qryMgr.enable(); }

Target:
public void onSchemaAddQueryEntity(SchemaAddQueryEntityOperation op) { onSchemaAddQueryEntity(op.entities(), op.schemaName(), op.isSqlEscape(), op.queryParallelism()); }
Source:
public ApiPersistentConnection getApiPersistentConnection(String name) { for (ApiPersistentConnection other : this.apiPersistentConnections) { if (other.getName().equals(name)) { return other; } } return null; }

Target:
public ApiPersistentConnection getApiPersistentConnection(String name) { for (ApiPersistentConnection pconn : this.apiPersistentConnections) { if (pconn.getName().equals(name)) { return pconn; } } return null; }
Source:
public void LightboxTest_010_filepage_video() { WikiBasePageObject base = new WikiBasePageObject(driver); SpecialVideosPageObject specialVideos = base.openSpecialVideoPage(wikiURL); int itemNumber = 0; String fileUrl = specialVideos.getFileUrl(wikiURL, itemNumber); LightboxComponentObject lightbox = specialVideos.openLightboxForGridVideo(itemNumber); lightbox.verifyLightboxPopup(); lightbox.verifyLightboxVideo(); lightbox.verifyTitleUrl(fileUrl); lightbox.verifyMoreInfoUrl(fileUrl); FilePagePageObject filePage = lightbox.clickTitle(); filePage.verifyTabsExistVideo(); filePage.verifyEmbeddedVideoIsPresent(); filePage.verifyVideoAutoplay(true); }

Target:
public void LightboxTest_010_filepage_video() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); SpecialVideosPageObject specialVideos = base.openSpecialVideoPage(wikiURL); int itemNumber = 0; String fileUrl = specialVideos.getFileUrl(wikiURL, itemNumber); LightboxComponentObject lightbox = specialVideos.openLightboxForGridVideo(itemNumber); lightbox.verifyLightboxPopup(); lightbox.verifyLightboxVideo(); FilePagePageObject filePage = lightbox.clickTitle(); filePage.verifyTabsExistVideo(); filePage.verifyEmbeddedVideoIsPresent(); filePage.verifyVideoAutoplay(true); }
Source:
public URL getComplexQueryURL(ComplexSearchQuery complexSearchQuery) { try { URIBuilder uriBuilder = new URIBuilder("<LINK_0>"); uriBuilder.addParameter("apikey", API_KEY); complexSearchQuery.getDefaultField().ifPresent(defaultField -> uriBuilder.addParameter("querytext", defaultField)); complexSearchQuery.getAuthor().ifPresent(author -> uriBuilder.addParameter("author", author)); complexSearchQuery.getTitle().ifPresent(articleTitle -> uriBuilder.addParameter("article_title", articleTitle)); complexSearchQuery.getJournal().ifPresent(journalTitle -> uriBuilder.addParameter("publication_title", journalTitle)); complexSearchQuery.getFromYear().map(String::valueOf).ifPresent(year -> uriBuilder.addParameter("start_year", year)); complexSearchQuery.getToYear().map(String::valueOf).ifPresent(year -> uriBuilder.addParameter("end_year", year)); URLDownload.bypassSSLVerification(); return uriBuilder.build().toURL(); } catch (URISyntaxException | MalformedURLException ex) { LOGGER.error("Error creating URL.", ex); throw new IllegalStateException("Error during creation of URL.", ex); } }

Target:
public URL getComplexQueryURL(ComplexSearchQuery complexSearchQuery) throws URISyntaxException, MalformedURLException { URIBuilder uriBuilder = new URIBuilder("<LINK_0>"); uriBuilder.addParameter("apikey", API_KEY); complexSearchQuery.getDefaultField().ifPresent(defaultField -> uriBuilder.addParameter("querytext", defaultField)); complexSearchQuery.getAuthors().ifPresent(authors -> uriBuilder.addParameter("author", String.join(" AND ", authors))); complexSearchQuery.getTitlePhrases().ifPresent(articleTitlePhrases -> uriBuilder.addParameter("article_title", String.join(" AND ", articleTitlePhrases))); complexSearchQuery.getJournal().ifPresent(journalTitle -> uriBuilder.addParameter("publication_title", journalTitle)); complexSearchQuery.getFromYear().map(String::valueOf).ifPresent(year -> uriBuilder.addParameter("start_year", year)); complexSearchQuery.getToYear().map(String::valueOf).ifPresent(year -> uriBuilder.addParameter("end_year", year)); complexSearchQuery.getSingleYear().map(String::valueOf).ifPresent(year -> { uriBuilder.addParameter("start_year", year); uriBuilder.addParameter("end_year", year); }); URLDownload.bypassSSLVerification(); return uriBuilder.build().toURL(); }
Source:
private RebaseResult cherryPickCommit(RevCommit commitToPick) throws IOException, GitAPIException, NoMessageException, UnmergedPathsException, ConcurrentRefUpdateException, WrongRepositoryStateException, NoHeadException { try { monitor.beginTask(MessageFormat.format( JGitText.get().applyingCommit, commitToPick.getShortMessage()), ProgressMonitor.UNKNOWN); if (preserveMerges) return cherryPickCommitPreservingMerges(commitToPick); newHead = tryFastForward(commitToPick); lastStepWasForward = newHead != null; if (!lastStepWasForward) { String ourCommitName = getOurCommitName(); CherryPickResult cherryPickResult = new Git(repo).cherryPick() .include(commitToPick).setOurCommitName(ourCommitName) .setReflogPrefix(REFLOG_PREFIX).setStrategy(strategy) .call(); switch (cherryPickResult.getStatus()) { case FAILED: if (operation == Operation.BEGIN) return abort(RebaseResult.failed(cherryPickResult .getFailingPaths())); else return stop(commitToPick, Status.STOPPED); case CONFLICTING: return stop(commitToPick, Status.STOPPED); case OK: newHead = cherryPickResult.getNewHead(); } } return null; } finally { monitor.endTask(); } }

Target:
private RebaseResult cherryPickCommit(RevCommit commitToPick) throws IOException, GitAPIException, NoMessageException, UnmergedPathsException, ConcurrentRefUpdateException, WrongRepositoryStateException, NoHeadException { try { monitor.beginTask(MessageFormat.format( JGitText.get().applyingCommit, commitToPick.getShortMessage()), ProgressMonitor.UNKNOWN); if (preserveMerges) return cherryPickCommitPreservingMerges(commitToPick); else return cherryPickCommitFlattening(commitToPick); } finally { monitor.endTask(); } }
Source:
public void testRecordsException() throws Exception { TestException testException = new TestException(); TestRequestDispatcher requestProcessor = new TestRequestDispatcher() { @Override public void dispatch(ChannelStateWriteRequest request) { throw testException; } }; LinkedBlockingDeque<ChannelStateWriteRequest> deque = new LinkedBlockingDeque<>(Arrays.asList(new TestWriteRequest())); try (ChannelStateWriteRequestExecutorImpl worker = new ChannelStateWriteRequestExecutorImpl(requestProcessor, deque)) { worker.start(); } }

Target:
public void testRecordsException() throws IOException { TestException testException = new TestException(); TestRequestDispatcher throwingRequestProcessor = new TestRequestDispatcher() { @Override public void dispatch(ChannelStateWriteRequest request) { throw testException; } }; LinkedBlockingDeque<ChannelStateWriteRequest> deque = new LinkedBlockingDeque<>(Arrays.asList(new TestWriteRequest())); ChannelStateWriteRequestExecutorImpl worker = new ChannelStateWriteRequestExecutorImpl(throwingRequestProcessor, deque); worker.run(); try { worker.close(); } catch (IOException e) { if (findThrowable(e, TestException.class).filter(found -> found == testException).isPresent()) { return; } else { throw e; } } fail("exception not thrown"); }
Source:
public void shutdown(){ buffer.clear(); if (thread != null) thread.interrupt(); try { if (thread != null) thread.join(); } catch (InterruptedException e) { } buffer.clear(); }

Target:
public void shutdown(){ buffer.clear(); if (thread != null) thread.interrupt(); try { if (thread != null) thread.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } buffer.clear(); }
Source:
public LocationHandle forTemporaryTable(SemiTransactionalHiveMetastore metastore, ConnectorSession session, Table table) { String schemaName = table.getDatabaseName(); String tableName = table.getTableName(); HdfsContext context = new HdfsContext(session, schemaName, tableName); Path targetPath = getTableDefaultLocation(context, metastore, hdfsEnvironment, schemaName, tableName); if (pathExists(context, hdfsEnvironment, targetPath)) { deleteDirectory(context, hdfsEnvironment, targetPath); } return new LocationHandle(targetPath, targetPath, TEMPORARY, DIRECT_TO_TARGET_NEW_DIRECTORY); }

Target:
public LocationHandle forTemporaryTable(SemiTransactionalHiveMetastore metastore, ConnectorSession session, Table table) { String schemaName = table.getDatabaseName(); String tableName = table.getTableName(); HdfsContext context = new HdfsContext(session, schemaName, tableName); Path targetPath = new Path(getTableDefaultLocation(context, metastore, hdfsEnvironment, schemaName, tableName), randomUUID().toString().replaceAll("-", "_")); return new LocationHandle(targetPath, targetPath, TEMPORARY, DIRECT_TO_TARGET_NEW_DIRECTORY); }
Source:
private static Rule toRule(RuleDefinitionDto ruleDefinition, List<RuleParamDto> params) { String severity = ruleDefinition.getSeverityString(); String description = ruleDefinition.getDescription(); RuleDto.Format descriptionFormat = ruleDefinition.getDescriptionFormat(); Rule apiRule = new Rule(); apiRule .setName(ruleDefinition.getName()) .setLanguage(ruleDefinition.getLanguage()) .setKey(ruleDefinition.getRuleKey()) .setConfigKey(ruleDefinition.getConfigKey()) .setIsTemplate(ruleDefinition.isTemplate()) .setCreatedAt(new Date(ruleDefinition.getCreatedAt())) .setUpdatedAt(new Date(ruleDefinition.getUpdatedAt())) .setRepositoryKey(ruleDefinition.getRepositoryKey()) .setSeverity(severity != null ? RulePriority.valueOf(severity) : null) .setStatus(ruleDefinition.getStatus().name()) .setSystemTags(ruleDefinition.getSystemTags().toArray(new String[ruleDefinition.getSystemTags().size()])) .setTags(new String[0]) .setId(ruleDefinition.getId()); if (description != null && descriptionFormat != null) { if (RuleDto.Format.HTML.equals(descriptionFormat)) { apiRule.setDescription(description); } else { apiRule.setDescription(Markdown.convertToHtml(description)); } } List<org.sonar.api.rules.RuleParam> apiParams = newArrayList(); for (RuleParamDto param : params) { apiParams.add(new org.sonar.api.rules.RuleParam(apiRule, param.getName(), param.getDescription(), param.getType()) .setDefaultValue(param.getDefaultValue())); } apiRule.setParams(apiParams); return apiRule; }

Target:
private static Rule toRule(RuleDefinitionDto ruleDefinition, List<RuleParamDto> params) { String severity = ruleDefinition.getSeverityString(); String description = ruleDefinition.getDescription(); RuleDto.Format descriptionFormat = ruleDefinition.getDescriptionFormat(); Rule apiRule = new Rule(); String[] systemTags = ruleDefinition.getSystemTags().toArray(new String[ruleDefinition.getSystemTags().size()]); apiRule .setName(ruleDefinition.getName()) .setLanguage(ruleDefinition.getLanguage()) .setKey(ruleDefinition.getRuleKey()) .setConfigKey(ruleDefinition.getConfigKey()) .setIsTemplate(ruleDefinition.isTemplate()) .setCreatedAt(new Date(ruleDefinition.getCreatedAt())) .setUpdatedAt(new Date(ruleDefinition.getUpdatedAt())) .setRepositoryKey(ruleDefinition.getRepositoryKey()) .setSeverity(severity != null ? RulePriority.valueOf(severity) : null) .setStatus(ruleDefinition.getStatus().name()) .setSystemTags(systemTags) .setTags(systemTags) .setId(ruleDefinition.getId()); if (description != null && descriptionFormat != null) { if (RuleDto.Format.HTML.equals(descriptionFormat)) { apiRule.setDescription(description); } else { apiRule.setDescription(Markdown.convertToHtml(description)); } } List<org.sonar.api.rules.RuleParam> apiParams = newArrayList(); for (RuleParamDto param : params) { apiParams.add(new org.sonar.api.rules.RuleParam(apiRule, param.getName(), param.getDescription(), param.getType()) .setDefaultValue(param.getDefaultValue())); } apiRule.setParams(apiParams); return apiRule; }