auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public String isValid(String call){ JSONObject jCall = new JSONObject(call); JSONObject params = jCall.getJSONObject("params"); String methodName = jCall.getString("method"); if(!jCall.has("method") || !params.has("sourceO") || !params.has("sourceIP") || !params.has("sourcePort") || !params.has("destinationO") || !params.has("extensions")){ return "invalid"; } if(methodName.equalsIgnoreCase("PUT") && !params.has("value")){ return "params"; } if(methodName.equalsIgnoreCase("GET") && !params.has("index")){ return "params"; } <START> if(methodName.equalsIgnoreCase("SHUTDOWN") && !params.has("port")){ <END> return "params"; } if(!methodName.equalsIgnoreCase("PING") && !methodName.equalsIgnoreCase("PONG") && !methodName.equalsIgnoreCase("LOOKUP") && !methodName.equalsIgnoreCase("PUT") && !methodName.equalsIgnoreCase("GET") && !methodName.equalsIgnoreCase("SHUTDOWN")){ return "method"; } String ip = params.getString("sourceIP"); int port = params.getInt("sourcePort"); final String PATTERN = "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; Pattern pattern = Pattern.compile(PATTERN); Matcher matcher = pattern.matcher(ip); if(!matcher.matches()){ return "params"; } if(port < 0 || port > 61001){ return "params"; } return "valid"; }</code><technical_language>@euphzji "!params.has("port")" supposed "!params.has("sourcePort")"? If in "port" field, need pull in @ykravtsov get added RPCBuilder</technical_language>

Target:
public String isValid(String call) { JSONObject jCall; try { jCall = new JSONObject(call); } catch (JSONException e) { DBP.printException(e); return "parse"; } JSONObject params = new JSONObject(); String methodName = ""; if (!jCall.has("method") || !jCall.has("params") || !jCall.has("jsonrpc")) { return "invalid"; } else { methodName = jCall.getString("method"); params = jCall.getJSONObject("params"); } if (!jCall.getString("jsonrpc").equals("2.0")) return "invalid"; if (!params.has("sourceO") || !params.has("sourceIP") || !params.has("sourcePort") || !params.has("destinationO") || !params.has("extensions")) { return "params"; } if (methodName.equalsIgnoreCase("PUT") && !params.has("value")) { return "params"; } if (methodName.equalsIgnoreCase("GET") && !params.has("index")) { return "params"; } if (methodName.equalsIgnoreCase("SHUTDOWN") && !params.has("sourcePort")) { return "params"; } if (!methodName.equalsIgnoreCase("PING") && !methodName.equalsIgnoreCase("PONG") && !methodName.equalsIgnoreCase("LOOKUP") && !methodName.equalsIgnoreCase("PUT") && !methodName.equalsIgnoreCase("GET") && !methodName.equalsIgnoreCase("SHUTDOWN")) { return "method"; } String ip = params.getString("sourceIP"); int port = params.getInt("sourcePort"); final String PATTERN = "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; Pattern pattern = Pattern.compile(PATTERN); Matcher matcher = pattern.matcher(ip); if (!matcher.matches()) { return "params"; } if (port < 0 || port > 61001) { return "params"; } return "valid"; }
Source:
<code>static boolean castToBoolean(final Object in) throws PSQLException { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Cast to boolean: \"{0}\"", String.valueOf(in)); } if (in instanceof Boolean) { return (Boolean) in; } if (in instanceof String) { return fromString((String) in); } if (in instanceof Character) { <START> return fromString(in.toString()); <END> } if (in instanceof Number) { return fromNumber((Number) in); } throw new PSQLException("Cannot cast to boolean", PSQLState.CANNOT_COERCE); }</code><technical_language>a separate map. Character is set bools, in.toString() ruin performance here</technical_language>

Target:
static boolean castToBoolean(final Object in) throws PSQLException { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Cast to boolean: \"{0}\"", String.valueOf(in)); } if (in instanceof Boolean) { return (Boolean) in; } if (in instanceof String) { return fromString((String) in); } if (in instanceof Character) { return fromCharacter((Character) in); } if (in instanceof Number) { return fromNumber((Number) in); } throw new PSQLException("Cannot cast to boolean", PSQLState.CANNOT_COERCE); }
Source:
<code>public void handleGetFirmwareVersionResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception, final List<FirmwareVersionDto> firmwareVersionList) { LOGGER.info("handleGetFirmwareVersionResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Get firmware version response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } final List<FirmwareVersion> firmwareVersions = this.configurationMapper.mapAsList(firmwareVersionList, FirmwareVersion.class); final FirmwareVersionResponse firmwareVersionResponse = new FirmwareVersionResponse(firmwareVersions); <START> this.webServiceResponseMessageSender.send( <END> ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withDataObject(firmwareVersionResponse) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
public void handleGetFirmwareVersionResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception, final List<FirmwareVersionDto> firmwareVersionList) { LOGGER.info("handleGetFirmwareVersionResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Get firmware version response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } final List<FirmwareVersion> firmwareVersions = this.configurationMapper.mapAsList(firmwareVersionList, FirmwareVersion.class); final FirmwareVersionResponse firmwareVersionResponse = new FirmwareVersionResponse(firmwareVersions); ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withDataObject(firmwareVersionResponse) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send( responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
<code>protected IStatus run(IProgressMonitor monitor) { <START> ISourceModule module = null; <END> while ((module = modules.poll()) != null) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } processModule(module, buildType, state); } return Status.OK_STATUS; }</code><technical_language>initial null needed. a for () loop :) for (ISourceModule module; (module = modules.poll()) != null;) { ... }</technical_language>

Target:
protected IStatus run(IProgressMonitor monitor) { for (ISourceModule module; (module = modules.poll()) != null;) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; } processModule(module, buildType, state); } return Status.OK_STATUS; }
Source:
<code>public void onClick(ClickEvent event) { ExpandableListViewItem eventItem = null; if (event.getSource() instanceof ExpandableListViewItem) { eventItem = (ExpandableListViewItem)event.getSource(); } if (eventItem != null) { boolean active = eventItem.isActive(); hideAllDetails(); eventItem.toggleExpanded(!active); toggleExpanded(); } else { hideAllDetails(); } event.preventDefault(); <START> event.stopPropagation(); <END> }</code><technical_language>Nit-pick: please consider putting top instead of bottom. (I prevent/stop event handle it.)</technical_language>

Target:
public void onClick(ClickEvent event) { event.preventDefault(); event.stopPropagation(); ExpandableListViewItem eventItem = null; if (event.getSource() instanceof ExpandableListViewItem) { eventItem = (ExpandableListViewItem)event.getSource(); } if (eventItem != null) { boolean active = eventItem.isActive(); hideAllDetails(); eventItem.toggleExpanded(!active); toggleExpanded(); } else { hideAllDetails(); } }
Source:
<code>private Guid getClusterId() { <START> Guid vdsGroupId = getParameters().getVdsGroupId(); <END> if (Guid.Empty.equals(getParameters().getVdsGroupId())) { vdsGroupId = Guid.createGuidFromStringDefaultEmpty( Config.<String> getValue(ConfigValues.AutoRegistrationDefaultVdsGroupID)); log.debug( "RegisterVdsQuery::ExecuteCommand - VdsGroupId received as -1, using AutoRegistrationDefaultVdsGroupID: '{}'", vdsGroupId); } if (vdsGroupId == null || Guid.Empty.equals(vdsGroupId)) { VdsGroupDAO dao = DbFacade.getInstance().getVdsGroupDao(); VDSGroup cluster = dao.getByName("Default"); if (cluster != null) { vdsGroupId = cluster.getId(); } else { List<VDSGroup> clusters = dao.getAll(); if (clusters.size() > 0) { vdsGroupId = clusters.get(0).getId(); } } } return vdsGroupId; }</code><technical_language>s/vdsGroupId/clusterId</technical_language>

Target:
private Guid getClusterId() { Guid clusterId = getParameters().getVdsGroupId(); if (Guid.Empty.equals(getParameters().getVdsGroupId())) { clusterId = Guid.createGuidFromStringDefaultEmpty( Config.<String> getValue(ConfigValues.AutoRegistrationDefaultVdsGroupID)); log.debug( "Cluster id was not provided for registering the host {}, the cluster id is taken from the config value {}", getParameters().getVdsName(), clusterId, ConfigValues.AutoRegistrationDefaultVdsGroupID.name()); } if (Guid.isNullOrEmpty(clusterId)) { VdsGroupDAO clusterDao = getDbFacade().getVdsGroupDao(); VDSGroup cluster = clusterDao.getByName("Default"); if (cluster != null) { clusterId = cluster.getId(); } else { List<VDSGroup> clusters = clusterDao.getAll(); if (clusters.isEmpty()) { clusterId = clusters.get(0).getId(); } } } return clusterId; }
Source:
<code>public void increaseStart(long value) { start += value; if (start == currentBlock().getEnd()) { currentBlockIndex++; if (isDone()) { return; } <START> checkArgument(start == currentBlock().getStart()); <END> } }</code><technical_language>This verify() a condition of input</technical_language>

Target:
public void increaseStart(long value) { start += value; if (start == currentBlock().getEnd()) { currentBlockIndex++; if (isDone()) { return; } verify(start == currentBlock().getStart()); } }
Source:
<code>protected void addFileSetProperties(FileSetProperties.Builder properties) { try { FileSetUtil.configureORCFileSet(config.schema, properties); } catch (IOException e) { <START> LOG.debug(""); <END> } catch (UnsupportedTypeException e) { e.printStackTrace(); } }</code><technical_language>wrong, need include a good error message. I leave messaging FileSetUtil instead of catching exceptions here, method is is invalid</technical_language>

Target:
protected void addFileSetProperties(FileSetProperties.Builder properties) { FileSetUtil.configureORCFileSet(config.schema, properties); }
Source:
<code>public CertificationStatus(String name){ this.id = id; <START> this.name = name; <END> }</code><technical_language>is this file changing? concerned changing domain objects far-reaching effects. well, id this.id set in this method</technical_language>

Target:
public CertificationStatus(String name){ this.name = name; }
Source:
<code>public void cloneShouldOnlyWorksWithEmptyRepos() throws IOException { final File parentFolder = createTempDirectory(); final File gitSource = new File(parentFolder, SOURCE_GIT + ".git"); final File gitTarget = new File(parentFolder, TARGET_GIT + ".git"); final Git origin = setupGitRepo(gitSource); final Git cloned = new Clone(gitTarget, gitSource.getAbsolutePath(), false, CredentialsProvider.getDefault(), null).execute().get(); assertThat(cloned).isNotNull(); assertThat(new ListRefs(cloned.getRepository()).execute()).hasSize(2); assertEquals(new ListRefs(cloned.getRepository()).execute().size(), new ListRefs(origin.getRepository()).execute().size()); <START> final Git clonedWithNoEmptyRepo = new Clone(gitTarget, <END> gitSource.getAbsolutePath(), false, CredentialsProvider.getDefault(), null).execute().get(); }</code><technical_language>Nitpick: java assertThatThrownBy( () -> /* some code throws exception*/) .isInstanceOf(Clone.CloneException.class) .hasMessage("specific message"); //or hasMessageContaining("substring"); wrap statement is supposed throw exception. This give more useful error message in case assertion fails, test more informative (what kind of failure expecting statement is supposed throw it?) focused (it fail if exception is accidentally thrown some other statement in test)</technical_language>

Target:
public void cloneShouldOnlyWorksWithEmptyRepos() throws IOException { final File parentFolder = createTempDirectory(); final File gitSource = new File(parentFolder, SOURCE_GIT + ".git"); final File gitTarget = new File(parentFolder, TARGET_GIT + ".git"); final Git origin = setupGitRepo(gitSource); final Git cloned = new Clone(gitTarget, gitSource.getAbsolutePath(), false, CredentialsProvider.getDefault(), null).execute().get(); assertThat(cloned).isNotNull(); assertThat(new ListRefs(cloned.getRepository()).execute()).hasSize(2); assertEquals(new ListRefs(cloned.getRepository()).execute().size(), new ListRefs(origin.getRepository()).execute().size()); assertThatThrownBy(() -> new Clone(gitTarget, gitSource.getAbsolutePath(), false, CredentialsProvider.getDefault(), null).execute().get()) .isInstanceOf(Clone.CloneException.class); }
Source:
<code>private Optional<AggregationBuilder> getCreatedAtFacet(IssueQuery query, Map<String, QueryBuilder> filters, QueryBuilder esQuery) { long startTime; Date createdAfter = query.createdAfter(); if (createdAfter == null) { Optional<Long> minDate = getMinCreatedAt(filters, esQuery); if (!minDate.isPresent()) { return Optional.empty(); } startTime = minDate.get(); } else { startTime = createdAfter.getTime(); } Date createdBefore = query.createdBefore(); long endTime = createdBefore == null ? system.now() : createdBefore.getTime(); Duration timeSpan = new Duration(startTime, endTime); DateHistogramInterval bucketSize = DateHistogramInterval.YEAR; if (timeSpan.isShorterThan(TWENTY_DAYS)) { bucketSize = DateHistogramInterval.DAY; } else if (timeSpan.isShorterThan(TWENTY_WEEKS)) { bucketSize = DateHistogramInterval.WEEK; } else if (timeSpan.isShorterThan(TWENTY_MONTHS)) { bucketSize = DateHistogramInterval.MONTH; } AggregationBuilder dateHistogram = AggregationBuilders.dateHistogram(PARAM_CREATED_AT) .field(IssueIndexDefinition.FIELD_ISSUE_FUNC_CREATED_AT) .dateHistogramInterval(bucketSize) .minDocCount(0L) <START> .format("yyyy-MM-dd'T'HH:mm:ssZZ") <END> .timeZone(DateTimeZone.forOffsetMillis(system.getDefaultTimeZone().getRawOffset())) .extendedBounds(new ExtendedBounds(startTime, endTime - 1L)); addEffortAggregationIfNeeded(query, dateHistogram); return Optional.of(dateHistogram); }</code><technical_language>This update in this commit => this commit is updating test code, this is prod code</technical_language>

Target:
private Optional<AggregationBuilder> getCreatedAtFacet(IssueQuery query, Map<String, QueryBuilder> filters, QueryBuilder esQuery) { long startTime; Date createdAfter = query.createdAfter(); if (createdAfter == null) { Optional<Long> minDate = getMinCreatedAt(filters, esQuery); if (!minDate.isPresent()) { return Optional.empty(); } startTime = minDate.get(); } else { startTime = createdAfter.getTime(); } Date createdBefore = query.createdBefore(); long endTime = createdBefore == null ? system.now() : createdBefore.getTime(); Duration timeSpan = new Duration(startTime, endTime); DateHistogramInterval bucketSize = DateHistogramInterval.YEAR; if (timeSpan.isShorterThan(TWENTY_DAYS)) { bucketSize = DateHistogramInterval.DAY; } else if (timeSpan.isShorterThan(TWENTY_WEEKS)) { bucketSize = DateHistogramInterval.WEEK; } else if (timeSpan.isShorterThan(TWENTY_MONTHS)) { bucketSize = DateHistogramInterval.MONTH; } AggregationBuilder dateHistogram = AggregationBuilders.dateHistogram(PARAM_CREATED_AT) .field(IssueIndexDefinition.FIELD_ISSUE_FUNC_CREATED_AT) .dateHistogramInterval(bucketSize) .minDocCount(0L) .format(JODA_DATE_TIME_FORMAT) .timeZone(DateTimeZone.forOffsetMillis(system.getDefaultTimeZone().getRawOffset())) .extendedBounds(new ExtendedBounds(startTime, endTime - 1L)); addEffortAggregationIfNeeded(query, dateHistogram); return Optional.of(dateHistogram); }
Source:
<code>public static void beforeClass() throws Exception { <START> <END> if (bot.activeView().getTitle().equals("Welcome")) bot.viewByTitle("Welcome").close(); bot.perspectiveById("org.eclipse.jdt.ui.JavaPerspective").activate(); bot.viewByTitle("Package Explorer").show(); bot.menu("File").menu("New").menu("Java Project").click(); SWTBotShell shell = bot.shell("New Java Project"); shell.activate(); bot.textWithLabel("Project name:").setText(projectName); bot.button("Finish").click(); }</code><technical_language>whitespace</technical_language>

Target:
public static void beforeClass() throws Exception { if (bot.activeView().getTitle().equals("Welcome")) bot.viewByTitle("Welcome").close(); bot.perspectiveById("org.eclipse.jdt.ui.JavaPerspective").activate(); bot.viewByTitle("Package Explorer").show(); bot.menu("File").menu("New").menu("Project...").click(); bot.tree().getTreeItem("General").expand().getNode("Project").select(); bot.button("Next >").click(); bot.textWithLabel("Project name:").setText(projectName); bot.button("Finish").click(); }
Source:
<code>public void testHardTimeExpiration() throws InterruptedException { <START> org.midonet.odp.FlowMatch flowMatch = <END> new org.midonet.odp.FlowMatch().addKey(FlowKeys.tunnel(10L, 100, 200)); WildcardFlow wildcardFlow = WildcardFlowFactory.createHardExpiration(flowMatch, timeOut); Flow flow = new Flow(flowMatch, actionsAsJava(wildcardFlow)); int numberOfFlowsAdded = 0; ManagedWildcardFlow wflow = ManagedWildcardFlow.create(wildcardFlow); flowManager.add(wflow); flowManager.add(flow, wflow); flowManagerHelper.addFlow(new Flow(flowMatch)); numberOfFlowsAdded++; assertThat("DpFlowTable was not updated", flowManager.dpFlowTable.size(), equalTo(numberOfFlowsAdded)); assertThat("WildcardFlowsToDpFlows was not updated", flowManager.getNumWildcardFlows(), equalTo(numberOfFlowsAdded)); assertThat("DpFlowToWildFlow table was not updated", flowManager.getWildcardTables().get( wflow.getMatch().getUsedFields()) .get(wflow.getMatch()), equalTo(wflow)); Thread.sleep(timeOut); flowManager.checkFlowsExpiration(); assertThat("Flow was not deleted", flowManagerHelper.flowsMap.get(flowMatch), nullValue()); assertThat("Flow was not deleted from ManagedWildcardFlow", !wflow.dpFlows().contains(flowMatch)); }</code><technical_language>fq names now? this class is imported, bare above. weird</technical_language>

Target:
public void testHardTimeExpiration() throws InterruptedException { FlowMatch flowMatch = new FlowMatch().addKey(FlowKeys.tunnel(10L, 100, 200)); WildcardFlow wildcardFlow = WildcardFlowFactory.createHardExpiration(flowMatch, timeOut); Flow flow = new Flow(flowMatch, actionsAsJava(wildcardFlow)); int numberOfFlowsAdded = 0; ManagedWildcardFlow wflow = ManagedWildcardFlow.create(wildcardFlow); flowManager.add(wflow); flowManager.add(flow, wflow); flowManagerHelper.addFlow(new Flow(flowMatch)); numberOfFlowsAdded++; assertThat("DpFlowTable was not updated", flowManager.dpFlowTable.size(), equalTo(numberOfFlowsAdded)); assertThat("WildcardFlowsToDpFlows was not updated", flowManager.getNumWildcardFlows(), equalTo(numberOfFlowsAdded)); assertThat("DpFlowToWildFlow table was not updated", flowManager.getWildcardTables().get( wflow.getMatch().getUsedFields()) .get(wflow.getMatch()), equalTo(wflow)); Thread.sleep(timeOut); flowManager.checkFlowsExpiration(); assertThat("Flow was not deleted", flowManagerHelper.flowsMap.get(flowMatch), nullValue()); assertThat("Flow was not deleted from ManagedWildcardFlow", !wflow.dpFlows().contains(flowMatch)); }
Source:
<code>protected abstract void runAutonomous() throws InterruptedException, AutonomousModeOverException; public void loadSettings(TuningContext context) { this.driveSpeed = context.getFloat("auto-main-driveSpeed", 1.0f); this.rotateSpeed = context.getFloat("auto-main-rotateSpeed", 1.0f); <START> this.clampHeightPadding = context.getFloat("auto-main-clampHeightPadding", 0.1f); <END> }</code><technical_language>want default smaller - 0.01</technical_language>

Target:
protected abstract void runAutonomous() throws InterruptedException, AutonomousModeOverException; public void loadSettings(TuningContext context) { this.driveSpeed = context.getFloat("auto-main-driveSpeed", 1.0f); this.rotateSpeed = context.getFloat("auto-main-rotateSpeed", 1.0f); this.clampHeightPadding = context.getFloat("auto-main-clampHeightPadding", 0.01f); }
Source:
<code>public void loadConfiguration(IProgressMonitor monitor) { if (!configured) { synchronized (this) { if (!configured) { try { <START> mapping = Collections.emptyMap(); <END> if (source != null) { File file = new File(source); if (file.isFile()) { Map<String, String> result; if (kind == ESourceKind.BINARY) { result = FunctionNameMapper.mapFromBinaryFile(file); } else { result = FunctionNameMapper.mapFromNmTextFile(file); } if (result != null) { mapping = result; } } } } finally { configured = true; } } } } }</code><technical_language>'mapping' is initialized Collections.emptyMap()</technical_language>

Target:
public void loadConfiguration(IProgressMonitor monitor) { if (!fConfigured) { synchronized (this) { if (!fConfigured) { try { fMapping = Collections.emptyMap(); if (fSource != null) { File file = new File(fSource); if (file.isFile()) { Map<String, String> result; if (fKind == SourceKind.BINARY) { result = FunctionNameMapper.mapFromBinaryFile(file); } else { result = FunctionNameMapper.mapFromNmTextFile(file); } if (result != null) { fMapping = result; } } } } finally { fConfigured = true; } } } } }
Source:
<code>public void onSelectPage(@NonNull Card card, @NonNull HistoryEntry entry, View view) { ActivityOptionsCompat options = ActivityOptionsCompat. <START> makeSceneTransitionAnimation((Activity) getContext(), ((ListCardItemView) <END> view).getTitleView(), getContext().getString(R.string.transition_title)); startActivity(PageActivity.newIntentForNewTab(getContext(), entry, entry.getTitle()), options.toBundle()); }</code><technical_language>getAppCompatActivity()</technical_language>

Target:
public void onSelectPage(@NonNull Card card, @NonNull HistoryEntry entry, View view) { ActivityOptionsCompat options = ActivityOptionsCompat. makeSceneTransitionAnimation(getAppCompatActivity(), ((ListCardItemView) view).getTitleView(), getContext().getString(R.string.transition_title)); startActivity(PageActivity.newIntentForNewTab(getContext(), entry, entry.getTitle()), options.toBundle()); }
Source:
<code>private static void setSuspensionLevel(int level) { if (level < 0 || level >= valves.length) { throw new IndexOutOfBoundsException(); } for (int i = 0; i < valves.length; i++) { if (i == level) { valves[i].set(true); } else { valves[i].set(false); <START> } <END> } currentLevel = level; }</code><technical_language>Minor nitpick, shorten this code</technical_language>

Target:
private static void setSuspensionLevel(int level) { if (level < 0 || level >= valves.length) { throw new IndexOutOfBoundsException(); } for (int i = 0; i < valves.length; i++) { valves[i].set(i == level); } currentLevel = level; }
Source:
<code>public void deletePrefix(WinePrefixDTO winePrefix, Consumer<Exception> errorCallback) { try { fileUtilities.remove(new File(winePrefix.getPath())); } catch (IOException e) { <START> errorCallback.accept(e); <END> } List<ShortcutDTO> shortcuts = libraryManager.fetchShortcuts(); for (ShortcutDTO shortcutDTO: shortcuts) { final InteractiveScriptSession interactiveScriptSession = scriptInterpreter.createInteractiveSession(); interactiveScriptSession.eval("include([\"Functions\", \"Shortcuts\", \"Reader\"]);", ignored -> interactiveScriptSession.eval( "new ShortcutReader()", output -> { final ScriptObjectMirror shortcutReader = (ScriptObjectMirror) output; shortcutReader.callMember("of", shortcutDTO); final String container = (String) shortcutReader.callMember("container"); if (container.equals(winePrefix.getName())) { shortcutManager.deleteShortcut(shortcutDTO); } }, errorCallback), errorCallback ); } }</code><technical_language>log this exception</technical_language>

Target:
public void deletePrefix(WinePrefixDTO winePrefix, Consumer<Exception> errorCallback) { try { fileUtilities.remove(new File(winePrefix.getPath())); } catch (IOException e) { LOGGER.error("Cannot delete Wine prefix (" + winePrefix.getPath() + ")! Exception: " + e.toString()); errorCallback.accept(e); } List<ShortcutDTO> shortcuts = libraryManager.fetchShortcuts(); for (ShortcutDTO shortcutDTO: shortcuts) { final InteractiveScriptSession interactiveScriptSession = scriptInterpreter.createInteractiveSession(); interactiveScriptSession.eval("include([\"Functions\", \"Shortcuts\", \"Reader\"]);", ignored -> interactiveScriptSession.eval( "new ShortcutReader()", output -> { final ScriptObjectMirror shortcutReader = (ScriptObjectMirror) output; shortcutReader.callMember("of", shortcutDTO); final String container = (String) shortcutReader.callMember("container"); if (container.equals(winePrefix.getName())) { shortcutManager.deleteShortcut(shortcutDTO); } }, errorCallback), errorCallback ); } }
Source:
<code>public final Optional<RedirectAction> getLogoutAction(final WebContext context, final U currentProfile, final String targetUrl) { init(); <START> return Optional.of(logoutActionBuilder.getLogoutAction(context, currentProfile, targetUrl)); <END> }</code><technical_language>ofNullable</technical_language>

Target:
public final Optional<RedirectAction> getLogoutAction(final WebContext context, final U currentProfile, final String targetUrl) { init(); return logoutActionBuilder.getLogoutAction(context, currentProfile, targetUrl); }
Source:
<code>public void processLeftCheckpoint(final MistCheckpointEvent input) { <START> final Map<String, Object> stateMap = checkpointMap.remove(latestTimestampBeforeCheckpoint); <END> stateMap.put("count", count); checkpointMap.put(latestTimestampBeforeCheckpoint, stateMap); outputEmitter.emitCheckpoint(input); }</code><technical_language>do remove state? this happen? This return null if Map is set remove</technical_language>

Target:
public void processLeftCheckpoint(final MistCheckpointEvent input) { final Map<String, Object> stateMap = super.getStateSnapshot(); stateMap.put("count", count); checkpointMap.put(latestTimestampBeforeCheckpoint, stateMap); outputEmitter.emitCheckpoint(input); }
Source:
<code>public Map<String, Optional<Partition>> getPartitionsByNames(String databaseName, String tableName, List<String> partitionNames) { if (partitionNames.isEmpty()) { <START> return Collections.emptyMap(); <END> } try { List<PartitionInfo> partitionInfos = ProtoUtils.toPartitionInfoList( client.readTable(databaseName, tableName, Constraint.getDefaultInstance())); partitionInfos = partitionInfos.stream().filter(p -> p.getTableName().equals(tableName)) .collect(Collectors.toList()); Map<String, Optional<Partition>> result = partitionInfos.stream() .filter(p -> partitionNames.stream().anyMatch(p.getPartitionName()::equals)) .collect(Collectors.toMap( PartitionInfo::getPartitionName, pi -> Optional.of(ProtoUtils.fromProto(pi)))); return Collections.unmodifiableMap(result); } catch (AlluxioStatusException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } }</code><technical_language>ImmutableMap.of</technical_language>

Target:
public Map<String, Optional<Partition>> getPartitionsByNames(String databaseName, String tableName, List<String> partitionNames) { if (partitionNames.isEmpty()) { return ImmutableMap.of(); } try { List<PartitionInfo> partitionInfos = AlluxioProtoUtils.toPartitionInfoList(client.readTable(databaseName, tableName, Constraint.getDefaultInstance())); partitionInfos = partitionInfos.stream().filter(p -> p.getTableName().equals(tableName)).collect(toImmutableList()); return partitionInfos.stream() .filter(p -> partitionNames.stream().anyMatch(p.getPartitionName()::equals)) .collect(toImmutableMap(PartitionInfo::getPartitionName, partitionInfo -> Optional.of(AlluxioProtoUtils.fromProto(partitionInfo)))); } catch (AlluxioStatusException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } }
Source:
<code>public void setWidth(int desiredWidth, int desiredScale, boolean errorOnTrunc) throws StandardException { int sourceWidth; if ( (_clobValue == null ) && (getString() == null) ) { return; } sourceWidth = getLength(); if (sourceWidth < desiredWidth) { if (!(this instanceof SQLVarchar)) { StringBuilder strBuilder; strBuilder = new StringBuilder(getString()); for ( ; sourceWidth < desiredWidth-1; sourceWidth++) { strBuilder.append(' '); } setValue(new String(strBuilder)); } } else if (sourceWidth > desiredWidth && desiredWidth > 0) { try { hasNonBlankChars(getString(), desiredWidth, sourceWidth); } catch (StandardException se) { if (errorOnTrunc) { throw se; } String source = getString(); int transferSize = getUTF8Length(source, 0, desiredWidth); int dataSize = transferSize + getUTF8Length(source, desiredWidth, source.length()); DataTruncation warning = new DataTruncation( -1, false, true, dataSize, transferSize, se); StatementContext statementContext = (StatementContext) ContextService.getContext(ContextId.LANG_STATEMENT); if (statementContext != null) { Activation activation = statementContext.getActivation(); if (activation != null) { activation.getResultSet().addWarning(warning); } } <START> String warningMessage = String.format("Truncated a string source=%s, sourceWidth=%s, desiredWidth=%s", <END> source, sourceWidth, desiredWidth); logger.warn(warningMessage); } setValue(getString().substring(0, desiredWidth)); } }</code><technical_language>sourceWidth desiredWidth %d</technical_language>

Target:
public void setWidth(int desiredWidth, int desiredScale, boolean errorOnTrunc) throws StandardException { int sourceWidth; if ( (_clobValue == null ) && (getString() == null) ) { return; } sourceWidth = getLength(); if (sourceWidth < desiredWidth) { if (!(this instanceof SQLVarchar)) { StringBuilder strBuilder; strBuilder = new StringBuilder(getString()); for ( ; sourceWidth < desiredWidth-1; sourceWidth++) { strBuilder.append(' '); } setValue(new String(strBuilder)); } } else if (sourceWidth > desiredWidth && desiredWidth > 0) { try { hasNonBlankChars(getString(), desiredWidth, sourceWidth); } catch (StandardException se) { if (errorOnTrunc) { throw se; } String source = getString(); int transferSize = getUTF8Length(source, 0, desiredWidth); int dataSize = transferSize + getUTF8Length(source, desiredWidth, source.length()); DataTruncation warning = new DataTruncation( -1, false, true, dataSize, transferSize, se); StatementContext statementContext = (StatementContext) ContextService.getContext(ContextId.LANG_STATEMENT); if (statementContext != null) { Activation activation = statementContext.getActivation(); if (activation != null) { activation.getResultSet().addWarning(warning); } } String warningMessage = String.format("Truncated a string source=%s, sourceWidth=%d, desiredWidth=%d", source, sourceWidth, desiredWidth); logger.warn(warningMessage); } setValue(getString().substring(0, desiredWidth)); } }
Source:
<code>public void onApplicationEvent(ContextStartedEvent event) { CronTasksConfigurationDto cronTasksConfiguration = getTasksConfigurationDto(); for (CronTaskConfigurationDto dto : cronTasksConfiguration.getCronTaskConfigurations()) { if (dto.isOneTimeExecution()) { <START> continue; <END> } cronJobSchedulerService.scheduleJob(dto); if (dto.shouldExecuteImmediately()) { cronJobSchedulerService.executeJob(dto); } } }</code><technical_language>I handled isOneTimeExecution() properly in CronJobSchedulerServiceImpl.scheduleJob, skipping</technical_language>

Target:
public void onApplicationEvent(ContextStartedEvent event) { CronTasksConfigurationDto cronTasksConfiguration = getTasksConfigurationDto(); for (CronTaskConfigurationDto dto : cronTasksConfiguration.getCronTaskConfigurations()) { if (dto.isOneTimeExecution()) { continue; } cronJobSchedulerService.scheduleJob(dto); } }
Source:
<code>public static boolean updateDiskStats(HWDiskStore diskStore) { String index = null; HWPartition[] partitions = diskStore.getPartitions(); if (partitions.length > 0) { index = Integer.toString(partitions[0].getMajor()); } else if (diskStore.getName().startsWith(PHYSICALDRIVE_PREFIX)) { index = diskStore.getName().substring(PHYSICALDRIVE_PREFIX.length(), diskStore.getName().length()); } else { LOG.warn("Couldn't match index for {}", diskStore.getName()); return false; } populateReadWriteMaps(index); if (readMap.containsKey(index)) { diskStore.setReads(MapUtil.getOrDefault(readMap, index, 0L)); diskStore.setReadBytes(MapUtil.getOrDefault(readByteMap, index, 0L)); diskStore.setWrites(MapUtil.getOrDefault(writeMap, index, 0L)); diskStore.setWriteBytes(MapUtil.getOrDefault(writeByteMap, index, 0L)); diskStore.setCurrentQueueLength(MapUtil.getOrDefault(queueLengthMap, index, 0L)); <START> diskStore.setTransferTime(MapUtil.getOrDefault(timeStampMap, index, 0L)-MapUtil.getOrDefault(xferTimeMap, index, 0L)); <END> diskStore.setTimeStamp(MapUtil.getOrDefault(timeStampMap, index, 0L)); return true; } else { return false; } }</code><technical_language>minor performance tweak. If do next line (set timestamp) first, diskStore.getTimeStamp() here. swap lines 249 250 for reason</technical_language>

Target:
public static boolean updateDiskStats(HWDiskStore diskStore) { String index = null; HWPartition[] partitions = diskStore.getPartitions(); if (partitions.length > 0) { index = Integer.toString(partitions[0].getMajor()); } else if (diskStore.getName().startsWith(PHYSICALDRIVE_PREFIX)) { index = diskStore.getName().substring(PHYSICALDRIVE_PREFIX.length(), diskStore.getName().length()); } else { LOG.warn("Couldn't match index for {}", diskStore.getName()); return false; } populateReadWriteMaps(index); if (readMap.containsKey(index)) { diskStore.setReads(MapUtil.getOrDefault(readMap, index, 0L)); diskStore.setReadBytes(MapUtil.getOrDefault(readByteMap, index, 0L)); diskStore.setWrites(MapUtil.getOrDefault(writeMap, index, 0L)); diskStore.setWriteBytes(MapUtil.getOrDefault(writeByteMap, index, 0L)); diskStore.setCurrentQueueLength(MapUtil.getOrDefault(queueLengthMap, index, 0L)); diskStore.setTimeStamp(MapUtil.getOrDefault(timeStampMap, index, 0L)); diskStore.setTransferTime(diskStore.getTimeStamp()-MapUtil.getOrDefault(xferTimeMap, index, 0L)); return true; } else { return false; } }
Source:
<code>public GatewayRefundResponse refund(RefundGatewayRequest request) { EpdqRefundResponse unmarshalled; try { GatewayClient.Response response = client.postRequestFor(ROUTE_FOR_MAINTENANCE_ORDER, request.getGatewayAccount(), buildRefundOrder(request)); <START> unmarshalled = unmarshallResponse(response, EpdqRefundResponse.class); <END> } catch (GenericGatewayErrorException | GatewayConnectionTimeoutErrorException | GatewayConnectionErrorException e) { return GatewayRefundResponse.fromGatewayError(e.toGatewayError()); } return GatewayRefundResponse.fromBaseRefundResponse(unmarshalled, PENDING); }</code><technical_language>is a reason return this here</technical_language>

Target:
public GatewayRefundResponse refund(RefundGatewayRequest request) { try { GatewayClient.Response response = client.postRequestFor(ROUTE_FOR_MAINTENANCE_ORDER, request.getGatewayAccount(), buildRefundOrder(request)); return GatewayRefundResponse.fromBaseRefundResponse(unmarshallResponse(response, EpdqRefundResponse.class), PENDING); } catch (GenericGatewayErrorException | GatewayConnectionTimeoutErrorException | GatewayConnectionErrorException e) { return GatewayRefundResponse.fromGatewayError(e.toGatewayError()); } }
Source:
<code>public List<LogrotateAdditionalFile> getExtrasFilesHourly() { return getAllExtraFiles().stream() <START> .filter(p -> p.getLogrotateFrequencyOverride().equals(SingularityExecutorLogrotateFrequency.HOURLY)).collect(Collectors.toList()); <END> }</code><technical_language>formatting, put collect call a new line more readable</technical_language>

Target:
public List<LogrotateAdditionalFile> getExtrasFilesHourly() { return getAllExtraFiles().stream() .filter(p -> p.getLogrotateFrequencyOverride().equals(SingularityExecutorLogrotateFrequency.HOURLY.getLogrotateValue())) .collect(Collectors.toList()); }
Source:
<code>public static String extractKFSInfoFromConcurString(String concurString) { String kfsInfo = StringUtils.EMPTY; <START> if (StringUtils.isNotBlank(concurString) && concurString.contains(CUKFSConstants.LEFT_PARENTHESIS) && concurString.contains(CUKFSConstants.RIGHT_PARENTHESIS) && concurString.lastIndexOf(CUKFSConstants.LEFT_PARENTHESIS) < concurString.length()) { <END> kfsInfo = concurString.substring(concurString.lastIndexOf(CUKFSConstants.LEFT_PARENTHESIS) + 1, concurString.lastIndexOf(CUKFSConstants.RIGHT_PARENTHESIS)); } return kfsInfo; }</code><technical_language>this if statement broken out some improve readability? doesStringContainOpenCloseParens</technical_language>

Target:
public static String extractKFSInfoFromConcurString(String concurString) { String kfsInfo = StringUtils.EMPTY; if (doesStringContainOpenCloseParenthesis(concurString)) { kfsInfo = concurString.substring(concurString.lastIndexOf(CUKFSConstants.LEFT_PARENTHESIS) + 1, concurString.lastIndexOf(CUKFSConstants.RIGHT_PARENTHESIS)); } return kfsInfo; }
Source:
<code>private void unmarkTeamPrivate(final IContainer p) throws CoreException { final IResource[] c; c = p.members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS); if (c != null) { for (int k = 0; k < c.length; k++) { if (c[k] instanceof IContainer) { unmarkTeamPrivate((IContainer) c[k]); } if (c[k].isTeamPrivateMember()) { <START> if (GitTraceLocation.CORE.isActive()) { <END> GitTraceLocation.getTrace().trace( GitTraceLocation.CORE.getLocation(), "notTeamPrivate " + c[k]); } c[k].setTeamPrivateMember(false); } } } }</code><technical_language>unrelated change</technical_language>

Target:
private void unmarkTeamPrivate(final IContainer p) throws CoreException { final IResource[] c; c = p.members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS); if (c != null) { for (int k = 0; k < c.length; k++) { if (c[k] instanceof IContainer) { unmarkTeamPrivate((IContainer) c[k]); } if (c[k].isTeamPrivateMember()) { if (GitTraceLocation.CORE.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.CORE.getLocation(), "notTeamPrivate " + c[k]); c[k].setTeamPrivateMember(false); } } } }
Source:
<code>public void loadPreviewImage(JLabel bp, Entity entity, IPlayer player) { Image camo = CamoManager.getPlayerCamoImage(player); <START> if (entity.getCamoCategory() != null && !entity.getCamoCategory().equals(IPlayer.NO_CAMO)) { <END> camo = CamoManager.getEntityCamoImage(entity); } int tint = PlayerColors.getColorRGB(player.getColorIndex()); Image icon = bv.getTilesetManager().loadPreviewImage(entity, camo, tint, bp); if (icon != null) { bp.setIcon(new ImageIcon(icon)); } else { bp.setIcon(null); } }</code><technical_language>suggestion if ((entity.getCamoCategory() != null) && !entity.getCamoCategory().equals(IPlayer.NO_CAMO)) {</technical_language>

Target:
public void loadPreviewImage(JLabel bp, Entity entity, IPlayer player) { Image camo = CamoManager.getPlayerCamoImage(player); if ((entity.getCamoCategory() != null) && !entity.getCamoCategory().equals(IPlayer.NO_CAMO)) { camo = CamoManager.getEntityCamoImage(entity); } int tint = PlayerColors.getColorRGB(player.getColorIndex()); Image icon = bv.getTilesetManager().loadPreviewImage(entity, camo, tint, bp); if (icon != null) { bp.setIcon(new ImageIcon(icon)); } else { bp.setIcon(null); } }
Source:
<code>protected static void validateUpsertConfig(TableConfig tableConfig, Schema schema) { if (tableConfig.getUpsertMode() == UpsertConfig.Mode.NONE) { return; } Preconditions .checkState(tableConfig.getTableType() == TableType.REALTIME, "Upsert table is for realtime table only."); Preconditions.checkState(CollectionUtils.isNotEmpty(schema.getPrimaryKeyColumns()), "Upsert table must have primary key columns in the schema"); Preconditions.checkState( tableConfig.getIndexingConfig() != null && tableConfig.getIndexingConfig().getStreamConfigs() != null, "streamConfig must exist in the table config"); StreamConfig streamConfig = new StreamConfig(tableConfig.getTableName(), tableConfig.getIndexingConfig().getStreamConfigs()); Preconditions.checkState(streamConfig.hasLowLevelConsumerType() && !streamConfig.hasHighLevelConsumerType(), "Upsert table must use low-level streaming consumer type"); Preconditions.checkState( tableConfig.getRoutingConfig() != null && RoutingConfig.REPLICA_GROUP_INSTANCE_SELECTOR_TYPE .equalsIgnoreCase(tableConfig.getRoutingConfig().getInstanceSelectorType()), "Upsert table must use replica-group (i.e. replicaGroup) based routing"); Preconditions.checkState( <START> tableConfig.getIndexingConfig().getStarTreeIndexConfigs() == null || tableConfig.getIndexingConfig() .getStarTreeIndexConfigs().isEmpty(), "The upsert table cannot have star-tree index."); <END> }</code><technical_language>suggestion Collections.isEmpty(tableConfig.getIndexingConfig().getStarTreeIndexConfigs()) && !tableConfig.getIndexingConfig().isEnableDefaultStarTree(), "The upsert table star-tree index.");</technical_language>

Target:
protected static void validateUpsertConfig(TableConfig tableConfig, Schema schema) { if (tableConfig.getUpsertMode() == UpsertConfig.Mode.NONE) { return; } Preconditions .checkState(tableConfig.getTableType() == TableType.REALTIME, "Upsert table is for realtime table only."); Preconditions.checkState(CollectionUtils.isNotEmpty(schema.getPrimaryKeyColumns()), "Upsert table must have primary key columns in the schema"); Preconditions.checkState( tableConfig.getIndexingConfig() != null && tableConfig.getIndexingConfig().getStreamConfigs() != null, "streamConfig must exist in the table config"); StreamConfig streamConfig = new StreamConfig(tableConfig.getTableName(), tableConfig.getIndexingConfig().getStreamConfigs()); Preconditions.checkState(streamConfig.hasLowLevelConsumerType() && !streamConfig.hasHighLevelConsumerType(), "Upsert table must use low-level streaming consumer type"); Preconditions.checkState( tableConfig.getRoutingConfig() != null && RoutingConfig.REPLICA_GROUP_INSTANCE_SELECTOR_TYPE .equalsIgnoreCase(tableConfig.getRoutingConfig().getInstanceSelectorType()), "Upsert table must use replica-group (i.e. replicaGroup) based routing"); Preconditions.checkState( CollectionUtils.isEmpty(tableConfig.getIndexingConfig().getStarTreeIndexConfigs()) && !tableConfig .getIndexingConfig().isEnableDefaultStarTree(), "The upsert table cannot have star-tree index."); }
Source:
<code>public void createObjectWithUserMetadata() throws Exception { Form form = new Form().param("name", bucketName); Response response = target("/buckets").request(MediaType.APPLICATION_JSON_TYPE).post(Entity.form(form)); assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); response = target("/objects").request() .post(Entity.entity(new FormDataMultiPart() .field("bucketName", bucketName).field("create", "new") .field("key", "object1").field("contentType", "text/plain") .field("timestamp", "2012-09-08 11:00:00") .field("userMetadata", VALID_USER_METADATA) .field("file", testData1, MediaType.TEXT_PLAIN_TYPE), MediaType.MULTIPART_FORM_DATA )); assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); response = target("/objects/meta/" + bucketName).queryParam("key", "object1") .request(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .get(); JsonObject responseObj = gson.fromJson(response.readEntity(String.class), JsonElement.class).getAsJsonObject(); assertNotNull(responseObj); <START> assertEquals(VALID_USER_METADATA, responseObj.get("userMetadata").toString()); <END> }</code><technical_language>This is checking JSON objects represented exact string, strings while representing object. For example, whitespace different, order of keys in map. If upgraded Gson versions some implementation detail caused maps print keys in a order, this test break unexpectedly</technical_language>

Target:
public void createObjectWithUserMetadata() throws Exception { Form form = new Form().param("name", bucketName); Response response = target("/buckets").request(MediaType.APPLICATION_JSON_TYPE).post(Entity.form(form)); assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); response = target("/objects").request() .post(Entity.entity(new FormDataMultiPart() .field("bucketName", bucketName).field("create", "new") .field("key", "object1").field("contentType", "text/plain") .field("timestamp", "2012-09-08 11:00:00") .field("userMetadata", USER_METADATA) .field("file", testData1, MediaType.TEXT_PLAIN_TYPE), MediaType.MULTIPART_FORM_DATA )); assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); response = target("/objects/meta/" + bucketName).queryParam("key", "object1") .request(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE) .get(); JsonObject responseObj = gson.fromJson(response.readEntity(String.class), JsonElement.class).getAsJsonObject(); assertNotNull(responseObj); assertEquals(USER_METADATA, responseObj.get("userMetadata").getAsString()); }
Source:
<code>private static String fetchPrometheusUrl(Provider<KubevirtProviderProperties> provider) { OpenshiftApi api; Optional<V1Route> route = null; try { api = KubevirtUtils.getOpenshiftApi(provider); } catch (IOException e) { log.error("failed to connect to openshift for kubevirt provider (url = {}): {}", provider.getUrl(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); return null; } try { V1RouteList routes = api.listNamespacedRoute("openshift-monitoring", null, "metadata.name=prometheus-k8s", null, null, null, null, null, Boolean.FALSE); route = routes.getItems().stream().findAny(); } catch (ApiException e) { log.error("failed to retrieve prometheus url for kubevirt provider (url = {}): {}", provider.getUrl(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); } if (route != null && route.isPresent()) { String <START> host = <END> route.get().getSpec().getHost(); try { return new URI("https", host, null, null).toString(); } catch (URISyntaxException e) { log.error("failed to retrieve prometheus url for kubevirt provider (url = {}): {}", provider.getUrl(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); } } return null; }</code><technical_language>add of 'host' error message in case of URISyntaxException</technical_language>

Target:
private static String fetchPrometheusUrl(Provider<KubevirtProviderProperties> provider) { OpenshiftApi api; Optional<V1Route> route = null; try { api = KubevirtUtils.getOpenshiftApi(provider); } catch (IOException e) { log.error("failed to connect to openshift for kubevirt provider (url = {}): {}", provider.getUrl(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); return null; } try { V1RouteList routes = api.listNamespacedRoute("openshift-monitoring", null, "metadata.name=prometheus-k8s", null, null, null, null, null, Boolean.FALSE); route = routes.getItems().stream().findAny(); } catch (ApiException e) { log.error("failed to retrieve prometheus url for kubevirt provider (url = {}): {}", provider.getUrl(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); } if (route != null && route.isPresent()) { String host = route.get().getSpec().getHost(); try { return new URI("https", host, null, null).toString(); } catch (URISyntaxException e) { log.error("Failed to retrieve prometheus url for kubevirt provider (host = {}, url = {}): {}", host, provider.getUrl(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); } } return null; }