auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void run() { Column column = _project.columnModel.getColumnByName(_baseColumnName); if (column == null) { _project.processManager.onFailedProcess(this, new Exception("No column named " + _baseColumnName)); return; } if (_project.columnModel.getColumnByName(_newColumnName) != null) { _project.processManager.onFailedProcess(this, new Exception("Another column already named " + _newColumnName)); return; } List<CellAtRow> urls = new ArrayList<CellAtRow>(_project.rows.size()); FilteredRows filteredRows = _engine.getAllFilteredRows(); filteredRows.accept(_project, createRowVisitor(urls)); List<CellAtRow> responseBodies = new ArrayList<CellAtRow>(urls.size()); for (int i = 0; i < urls.size(); i++) { CellAtRow urlData = urls.get(i); CellAtRow cellAtRow = cachedFetch(urlData); if (cellAtRow != null) { responseBodies.add(cellAtRow); } _progress = i * 100 / urls.size(); if (_canceled) { break; } } <START> _urlCache.clear(); <END> if (!_canceled) { HistoryEntry historyEntry = new HistoryEntry( _historyEntryID, _project, _description, ColumnAdditionByFetchingURLsOperation.this, new ColumnAdditionChange( _newColumnName, _columnInsertIndex, responseBodies) ); _project.history.addEntry(historyEntry); _project.processManager.onDoneProcess(this); } }</code><technical_language>clear() shrink HashMap. [WeakHashMap](<LINK_0> in this case. entry in a WeakHashMap automatically removed key is longer in ordinary use</technical_language>

Target:
public void run() { Column column = _project.columnModel.getColumnByName(_baseColumnName); if (column == null) { _project.processManager.onFailedProcess(this, new Exception("No column named " + _baseColumnName)); return; } if (_project.columnModel.getColumnByName(_newColumnName) != null) { _project.processManager.onFailedProcess(this, new Exception("Another column already named " + _newColumnName)); return; } List<CellAtRow> urls = new ArrayList<CellAtRow>(_project.rows.size()); FilteredRows filteredRows = _engine.getAllFilteredRows(); filteredRows.accept(_project, createRowVisitor(urls)); List<CellAtRow> responseBodies = new ArrayList<CellAtRow>(urls.size()); for (int i = 0; i < urls.size(); i++) { CellAtRow urlData = urls.get(i); String urlString = urlData.cell.value.toString(); Serializable response = null; if (_urlCache != null) { response = cachedFetch(urlString); } else { response = fetch(urlString); } if (response != null) { CellAtRow cellAtRow = new CellAtRow( urlData.row, new Cell(response, null)); responseBodies.add(cellAtRow); } _progress = i * 100 / urls.size(); if (_canceled) { break; } } if (!_canceled) { HistoryEntry historyEntry = new HistoryEntry( _historyEntryID, _project, _description, ColumnAdditionByFetchingURLsOperation.this, new ColumnAdditionChange( _newColumnName, _columnInsertIndex, responseBodies) ); _project.history.addEntry(historyEntry); _project.processManager.onDoneProcess(this); } }
Source:
<code>private List<String> revList(ObjectId initialObjectId) throws IOException { ArrayList<String> revs = new ArrayList<>(); Repository repo = git.getRepository(); try (RevWalk walk = new RevWalk(repo)) { walk.setRetainBody(false); RevCommit head = walk.parseCommit(initialObjectId); while (true) { revs.add(head.getName()); RevCommit[] parents = head.getParents(); if (parents == null || parents.length == 0) { break; } head = walk.parseCommit(parents[0]); } <START> walk.close(); <END> } return revs; }</code><technical_language>this is necessary, try-with-resources block call walk.close() automatically</technical_language>

Target:
private List<String> revList(ObjectId initialObjectId) throws IOException { ArrayList<String> revs = new ArrayList<>(); Repository repo = git.getRepository(); try (RevWalk walk = new RevWalk(repo)) { walk.setRetainBody(false); RevCommit head = walk.parseCommit(initialObjectId); while (true) { revs.add(head.getName()); RevCommit[] parents = head.getParents(); if (parents == null || parents.length == 0) { break; } head = walk.parseCommit(parents[0]); } } return revs; }
Source:
<code>public Object[] deserialize(InputStream inputStream, ResourceMethod method) { Method jMethod = method.getMethod(); Class<?>[] types = jMethod.getParameterTypes(); if (types.length == 0) { throw new IllegalArgumentException( "Methods that consumes representations must receive just one argument"); } Gson gson = getGson(); Object[] params = new Object[types.length]; String[] parameterNames = paramNameProvider.parameterNamesFor(jMethod); try { String content = getContentOfStream(inputStream); <START> if(content.trim().equals("")) { <END> logger.debug("json with no content"); return params; } logger.debug("json retrieved: {}", content); JsonParser parser = new JsonParser(); JsonObject root = (JsonObject) parser.parse(content); for (int i = 0; i < types.length; i++) { String name = parameterNames[i]; JsonElement node = root.get(name); if (isWithoutRoot(types, node)) { params[i] = gson.fromJson(root, types[i]); logger.info("json without root deserialized"); } else if(node != null){ params[i] = gson.fromJson(node, types[i]); } logger.debug("json deserialized: {}", params[i]); } } catch (Exception e) { throw new ResultException("Unable to deserialize data", e); } return params; }</code><technical_language><code>Strings.isNullOrEmpty</code> is more efficient equals another String</technical_language>

Target:
public Object[] deserialize(InputStream inputStream, ResourceMethod method) { Method jMethod = method.getMethod(); Class<?>[] types = jMethod.getParameterTypes(); if (types.length == 0) { throw new IllegalArgumentException( "Methods that consumes representations must receive just one argument"); } Gson gson = getGson(); Object[] params = new Object[types.length]; String[] parameterNames = paramNameProvider.parameterNamesFor(jMethod); try { String content = getContentOfStream(inputStream); if(Strings.isNullOrEmpty(content)) { logger.debug("json with no content"); return params; } logger.debug("json retrieved: {}", content); JsonParser parser = new JsonParser(); JsonObject root = (JsonObject) parser.parse(content); for (int i = 0; i < types.length; i++) { String name = parameterNames[i]; JsonElement node = root.get(name); if (isWithoutRoot(types, node)) { params[i] = gson.fromJson(root, types[i]); logger.info("json without root deserialized"); } else if(node != null){ params[i] = gson.fromJson(node, types[i]); } logger.debug("json deserialized: {}", params[i]); } } catch (Exception e) { throw new ResultException("Unable to deserialize data", e); } return params; }
Source:
<code>private Properties buildExpectedProperties(String expectedDDLSerialization, HiveColumnHandle... expectedColumns) { <START> final String expectedColumnsType = getTypes(expectedColumns); <END> final String expectedColumnsName = getName(expectedColumns); Properties propExpected = new Properties(); propExpected.put(LIST_COLUMNS, expectedColumnsName); propExpected.put(SERIALIZATION_LIB, APACHE_HADOOP_HIVE); propExpected.put(SERIALIZATION_DDL, expectedDDLSerialization); propExpected.put(LIST_COLUMN_TYPES, expectedColumnsType); return propExpected; }</code><technical_language>In general mark local variables final in Presto source code</technical_language>

Target:
private Properties buildExpectedProperties(String expectedDDLSerialization, HiveColumnHandle... expectedColumns) { String expectedColumnsType = getTypes(expectedColumns); String expectedColumnsName = getName(expectedColumns); Properties propExpected = new Properties(); propExpected.put(LIST_COLUMNS, expectedColumnsName); propExpected.put(SERIALIZATION_LIB, LAZY_SERDE_CLASS_NAME); propExpected.put(SERIALIZATION_DDL, expectedDDLSerialization); propExpected.put(LIST_COLUMN_TYPES, expectedColumnsType); return propExpected; }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scratch_converter); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); setUpActionBar(); getSearchFragment().setDataFetcher(dataFetcher); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); <START> final long clientID = settings.getLong(Constants.SCRATCH_CONVERTER_CLIENT_ID_SHARED_PREFERENCE_NAME, <END> Client.INVALID_CLIENT_ID); if (client == null) { client = new WebSocketClient(clientID, new WebSocketMessageListener()); } conversionManager = new ScratchConversionManager(this, client, false); conversionManager.setCurrentActivity(this); conversionManager.addGlobalDownloadCallback(getSlidingUpFragment()); conversionManager.addBaseInfoViewListener(getSlidingUpFragment()); conversionManager.addGlobalJobViewListener(getSlidingUpFragment()); getSearchFragment().setConversionManager(conversionManager); slidingLayout = findViewById(R.id.sliding_layout); slidingLayout.addPanelSlideListener(this); hideSlideUpPanelBar(); }</code><technical_language>this final</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scratch_converter); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); String scratchConverter = getString(R.string.main_menu_scratch_converter); SpannableString scratchConverterBeta = new SpannableString(scratchConverter + " " + getString(R.string.beta)); scratchConverterBeta.setSpan( new ForegroundColorSpan( getResources().getColor(R.color.beta_label_color)), scratchConverter.length(), scratchConverterBeta.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); getSupportActionBar().setTitle(scratchConverterBeta); getSearchFragment().setDataFetcher(dataFetcher); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); long clientID = settings.getLong(Constants.SCRATCH_CONVERTER_CLIENT_ID_SHARED_PREFERENCE_NAME, Client.INVALID_CLIENT_ID); client = new WebSocketClient(clientID, new WebSocketMessageListener()); conversionManager = new ScratchConversionManager(this, client, false); conversionManager.setCurrentActivity(this); conversionManager.addGlobalDownloadCallback(getSlidingUpFragment()); conversionManager.addBaseInfoViewListener(getSlidingUpFragment()); conversionManager.addGlobalJobViewListener(getSlidingUpFragment()); getSearchFragment().setConversionManager(conversionManager); slidingLayout = findViewById(R.id.sliding_layout); slidingLayout.addPanelSlideListener(this); hideSlideUpPanelBar(); }
Source:
<code>public void testGetLocation() { <START> setUp(); <END> CtfLocationInfo location = fixture.getLocationInfo(); long result = location.getTimestamp(); assertEquals(1L, result); }</code><technical_language>need call setUp()</technical_language>

Target:
public void testGetLocation() { CtfLocationInfo location = fixture.getLocationInfo(); long result = location.getTimestamp(); assertEquals(1337L, result); }
Source:
<code>public List<String> getEurekaServerServiceUrls(String myZone) { String serviceUrls = this.serviceUrl.get(myZone); if (serviceUrls == null || serviceUrls.isEmpty()) { serviceUrls = this.serviceUrl.get(DEFAULT_ZONE); } if (!StringUtils.isEmpty(serviceUrls)) { <START> final String[] serviceUrlsSplit = serviceUrls.split(","); <END> List<String> eurekaServiceUrls = new ArrayList<>(serviceUrlsSplit.length); for (String eurekaServiceUrl : serviceUrlsSplit) { if (!endsWithSlash(eurekaServiceUrl)) { eurekaServiceUrl += "/"; } eurekaServiceUrls.add(eurekaServiceUrl); } return eurekaServiceUrls; } return new ArrayList<>(); }</code><technical_language>StringUtils.commaDelimitedListToStringArray here</technical_language>

Target:
public List<String> getEurekaServerServiceUrls(String myZone) { String serviceUrls = this.serviceUrl.get(myZone); if (serviceUrls == null || serviceUrls.isEmpty()) { serviceUrls = this.serviceUrl.get(DEFAULT_ZONE); } if (!StringUtils.isEmpty(serviceUrls)) { final String[] serviceUrlsSplit = StringUtils.commaDelimitedListToStringArray(serviceUrls); List<String> eurekaServiceUrls = new ArrayList<>(serviceUrlsSplit.length); for (String eurekaServiceUrl : serviceUrlsSplit) { if (!endsWithSlash(eurekaServiceUrl)) { eurekaServiceUrl += "/"; } eurekaServiceUrls.add(eurekaServiceUrl); } return eurekaServiceUrls; } return new ArrayList<>(); }
Source:
<code>public FileStructureView(NodeFactory nodeFactory) { this.nodeFactory = nodeFactory; NodeStorage storage = new NodeStorage( <START> new NodeUniqueKeyProvider() { <END> @Override public String getKey(@NotNull Node item) { return String.valueOf(item.hashCode()); } }); NodeLoader loader = new NodeLoader(Collections.<NodeInterceptor>emptySet()); tree = new FileStructureTree(storage, loader); UI_BINDER.createAndBindUi(this); tree.setAutoExpand(false); tree.getSelectionModel().setSelectionMode(SINGLE); }</code><technical_language>changed lambda</technical_language>

Target:
public FileStructureView(NodeFactory nodeFactory) { this.nodeFactory = nodeFactory; NodeStorage storage = new NodeStorage(item->String.valueOf(item.hashCode())); NodeLoader loader = new NodeLoader(Collections.<NodeInterceptor>emptySet()); tree = new FileStructureTree(storage, loader); UI_BINDER.createAndBindUi(this); tree.setAutoExpand(false); tree.getSelectionModel().setSelectionMode(SINGLE); }
Source:
<code>private static int getGeometryType( long firstBlock ) <START> { <END> return (int) ((firstBlock & 0x00000000F0000000L) >> 28); }</code><technical_language>need do +1 in loop do iteration 1 <= dimension</technical_language>

Target:
private static int getGeometryType( long firstBlock ) { return (int) ((firstBlock & GEOMETRY_TYPE_MASK) >> 28); }
Source:
<code>public Set<DataSegment> perform(Task task, TaskActionToolbox toolbox) throws IOException { if(!toolbox.taskLockCoversSegments(task, segments, false)) { throw new ISE("Segments not covered by locks for task[%s]: %s", task.getId(), segments); } final Set<DataSegment> retVal = toolbox.getMergerDBCoordinator().announceHistoricalSegments(segments); final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder() .setUser2(task.getDataSource()) .setUser4(task.getType()); for (DataSegment segment : segments) { metricBuilder.setUser5(segment.getInterval().toString()); <START> toolbox.getEmitter().emit(metricBuilder.build("indexer/segment/bytes", segment.getSize())); <END> } return retVal; }</code><technical_language>I _think_ this get run twice. Indexer local worker. True false</technical_language>

Target:
public Set<DataSegment> perform(Task task, TaskActionToolbox toolbox) throws IOException { if(!toolbox.taskLockCoversSegments(task, segments, allowOlderVersions)) { throw new ISE("Segments not covered by locks for task[%s]: %s", task.getId(), segments); } final Set<DataSegment> retVal = toolbox.getMergerDBCoordinator().announceHistoricalSegments(segments); final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder() .setUser2(task.getDataSource()) .setUser4(task.getType()); for (DataSegment segment : segments) { metricBuilder.setUser5(segment.getInterval().toString()); toolbox.getEmitter().emit(metricBuilder.build("indexer/segment/bytes", segment.getSize())); } return retVal; }
Source:
<code>public void getConfigFormWithTimeout() throws XMPPException, InterruptedException { ThreadedDummyConnection con = new ThreadedDummyConnection(); PubSubManager mgr = new PubSubManager(con, PubSubManagerTest.DUMMY_PUBSUB_SERVICE); DiscoverInfoBuilder info = DiscoverInfo.builder("disco-result"); Identity ident = new Identity("pubsub", null, "leaf"); info.addIdentity(ident); DiscoverInfo discoverInfo = info.build(); con.addIQReply(discoverInfo); <START> assertThrows(Exception.class, () -> { <END> Node node = mgr.getNode("princely_musings"); SmackConfiguration.setDefaultReplyTimeout(100); con.setTimeout(); node.getNodeConfiguration(); }); }</code><technical_language>SmackException is expected thrown here. getNodeConfiguration() assume, lambda smaller</technical_language>

Target:
public void getConfigFormWithTimeout() throws XMPPException, InterruptedException { ThreadedDummyConnection con = new ThreadedDummyConnection(); PubSubManager mgr = new PubSubManager(con, PubSubManagerTest.DUMMY_PUBSUB_SERVICE); DiscoverInfoBuilder info = DiscoverInfo.builder("disco-result"); Identity ident = new Identity("pubsub", null, "leaf"); info.addIdentity(ident); DiscoverInfo discoverInfo = info.build(); con.addIQReply(discoverInfo); assertThrows(SmackException.class, () -> { Node node = mgr.getNode("princely_musings"); SmackConfiguration.setDefaultReplyTimeout(100); con.setTimeout(); node.getNodeConfiguration(); }); }
Source:
<code><START> protected Stream<ScheduledJob> allJobsWithOnAnnotation() { <END> return Arrays.stream(this.jobs) .filter(job -> job.getClass().isAnnotationPresent(On.class)) .map(job -> { Class<? extends Job> clazz = job.getClass(); On onAnnotation = clazz.getAnnotation(On.class); String cron = onAnnotation.value(); if (cron.isEmpty() || cron.matches("\\$\\{.*\\}")) { cron = readDurationFromConfig(onAnnotation, clazz, configuration); log.info(clazz + " is configured in the config file to run every " + cron); } int priority = onAnnotation.priority(); On.MisfirePolicy misfirePolicy = onAnnotation.misfirePolicy(); boolean requestRecovery = onAnnotation.requestRecovery(); boolean storeDurably = onAnnotation.storeDurably(); CronScheduleBuilder scheduleBuilder = createCronScheduleBuilder(cron); String timeZoneStr = onAnnotation.timeZone(); if (StringUtils.isNotBlank(timeZoneStr)) { TimeZone timeZone = TimeZone.getTimeZone(ZoneId.of(timeZoneStr)); scheduleBuilder = scheduleBuilder.inTimeZone(timeZone); } if (misfirePolicy == On.MisfirePolicy.IGNORE_MISFIRES) scheduleBuilder.withMisfireHandlingInstructionIgnoreMisfires(); else if (misfirePolicy == On.MisfirePolicy.DO_NOTHING) scheduleBuilder.withMisfireHandlingInstructionDoNothing(); else if (misfirePolicy == On.MisfirePolicy.FIRE_AND_PROCEED) scheduleBuilder.withMisfireHandlingInstructionFireAndProceed(); Trigger trigger = TriggerBuilder.newTrigger().withSchedule(scheduleBuilder).withPriority(priority).build(); JobKey jobKey = createJobKey(onAnnotation.jobName(), job); String message = String.format(" %-21s %s", cron, jobKey.toString()); ScheduledJob scheduledJob = new ScheduledJob(jobKey, clazz, trigger, requestRecovery, storeDurably, message); return scheduledJob; }); }</code><technical_language>Method allJobsWithOnAnnotation 32 lines of code (exceeds 25 allowed). Consider refactoring</technical_language>

Target:
protected Stream<ScheduledJob> allJobsWithOnAnnotation() { return Arrays.stream(this.jobs) .filter(job -> job.getClass().isAnnotationPresent(On.class)) .map(job -> { Class<? extends Job> clazz = job.getClass(); On onAnnotation = clazz.getAnnotation(On.class); String cron = onAnnotation.value(); if (cron.isEmpty() || cron.matches("\\$\\{.*\\}")) { cron = readDurationFromConfig(onAnnotation, clazz, configuration); log.info(clazz + " is configured in the config file to run every " + cron); } boolean requestRecovery = onAnnotation.requestRecovery(); boolean storeDurably = onAnnotation.storeDurably(); CronScheduleBuilder scheduleBuilder = createCronScheduleBuilder(cron); String timeZoneStr = onAnnotation.timeZone(); applyTimezone(timeZoneStr, scheduleBuilder); On.MisfirePolicy misfirePolicy = onAnnotation.misfirePolicy(); applyMisfirePolicy(misfirePolicy, scheduleBuilder); int priority = onAnnotation.priority(); Trigger trigger = TriggerBuilder.newTrigger() .withSchedule(scheduleBuilder) .withPriority(priority) .build(); JobKey jobKey = createJobKey(onAnnotation.jobName(), job); String message = String.format(" %-21s %s", cron, jobKey.toString()); return new ScheduledJob(jobKey, clazz, trigger, requestRecovery, storeDurably, message); }); }
Source:
<code>public LabeledText(ReferencedComposite referencedComposite, String label) { <START> super(referencedComposite, 0, new WithLabelMatcher(new RegexMatcher(label + "\\s*\\**"))); <END> }</code><technical_language>I wouldnt regex matcher this in this way. if a label contains a special char... matched properly</technical_language>

Target:
public LabeledText(ReferencedComposite referencedComposite, String label) { super(referencedComposite, 0, new WithLabelMatcher(label)); }
Source:
<code>protected void onPostExecute(final ArrayList<Theme> result) { runOnUiThread(new Runnable() { @Override public void run() { mFetchingThemes = false; if (mThemeBrowserFragment.isVisible()) { <START> mThemeBrowserFragment.mEmptyView.setText("No themes"); <END> mThemeBrowserFragment.setRefreshing(false); } else if (mThemeSearchFragment.isVisible()) { mThemeSearchFragment.mEmptyView.setText("No themes"); mThemeSearchFragment.setRefreshing(false); } } }); }</code><technical_language>Hardcoded string (+1 more below)</technical_language>

Target:
protected void onPostExecute(final ArrayList<Theme> result) { runOnUiThread(new Runnable() { @Override public void run() { mFetchingThemes = false; if (mThemeBrowserFragment != null && mThemeBrowserFragment.isVisible()) { mThemeBrowserFragment.mEmptyView.setText(R.string.no_themes); mThemeBrowserFragment.setRefreshing(false); } else if (mThemeSearchFragment != null && mThemeSearchFragment.isVisible()) { mThemeSearchFragment.mEmptyView.setText(R.string.no_themes); mThemeSearchFragment.setRefreshing(false); } } }); }
Source:
<code>private void doSaveElementState(TreePath parentPath, ModelDelta delta, VirtualItem item, Collection<VirtualItem> set, int flagsToSave) { Object element = item.getData(); if (element != null) { boolean expanded = item.getExpanded(); boolean selected = set.contains(item); int flags = IModelDelta.NO_CHANGE; if (expanded && (flagsToSave & IModelDelta.EXPAND) != 0) { flags = flags | IModelDelta.EXPAND; } if (!expanded && (flagsToSave & IModelDelta.COLLAPSE) != 0 && item.hasItems()){ flags = flags | IModelDelta.COLLAPSE; } if (selected && (flagsToSave & IModelDelta.SELECT) != 0) { flags = flags | IModelDelta.SELECT; } if (expanded || flags != IModelDelta.NO_CHANGE) { int modelIndex = ((TreeModelContentProvider)getContentProvider()).viewToModelIndex(parentPath, item.getIndex().intValue()); TreePath elementPath = parentPath.createChildPath(element); int numChildren = ((TreeModelContentProvider)getContentProvider()).viewToModelCount(elementPath, item.getItemCount()); ModelDelta childDelta = delta.addNode(element, modelIndex, flags, numChildren); if (expanded) { for (VirtualItem <START> item2 : <END> item.getItems()) { doSaveElementState(elementPath, childDelta, item2, set, flagsToSave); } } } } }</code><technical_language>rename childItem</technical_language>

Target:
private void doSaveElementState(TreePath parentPath, ModelDelta delta, VirtualItem item, Collection<VirtualItem> set, int flagsToSave) { Object element = item.getData(); if (element != null) { boolean expanded = item.getExpanded(); boolean selected = set.contains(item); int flags = IModelDelta.NO_CHANGE; if (expanded && (flagsToSave & IModelDelta.EXPAND) != 0) { flags = flags | IModelDelta.EXPAND; } if (!expanded && (flagsToSave & IModelDelta.COLLAPSE) != 0 && item.hasItems()){ flags = flags | IModelDelta.COLLAPSE; } if (selected && (flagsToSave & IModelDelta.SELECT) != 0) { flags = flags | IModelDelta.SELECT; } if (expanded || flags != IModelDelta.NO_CHANGE) { int modelIndex = ((TreeModelContentProvider)getContentProvider()).viewToModelIndex(parentPath, item.getIndex().intValue()); TreePath elementPath = parentPath.createChildPath(element); int numChildren = ((TreeModelContentProvider)getContentProvider()).viewToModelCount(elementPath, item.getItemCount()); ModelDelta childDelta = delta.addNode(element, modelIndex, flags, numChildren); if (expanded) { for (VirtualItem childItem : item.getItems()) { doSaveElementState(elementPath, childDelta, childItem, set, flagsToSave); } } } } }
Source:
<code>private static int getZoneNumber(final double lat, final double lon) { int zoneNumber = (int) ((lon + 180) / 6) + 1; if (lon == 180) { <START> zoneNumber = 60; <END> } if (lat >= 56.0f && lat < 64.0f && lon >= 3.0f && lon < 12.0f) { zoneNumber = 32; } if (lat >= 72.0f && lat < 84.0f) { if (lon >= 0.0f && lon < 9.0f) { zoneNumber = 31; } else if (lon >= 9.0f && lon < 21.0f) { zoneNumber = 33; } else if (lon >= 21.0f && lon < 33.0f) { zoneNumber = 35; } else if (lon >= 33.0f && lon < 42.0f) { zoneNumber = 37; } } return zoneNumber; }</code><technical_language>early return constructs instead of zoneNumber =</technical_language>

Target:
private static int getZoneNumber(final double lat, final double lon) { if (lon == 180) { return 60; } if (lat >= 56.0f && lat < 64.0f && lon >= 3.0f && lon < 12.0f) { return 32; } if (lat >= 72.0f && lat < 84.0f) { if (lon >= 0.0f && lon < 9.0f) { return 31; } else if (lon >= 9.0f && lon < 21.0f) { return 33; } else if (lon >= 21.0f && lon < 33.0f) { return 35; } else if (lon >= 33.0f && lon < 42.0f) { return 37; } } return (int) ((lon + 180) / 6) + 1; }
Source:
<code>public boolean isSameAsTlv(Tlv tlv){ return oui.equals(tlv.getOui()) && <START> subType.equals(tlv.getSubtype()); <END> }</code><technical_language>Is this purpose of this class</technical_language>

Target:
public boolean isSameAsTlv(Tlv tlv){ if (type < 127) { return type == tlv.getType(); } else if (type == 127) { return oui.equals(tlv.getOui()) && subType.equals(tlv.getSubtype()); } return false; }
Source:
<code>private void validateTestEnvId(TestEnvironmentEntity testEnv) { String envId = testEnv.getEnvironmentId(); <START> Pattern envIdPattern = Pattern.compile("^[a-zA-Z0-9\\._\\-]{1,249}$"); <END> Matcher matcher = envIdPattern.matcher(envId); if (!matcher.matches()) throw new TestEnvironmentInvalidIdException(envId, envIdPattern); }</code><technical_language>cached</technical_language>

Target:
private void validateTestEnvId(TestEnvironmentEntity testEnv) { String envId = testEnv.getEnvironmentId(); Pattern envIdPattern = Pattern.compile(ENV_ID_PATTERN); Matcher matcher = envIdPattern.matcher(envId); if (!matcher.matches()) throw new TestEnvironmentInvalidIdException(envId, envIdPattern); }
Source:
<code><START> public static KafkaSemantic getSinkSemantic(String semantic){ <END> switch (semantic){ case SINK_SEMANTIC_VALUE_EXACTLY_ONCE: return EXACTLY_ONCE; case SINK_SEMANTIC_VALUE_AT_LEAST_ONCE: return AT_LEAST_ONCE; case SINK_SEMANTIC_VALUE_NONE: return NONE; default: throw new TableException("Validator should have checked that"); } }</code><technical_language>SinkSemantic KafkaSinkSemantic? confusing works for source</technical_language>

Target:
public static KafkaSinkSemantic getSinkSemantic(String semantic){ switch (semantic){ case SINK_SEMANTIC_VALUE_EXACTLY_ONCE: return EXACTLY_ONCE; case SINK_SEMANTIC_VALUE_AT_LEAST_ONCE: return AT_LEAST_ONCE; case SINK_SEMANTIC_VALUE_NONE: return NONE; default: throw new TableException("Validator should have checked that"); } }
Source:
<code>public SingleResultView findByPrimaryKey(@PathParam("primaryKey") String key, @PathParam("primaryKeyValue") String value) { String registerPrimaryKey = requestContext.getRegisterPrimaryKey(); if (key.equals(registerPrimaryKey)) { Optional<DbRecord> record = queryDAO.findByKeyValue(key, value); if (record.isPresent()) { <START> setResponseHeader(key, value); <END> return viewFactory.getSingleResultView(record.get()); } } throw new NotFoundException(); }</code><technical_language>this method name is unclear</technical_language>

Target:
public SingleResultView findByPrimaryKey(@PathParam("primaryKey") String key, @PathParam("primaryKeyValue") String value) { String registerPrimaryKey = requestContext.getRegisterPrimaryKey(); if (key.equals(registerPrimaryKey)) { Optional<DbRecord> record = queryDAO.findByKeyValue(key, value); if (record.isPresent()) { setVersionHistoryLinkHeader(key, value); return viewFactory.getSingleResultView(record.get()); } } throw new NotFoundException(); }
Source:
<code>private boolean validateReceivedSuspectedMembers(MemberImpl sender, Collection<MemberInfo> suspectedMemberInfos) { if (!partialDisconnectionDetectionEnabled) { return false; } else if (!clusterService.isMaster()) { if (suspectedMemberInfos.size() > 0) { <START> logger.severe("This not is not master but received suspected members: " + suspectedMemberInfos + " from " <END> + sender); } return false; } else if (getLocalMember().equals(sender)) { logger.severe("Received suspected members: " + suspectedMemberInfos + " from itself."); return false; } else if (suspectedMemberInfos.contains(new MemberInfo(getLocalMember()))) { logger.severe("Received suspected members: " + suspectedMemberInfos + " from " + sender + " contains this member!"); return false; } else if (clusterService.getClusterJoinManager().isMastershipClaimInProgress()) { if (suspectedMemberInfos.size() > 0 && logger.isFineEnabled()) { logger.warning("Ignoring received suspected members: " + suspectedMemberInfos + " from " + sender + " because mastership claim is in progress..."); } return false; } return true; }</code><technical_language>severe logs, log warning</technical_language>

Target:
private boolean validateReceivedSuspectedMembers(MemberImpl sender, Collection<MemberInfo> suspectedMemberInfos) { if (!partialDisconnectionDetectionEnabled) { return false; } else if (!clusterService.isMaster()) { if (suspectedMemberInfos.size() > 0) { logger.warning("This not is not master but received suspected members: " + suspectedMemberInfos + " from " + sender); } return false; } else if (getLocalMember().equals(sender)) { logger.warning("Received suspected members: " + suspectedMemberInfos + " from itself."); return false; } else if (suspectedMemberInfos.contains(new MemberInfo(getLocalMember()))) { logger.warning("Received suspected members: " + suspectedMemberInfos + " from " + sender + " contains this member!"); return false; } else if (clusterService.getClusterJoinManager().isMastershipClaimInProgress()) { if (suspectedMemberInfos.size() > 0 && logger.isFineEnabled()) { logger.warning("Ignoring received suspected members: " + suspectedMemberInfos + " from " + sender + " because mastership claim is in progress..."); } return false; } return true; }
Source:
<code>public void init() throws XPathExpressionException, RemoteException, UserAdminUserAdminException { super.init(TestUserMode.SUPER_TENANT_USER); AndesClientUtils.sleepForInterval(15000); <START> defaultAndesAckWaitTimeOut = System.getProperty("AndesAckWaitTimeOut"); <END> System.setProperty("AndesAckWaitTimeOut", "0"); }</code><technical_language>set this string a pre-defined constant ? everywhere. Easier maintain if define system properties in test cases in a single place</technical_language>

Target:
public void init() throws XPathExpressionException, RemoteException, UserAdminUserAdminException { super.init(TestUserMode.SUPER_TENANT_USER); AndesClientUtils.sleepForInterval(15000); defaultAndesAckWaitTimeOut = System.getProperty(AndesClientConstants. ANDES_ACK_WAIT_TIMEOUT_PROPERTY); System.setProperty(AndesClientConstants.ANDES_ACK_WAIT_TIMEOUT_PROPERTY, "0"); }
Source:
<code>public void getSubItems(Item item, CreativeTabs tab, List list) { super.getSubItems(item, tab, list); for (Fluid fluid : FluidRegistry.getRegisteredFluids().values()) { if (fluid != null) list.add( <START> getFilledItemStack(new FluidStack(fluid, getCapacity()))); <END> } }</code><technical_language>fix formatting please</technical_language>

Target:
public void getSubItems(Item item, CreativeTabs tab, List list) { super.getSubItems(item, tab, list); for (Fluid fluid : FluidRegistry.getRegisteredFluids().values()) if (fluid != null) list.add(getFilledItemStack(new FluidStack(fluid, getCapacity()))); }
Source:
<code>public void setup() { <START> mockitoSession = Mockito.mockitoSession().initMocks(this).strictness(Strictness.STRICT_STUBS).startMocking(); <END> EventLogManager eventLogManager = new EventLogManagerImpl(); PersistentUUIDManager persistentUUIDManager = new PersistentUUIDManagerImpl(); EmbeddedCacheManager cacheManager = mock(EmbeddedCacheManager.class); topologyManager = mock(ClusterTopologyManager.class); transport = mock(Transport.class); PreferAvailabilityStrategy availabilityStrategy = new PreferAvailabilityStrategy(eventLogManager, persistentUUIDManager, ClusterTopologyManagerImpl::distLostDataCheck); status = new ClusterCacheStatus(cacheManager, CACHE_NAME, availabilityStrategy, RebalanceType.FOUR_PHASE, topologyManager, transport, Optional.empty(), persistentUUIDManager, false); }</code><technical_language>this one. I fields annotated @Mock for initMocks</technical_language>

Target:
public void setup() { mockitoSession = Mockito.mockitoSession().strictness(Strictness.STRICT_STUBS).startMocking(); EventLogManager eventLogManager = new EventLogManagerImpl(); PersistentUUIDManager persistentUUIDManager = new PersistentUUIDManagerImpl(); EmbeddedCacheManager cacheManager = mock(EmbeddedCacheManager.class); topologyManager = mock(ClusterTopologyManager.class); transport = mock(Transport.class); PreferAvailabilityStrategy availabilityStrategy = new PreferAvailabilityStrategy(eventLogManager, persistentUUIDManager, ClusterTopologyManagerImpl::distLostDataCheck); status = new ClusterCacheStatus(cacheManager, CACHE_NAME, availabilityStrategy, RebalanceType.FOUR_PHASE, topologyManager, transport, Optional.empty(), persistentUUIDManager, false); }
Source:
<code>public void validate(Object obj, Errors errors) { Obs obs = (Obs) obj; if (obs == null) { throw new APIException("Obs can't be null"); } else if (obs.getVoided()) { return; } List<Obs> ancestors = new ArrayList<>(); validateHelper(obs, errors, ancestors, true); ValidateUtil.validateFieldLengths(errors, obj.getClass(), "accessionNumber", "valueModifier", "valueComplex", "comment", "voidReason"); try { Encounter encounter = obs.getEncounter(); Patient patient = encounter.getPatient(); if(obs.getPerson() != patient){ throw new ValidationException("Obs.error.patient.id.mismatch"); } <START> }catch (Exception e){ <END> } }</code><technical_language>want log exception</technical_language>

Target:
public void validate(Object obj, Errors errors) { Obs obs = (Obs) obj; if (obs == null) { throw new APIException("Obs can't be null"); } else if (obs.getVoided()) { return; } List<Obs> ancestors = new ArrayList<>(); validateHelper(obs, errors, ancestors, true); ValidateUtil.validateFieldLengths(errors, obj.getClass(), "accessionNumber", "valueModifier", "valueComplex", "comment", "voidReason"); try { Encounter encounter = obs.getEncounter(); Patient patient = encounter.getPatient(); if (obs.getPerson() != patient){ throw new ValidationException("Obs.error.patient.id.mismatch"); } }catch (Exception ex){ log.error("Data contains null values",ex); } }
Source:
<code>public DocumentMetadataAvroTruncator build() { DocumentMetadataAvroTruncator instance = new DocumentMetadataAvroTruncator(); <START> if (Objects.nonNull(maxAbstractLength)) { <END> instance.abstractTruncator = new AbstractTruncator(maxAbstractLength); } if (Objects.nonNull(maxTitleLength)) { instance.titleTruncator = new TitleTruncator(maxTitleLength); } if (Objects.nonNull(maxAuthorsSize) && Objects.nonNull(maxAuthorFullnameLength)) { instance.authorsTruncator = new AuthorsTruncator(maxAuthorsSize, maxAuthorFullnameLength); } if (Objects.nonNull(maxKeywordsSize) && Objects.nonNull(maxKeywordLength)) { instance.keywordsTruncator = new KeywordsTruncator(maxKeywordsSize, maxKeywordLength); } return instance; }</code><technical_language>If object is currently instantiated relying statically defined values ImportInformationSpaceConstants class do need check nullability of fields in similar places below</technical_language>

Target:
public DocumentMetadataAvroTruncator build() { return new DocumentMetadataAvroTruncator( maxAbstractLength, maxTitleLength, maxAuthorsSize, maxAuthorFullnameLength, maxKeywordsSize, maxKeywordLength ); }
Source:
<code><START> public void addImportMenuItem(ZapMenuItem menuItem) { addImportMenuItemImpl(menuItem); } <END></code><technical_language>this is syntactically correct nice for consistent. Opening curly brace function declaration, code, closing curly brace a separate line</technical_language>

Target:
public void addImportMenuItem(ZapMenuItem menuItem) { if (importMenuItemList == null) { importMenuItemList = createList(); } importMenuItemList.add(menuItem); }
Source:
<code>public GeneralActivityListener(final EventManager eventManager, final String projectName) { mouseActivityListener = new AWTEventListener() { @Override public void eventDispatched(AWTEvent event) { if(!WatchDogUtils.getProjectName().equals(projectName)) { return; } eventManager.update(new WatchDogEvent(event, EventType.USER_ACTIVITY)); } }; Toolkit.getDefaultToolkit().addAWTEventListener(mouseActivityListener, AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_WHEEL_EVENT_MASK); keyboardActivityListener = new AWTEventListener() { @Override public void eventDispatched(AWTEvent event) { if(!WatchDogUtils.getProjectName().equals(projectName)) { return; } <START> if (((KeyEvent) event).getKeyCode() == KeyEvent.VK_RIGHT || <END> ((KeyEvent) event).getKeyCode() == KeyEvent.VK_UP || ((KeyEvent) event).getKeyCode() == KeyEvent.VK_DOWN || ((KeyEvent) event).getKeyCode() == KeyEvent.VK_LEFT || ((KeyEvent) event).getKeyCode() == KeyEvent.VK_PAGE_DOWN || ((KeyEvent) event).getKeyCode() == KeyEvent.VK_PAGE_UP ) { eventManager.update(new WatchDogEvent(event, EventType.USER_ACTIVITY)); } } }; Toolkit.getDefaultToolkit().addAWTEventListener(keyboardActivityListener, AWTEvent.KEY_EVENT_MASK); }</code><technical_language>factor out conversion if more readable? Moreover, a switch-case statement</technical_language>

Target:
public GeneralActivityListener(final EventManager eventManager, final String projectName) { mouseActivityListener = new AWTEventListener() { @Override public void eventDispatched(AWTEvent event) { if (!WatchDogUtils.getProjectName().equals(projectName)) { return; } eventManager.update(new WatchDogEvent(event, EventType.USER_ACTIVITY)); } }; Toolkit.getDefaultToolkit().addAWTEventListener(mouseActivityListener, AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_WHEEL_EVENT_MASK); keyboardActivityListener = new AWTEventListener() { @Override public void eventDispatched(AWTEvent event) { if (!WatchDogUtils.getProjectName().equals(projectName)) { return; } switch (((KeyEvent) event).getKeyCode()) { case KeyEvent.VK_RIGHT: case KeyEvent.VK_UP: case KeyEvent.VK_DOWN: case KeyEvent.VK_LEFT: case KeyEvent.VK_PAGE_DOWN: case KeyEvent.VK_PAGE_UP: eventManager.update(new WatchDogEvent(event, EventType.USER_ACTIVITY)); } } }; Toolkit.getDefaultToolkit().addAWTEventListener(keyboardActivityListener, AWTEvent.KEY_EVENT_MASK); }
Source:
<code>@Override public boolean start() throws Exception { Run<?,?> run = getContext().get(Run.class); if (run == null) { throw new MissingContextVariableException(Run.class); } FilePath workspace = getContext().get(FilePath.class); Launcher launcher = getContext().get(Launcher.class); <START> TaskListener listener = getContext().get(TaskListener.class); <END> Map<String,String> overrides = new HashMap<String,String>(); List<MultiBinding.Unbinder> unbinders = new ArrayList<MultiBinding.Unbinder>(); for (MultiBinding<?> binding : step.bindings) { for (Class<?> requiredContext : binding.getDescriptor().getRequiredContext()) { Object v = getContext().get(requiredContext); if (v == null) { throw new MissingContextVariableException(requiredContext); } } MultiBinding.MultiEnvironment environment = binding.bind(run, workspace, launcher, listener); unbinders.add(environment.getUnbinder()); overrides.putAll(environment.getValues()); } getContext().newBodyInvoker(). withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), new Overrider(overrides))). withContext(BodyInvoker.mergeConsoleLogFilters(getContext().get(ConsoleLogFilter.class), new Filter(overrides.values(), run.getCharset().name()))). withCallback(new Callback(unbinders)). start(); return false; }</code><technical_language>fail quickly claim require a TaskListener in getRequiredContext</technical_language>

Target:
@Override public boolean start() throws Exception { Run<?,?> run = getContext().get(Run.class); TaskListener listener = getContext().get(TaskListener.class); FilePath workspace = getContext().get(FilePath.class); Launcher launcher = getContext().get(Launcher.class); Map<String,String> overrides = new HashMap<String,String>(); List<MultiBinding.Unbinder> unbinders = new ArrayList<MultiBinding.Unbinder>(); for (MultiBinding<?> binding : step.bindings) { if (binding.getDescriptor().requiresWorkspace() && (workspace == null || launcher == null)) { throw new MissingContextVariableException(FilePath.class); } MultiBinding.MultiEnvironment environment = binding.bind(run, workspace, launcher, listener); unbinders.add(environment.getUnbinder()); overrides.putAll(environment.getValues()); } getContext().newBodyInvoker(). withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), new Overrider(overrides))). withContext(BodyInvoker.mergeConsoleLogFilters(getContext().get(ConsoleLogFilter.class), new Filter(overrides.values(), run.getCharset().name()))). withCallback(new Callback(unbinders)). start(); return false; }
Source:
<code>private SqlStatements(SqlStatements that) { this.attributes = new ConcurrentHashMap<>(that.attributes); this.templateEngine = that.templateEngine; this.sqlParser = that.sqlParser; this.sqlLogger = that.sqlLogger; this.queryTimeout = that.queryTimeout; this.allowUnusedBindings = that.allowUnusedBindings; <START> this.customizers = that.customizers; <END> }</code><technical_language>I this a copy, a reference. want changes jdbi context changing behavior of another</technical_language>

Target:
private SqlStatements(SqlStatements that) { this.attributes = new ConcurrentHashMap<>(that.attributes); this.templateEngine = that.templateEngine; this.sqlParser = that.sqlParser; this.sqlLogger = that.sqlLogger; this.queryTimeout = that.queryTimeout; this.allowUnusedBindings = that.allowUnusedBindings; this.customizers.addAll(that.customizers); }
Source:
<code>public Document xmlRead(String xmlString) { Document doc = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(new InputSource(new StringReader(xmlString))); doc.getDocumentElement().normalize(); } catch (Exception e) { <START> e.printStackTrace(); <END> } return doc; }</code><technical_language>Remove printStackTrace catch log proper exception</technical_language>

Target:
public Document xmlRead(String xmlString) { Document doc = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(new InputSource(new StringReader(xmlString))); doc.getDocumentElement().normalize(); } catch (ParserConfigurationException e) { log.error("unable to parse content" + xmlString, e); } catch (SAXException e) { log.error("unable to parse content" + xmlString, e); } catch (IOException e) { log.error("unable to parse content" + xmlString, e); } return doc; }
Source:
<code>private RelDataType inferTypeFromValidator( SqlCallBinding callBinding) { SqlCase caseCall = (SqlCase) callBinding.getCall(); SqlNodeList thenList = caseCall.getThenOperands(); ArrayList<SqlNode> nullList = new ArrayList<>(); List<RelDataType> argTypes = new ArrayList<>(); for (SqlNode node : thenList) { argTypes.add( callBinding.getValidator().deriveType( callBinding.getScope(), node)); if (SqlUtil.isNullLiteral(node, false)) { nullList.add(node); } } SqlNode elseOp = caseCall.getElseOperand(); argTypes.add( callBinding.getValidator().deriveType( callBinding.getScope(), caseCall.getElseOperand())); if (SqlUtil.isNullLiteral(elseOp, false)) { nullList.add(elseOp); } RelDataType ret = callBinding.getTypeFactory().leastRestrictive(argTypes); if (null == ret) { <START> boolean changed = false; <END> if (callBinding.getValidator().isEnableTypeCoercion()) { TypeCoercion typeCoercion = callBinding.getValidator().getTypeCoercion(); RelDataType commonType = typeCoercion.getWiderTypeFor(argTypes, true); if (null != commonType) { changed = typeCoercion.caseWhenCoercion(callBinding); if (changed) { ret = callBinding.getValidator() .deriveType(callBinding.getScope(), callBinding.getCall()); } } } if (!changed) { throw callBinding.newValidationError(RESOURCE.illegalMixingOfTypes()); } } final SqlValidatorImpl validator = (SqlValidatorImpl) callBinding.getValidator(); for (SqlNode node : nullList) { validator.setValidatedNodeType(node, ret); } return ret; }</code><technical_language>changed ? name</technical_language>

Target:
private RelDataType inferTypeFromValidator( SqlCallBinding callBinding) { SqlCase caseCall = (SqlCase) callBinding.getCall(); SqlNodeList thenList = caseCall.getThenOperands(); ArrayList<SqlNode> nullList = new ArrayList<>(); List<RelDataType> argTypes = new ArrayList<>(); for (SqlNode node : thenList) { argTypes.add( callBinding.getValidator().deriveType( callBinding.getScope(), node)); if (SqlUtil.isNullLiteral(node, false)) { nullList.add(node); } } SqlNode elseOp = caseCall.getElseOperand(); argTypes.add( callBinding.getValidator().deriveType( callBinding.getScope(), caseCall.getElseOperand())); if (SqlUtil.isNullLiteral(elseOp, false)) { nullList.add(elseOp); } RelDataType ret = callBinding.getTypeFactory().leastRestrictive(argTypes); if (null == ret) { boolean coerced = false; if (callBinding.getValidator().isTypeCoercionEnabled()) { TypeCoercion typeCoercion = callBinding.getValidator().getTypeCoercion(); RelDataType commonType = typeCoercion.getWiderTypeFor(argTypes, true); if (null != commonType) { coerced = typeCoercion.caseWhenCoercion(callBinding); if (coerced) { ret = callBinding.getValidator() .deriveType(callBinding.getScope(), callBinding.getCall()); } } } if (!coerced) { throw callBinding.newValidationError(RESOURCE.illegalMixingOfTypes()); } } final SqlValidatorImpl validator = (SqlValidatorImpl) callBinding.getValidator(); for (SqlNode node : nullList) { validator.setValidatedNodeType(node, ret); } return ret; }
Source:
<code>private void readJsonFromURL() { InputStream is = null; <START> try { <END> is = url.openStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); JsonReader jr = Json.createReader(rd); parseJson(jr.readObject()); } catch (IOException | NotFoundException e) { Utils.logException(LOG, "Unable to load url: " + url.toString(), e); } finally { try { is.close(); } catch (IOException e) { Utils.logException(LOG, e); } } streamsAreLoaded = true; }</code><technical_language>remove need for finally statement a [try resources statement](<LINK_0></technical_language>

Target:
private void readJsonFromURL() { try (InputStream is = url.openStream()) { BufferedReader rd = new BufferedReader(new InputStreamReader(is)); JsonReader jr = Json.createReader(rd); parseJson(jr.readObject()); } catch (IOException | NotFoundException e) { Utils.logException(LOG, "Unable to load url: " + url.toString(), e); } streamsAreLoaded = true; }
Source:
<code>private static void addNetworkInterfaceProperties(XmlRpcStruct struct, VmNetworkInterface vmInterface, VmDevice vmDevice, String nicModel) { struct.add(VdsProperties.Type, vmDevice.getType()); struct.add(VdsProperties.Device, vmDevice.getDevice()); struct.add(VdsProperties.network, vmInterface.getNetworkName()); addAddress(vmDevice, struct); struct.add(VdsProperties.mac_addr, vmInterface.getMacAddress()); addBootOrder(vmDevice, struct); struct.add(VdsProperties.SpecParams, vmDevice.getSpecParams()); struct.add(VdsProperties.DeviceId, String.valueOf(vmDevice.getId().getDeviceId())); struct.add(VdsProperties.nic_type, nicModel); <START> struct.add(VdsProperties.portMirroring, new Boolean(vmInterface.isPortMirroring()).toString()); <END> }</code><technical_language>this property typed boolean, use: Boolean.toString(vmInterface.isPortMirroring())</technical_language>

Target:
private static void addNetworkInterfaceProperties(XmlRpcStruct struct, VmNetworkInterface vmInterface, VmDevice vmDevice, String nicModel) { struct.add(VdsProperties.Type, vmDevice.getType()); struct.add(VdsProperties.Device, vmDevice.getDevice()); struct.add(VdsProperties.network, vmInterface.getNetworkName()); addAddress(vmDevice, struct); struct.add(VdsProperties.mac_addr, vmInterface.getMacAddress()); addBootOrder(vmDevice, struct); struct.add(VdsProperties.SpecParams, vmDevice.getSpecParams()); struct.add(VdsProperties.DeviceId, String.valueOf(vmDevice.getId().getDeviceId())); struct.add(VdsProperties.nic_type, nicModel); struct.add(VdsProperties.portMirroring, Boolean.toString(vmInterface.isPortMirroring())); }