auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void parseProperties() { for(String arg : getUsageArguments()) { ParserArgument argument = new ParserArgument(); argument.setName( getArgAttrValue(arg, "name") ); if (argument.getName() == null) { throw new IllegalArgumentException( String.format("Invalid configuration. Parameter '%1$s' has no name", arg) ); } argument.setMetavar( getArgAttrValue(arg, "metavar") ); argument.setHelp( getArgAttrValue(arg, "help") ); argument.setDefaultValue( getArgAttrValue(arg, "default") ); argument.setMultivalue( Boolean.parseBoolean( getArgAttrValue(arg, "multivalue") ) ); argument.setMandatory( Boolean.parseBoolean( getArgAttrValue(arg, "mandatory") ) ); argument.setType( ParametersParser.ArgumentType.valueOf( getArgAttrValue(arg, "type") ) ); argument.setMatcher( Pattern.compile( getArgAttrValue(arg, "matcher") ) ); try { argument.setConvert( argument.getType() != ArgumentType.no_argument ? <START> Boolean.class <END> : Class.forName( getArgAttrValue(arg, "convert"), true, Thread.currentThread().getContextClassLoader() ) ); } catch (ClassNotFoundException ex) { throw new IllegalArgumentException( String.format("Can't convert argument: '%1$s'. Please check convert class in properties file.", arg) ); } if (argument.isMandatory()) { mandatory.add(argument.getName()); } if (argument.getDefaultValue() != null) { defaults.add(String.format("%1$s%2$s=%3$s", LONG_PREFIX, argument.getName(), argument.getDefaultValue())); } arguments.put(argument.getName(), argument); } }</code><technical_language>this set user</technical_language>

Target:
private void parseProperties() { for(String arg : getUsageArguments()) { ParserArgument argument = new ParserArgument(); argument.setName( getArgAttrValue(arg, "name") ); if (argument.getName() == null) { throw new IllegalArgumentException( String.format("Invalid configuration. Parameter '%1$s' has no name", arg) ); } argument.setMetavar( getArgAttrValue(arg, "metavar") ); argument.setHelp( getArgAttrValue(arg, "help") ); argument.setDefaultValue( getArgAttrValue(arg, "default") ); argument.setMultivalue( Boolean.parseBoolean( getArgAttrValue(arg, "multivalue") ) ); argument.setValue( Boolean.parseBoolean( getArgAttrValue(arg, "value") ) ); argument.setMandatory( Boolean.parseBoolean( getArgAttrValue(arg, "mandatory") ) ); argument.setType( ParametersParser.ArgumentType.valueOf( getArgAttrValue(arg, "type") ) ); argument.setMatcher( Pattern.compile( getArgAttrValue(arg, "matcher") ) ); try { argument.setConvert( Class.forName( getArgAttrValue(arg, "convert"), true, Thread.currentThread().getContextClassLoader() ) ); } catch (ClassNotFoundException ex) { throw new IllegalArgumentException( String.format("Can't convert argument: '%1$s'. Please check convert class in properties file.", arg) ); } if (argument.isMandatory()) { mandatory.add(argument.getName()); } arguments.put(argument.getName(), argument); } }
Source:
<code>private boolean hasPermission(String sid, Permission p, RoleType roleType, AccessControlled controlledItem) { for(Role role : getRolesHavingPermission(p)) { if(this.grantedRoles.get(role).contains(sid)) { if (Macro.isMacro(role)) { Macro macro = RoleMacroExtension.getMacro(role.getName()); if (macro != null) { RoleMacroExtension macroExtension = RoleMacroExtension.getMacroExtension(macro.getName()); if (macroExtension.IsApplicable(roleType) && macroExtension.hasPermission(sid, p, roleType, controlledItem, macro)) { return true; } } } else { return true; } } else { try { UserDetails userDetails = Jenkins.getInstance().getSecurityRealm().loadUserByUsername(sid); for (GrantedAuthority grantedAuthority : userDetails.getAuthorities()) { if (grantedAuthority.getAuthority().equals(role.getName())) { return true; } } <START> } catch (Exception e) <END> } } return false; }</code><technical_language>logging</technical_language>

Target:
private boolean hasPermission(String sid, Permission p, RoleType roleType, AccessControlled controlledItem) { for(Role role : getRolesHavingPermission(p)) { if(this.grantedRoles.get(role).contains(sid)) { if (Macro.isMacro(role)) { Macro macro = RoleMacroExtension.getMacro(role.getName()); if (macro != null) { RoleMacroExtension macroExtension = RoleMacroExtension.getMacroExtension(macro.getName()); if (macroExtension.IsApplicable(roleType) && macroExtension.hasPermission(sid, p, roleType, controlledItem, macro)) { return true; } } } else { return true; } } else { try { UserDetails userDetails = cache.getIfPresent(sid); if (userDetails == null) { userDetails = Jenkins.getInstance().getSecurityRealm().loadUserByUsername(sid); cache.put(sid, userDetails); } for (GrantedAuthority grantedAuthority : userDetails.getAuthorities()) { if (grantedAuthority.getAuthority().equals(role.getName())) { return true; } } } catch (BadCredentialsException e) { LOGGER.log(Level.FINE, "Bad credentials", e); } catch (DataAccessException e) { LOGGER.log(Level.FINE, "failed to access the data", e); } } } return false; }
Source:
<code>public int deleteEventsBefore(long time) { final SQLiteDatabase db = this.helper.getWritableDatabase(); final String whereClause = "date < ?"; final int endDay = this.getDay(time); final String dayString = Integer.toString(endDay, 10); final String[] whereArgs = new String[] {dayString}; int numRowsDeleted = db.delete(EVENTS_TEXTUAL, whereClause, whereArgs); <START> numRowsDeleted += db.delete(EVENTS_INTEGER, whereClause, whereArgs); <END> return numRowsDeleted; }</code><technical_language>good put lines in a transaction. sense making expensive operation more expensive..</technical_language>

Target:
public int deleteEventsBefore(long time) { final SQLiteDatabase db = this.helper.getWritableDatabase(); final String whereClause = "date < ?"; final int endDay = this.getDay(time); final String dayString = Integer.toString(endDay, 10); final String[] whereArgs = new String[] {dayString}; int numRowsDeleted = 0; db.beginTransaction(); try { numRowsDeleted += db.delete(EVENTS_TEXTUAL, whereClause, whereArgs); numRowsDeleted += db.delete(EVENTS_INTEGER, whereClause, whereArgs); db.setTransactionSuccessful(); } finally { db.endTransaction(); } return numRowsDeleted; }
Source:
<code>private void formatAllowableHeaders(Set<String> allowedHeaderNames, HttpHeaders requestResponseHeaders, ClientLogger logger) { if (!allowedHeaderNames.isEmpty()) { StringBuilder sb = new StringBuilder(); for (HttpHeader header : requestResponseHeaders) { <START> sb.append(header.getName()).append(":"); <END> if (allowedHeaderNames.contains(header.getName())) { sb.append(header.getValue()); } else { sb.append(REDACTED_PLACEHOLDER); } sb.append(System.getProperty("line.separator")); } logger.info(sb.toString()); } }</code><technical_language>This case insensitive</technical_language>

Target:
private void formatAllowableHeaders(Set<String> allowedHeaderNames, HttpHeaders requestResponseHeaders, ClientLogger logger) { if (!allowedHeaderNames.isEmpty()) { StringBuilder sb = new StringBuilder(); for (HttpHeader header : requestResponseHeaders) { sb.append(header.getName()).append(":"); if (allowedHeaderNames.stream().anyMatch(header.getName()::equalsIgnoreCase)) { sb.append(header.getValue()); } else { sb.append(REDACTED_PLACEHOLDER); } sb.append(System.getProperty("line.separator")); } logger.info(sb.toString()); } }
Source:
<code>private boolean parsePath(Parser parser, List<Class<? extends Edge>> path) { boolean accept = false; <START> int currentState = 0; <END> for (Class<? extends Edge> edgeClass : path) { State state = mock(State.class); Edge edge = mock(edgeClass); when(state.getBackEdge()).thenReturn(edge); int terminal = parser.terminalFor(state); currentState = parser.transition(currentState, terminal); if (currentState == AutomatonState.REJECT) { return false; } } if (parser.accepts(currentState)) { accept = true; } return accept; }</code><technical_language>symbolic constant AutomatonState.START for clarity</technical_language>

Target:
private boolean parsePath(Parser parser, List<Class<? extends Edge>> path) { boolean accepted = false; int currentState = AutomatonState.START; for (Class<? extends Edge> edgeClass : path) { State state = mock(State.class); Edge edge = mock(edgeClass); when(state.getBackEdge()).thenReturn(edge); int terminal = parser.terminalFor(state); currentState = parser.transition(currentState, terminal); if (currentState == AutomatonState.REJECT) { return false; } } if (parser.accepts(currentState)) { accepted = true; } return accepted; }
Source:
<code>private Instant convertToDateTime(Object value) { try { return value != null ? Instant.ofEpochMilli(Double.valueOf(value.toString()).longValue()) : null; } catch (NumberFormatException e) { <START> throw new ValueConversionException(value, DATE_TIME, e); <END> } }</code><technical_language>Nice! (times n)</technical_language>

Target:
private Instant convertToDateTime(Object value) { try { return value != null ? Instant.ofEpochMilli(Double.valueOf(value.toString()).longValue()) : null; } catch (NumberFormatException e) { throw new AlgorithmValueConversionException(value, DATE_TIME, e); } }
Source:
<code>public Response start(Action action) { <START> RunVmOnceParams params = map(get(), new RunVmOnceParams(guid)); <END> if (action.isSetVm()) { validateEnums(VM.class, action.getVm()); VM vm = action.getVm(); params = map(vm, params); if (vm.isSetPlacementPolicy() && vm.getPlacementPolicy().isSetHost()) { validateParameters(vm.getPlacementPolicy(), "host.id|name"); params.setDestinationVdsId(getHostId(vm.getPlacementPolicy().getHost())); } } if (action.isSetPause() && action.isPause()) { params.setRunAndPause(true); } return doAction(VdcActionType.RunVmOnce, setReinitializeSysPrep(params), action); }</code><technical_language>get() invoke additional queries backend retrieve Payload Ballooning, while Payload huge 64k, do need Ballooning run vm, instead please run GetVmById query manually</technical_language>

Target:
public Response start(Action action) { RunVmOnceParams params = map(map(getEntity(entityType, VdcQueryType.GetVmByVmId, new GetVmByVmIdParameters(guid), id, true), new VM()), new RunVmOnceParams(guid)); if (action.isSetVm()) { validateEnums(VM.class, action.getVm()); VM vm = action.getVm(); params = map(vm, params); if (vm.isSetPlacementPolicy() && vm.getPlacementPolicy().isSetHost()) { validateParameters(vm.getPlacementPolicy(), "host.id|name"); params.setDestinationVdsId(getHostId(vm.getPlacementPolicy().getHost())); } } if (action.isSetPause() && action.isPause()) { params.setRunAndPause(true); } return doAction(VdcActionType.RunVmOnce, setReinitializeSysPrep(params), action); }
Source:
<code>public void testConfigValidations() { final KafkaSystemConsumer consumer = setupConsumer(FETCH_THRESHOLD_MSGS, FETCH_THRESHOLD_BYTES); <START> consumer.start(); <END> }</code><technical_language>stop consumer prevent leaking Consumers tests</technical_language>

Target:
public void testConfigValidations() { final KafkaSystemConsumer consumer = createConsumer(FETCH_THRESHOLD_MSGS, FETCH_THRESHOLD_BYTES); consumer.start(); }
Source:
<code>public String getDisplayName() { if (isAttributeExist(SCIMConstants.RoleSchemaConstants.DISPLAY_NAME)) { return LambdaExceptionUtils.rethrowSupplier( () -> ((SimpleAttribute) attributeList.get(SCIMConstants.RoleSchemaConstants.DISPLAY_NAME)) .getStringValue()).get(); <START> } else { <END> return null; } }</code><technical_language>return null; else</technical_language>

Target:
public String getDisplayName() { if (isAttributeExist(SCIMConstants.RoleSchemaConstants.DISPLAY_NAME)) { return LambdaExceptionUtils.rethrowSupplier( () -> ((SimpleAttribute) attributeList.get(SCIMConstants.RoleSchemaConstants.DISPLAY_NAME)) .getStringValue()).get(); } return null; }
Source:
<code>public static InetSocketAddress getRMWebAddress(Configuration conf, boolean sslEnabled, String rmId) { boolean isHA = (rmId != null); rmId = isHA ? ("." + rmId) : ""; if (isHA) { conf = getYarnConfiguration(conf); conf.set(ConfigUtils.RM_HA_ID, rmId); } InetSocketAddress address; if (sslEnabled) { address = conf.getSocketAddr(YarnConfiguration.RM_WEBAPP_HTTPS_ADDRESS + rmId, YarnConfiguration.DEFAULT_RM_WEBAPP_HTTPS_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_HTTPS_PORT); } else { address = conf.getSocketAddr(YarnConfiguration.RM_WEBAPP_ADDRESS + rmId, YarnConfiguration.DEFAULT_RM_WEBAPP_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_PORT); } if (isHA) { conf.unset(ConfigUtils.RM_HA_ID); } <START> LOG.info("rm webapp address setting {}", address); <END> LOG.debug("rm setting sources {}", conf.getPropertySources(YarnConfiguration.RM_WEBAPP_ADDRESS)); InetSocketAddress resolvedSocketAddress = NetUtils.getConnectAddress(address); InetAddress resolved = resolvedSocketAddress.getAddress(); if (resolved == null || resolved.isAnyLocalAddress() || resolved.isLoopbackAddress()) { try { resolvedSocketAddress = InetSocketAddress.createUnresolved(InetAddress.getLocalHost().getCanonicalHostName(), address.getPort()); } catch (UnknownHostException e) { } } return resolvedSocketAddress; }</code><technical_language>conf.set conf.unset combo expected behavior if getRMWebAddress() is called multiple threads time</technical_language>

Target:
public static InetSocketAddress getRMWebAddress(Configuration conf, boolean sslEnabled, String rmId) { boolean isHA = (rmId != null); if (isHA) { conf = getYarnConfiguration(conf); conf.set(ConfigUtils.RM_HA_ID, rmId); } InetSocketAddress address; if (sslEnabled) { address = conf.getSocketAddr(YarnConfiguration.RM_WEBAPP_HTTPS_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_HTTPS_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_HTTPS_PORT); } else { address = conf.getSocketAddr(YarnConfiguration.RM_WEBAPP_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_ADDRESS, YarnConfiguration.DEFAULT_RM_WEBAPP_PORT); } if (isHA) { conf.unset(ConfigUtils.RM_HA_ID); } LOG.info("rm webapp address setting {}", address); LOG.debug("rm setting sources {}", conf.getPropertySources(YarnConfiguration.RM_WEBAPP_ADDRESS)); InetSocketAddress resolvedSocketAddress = NetUtils.getConnectAddress(address); InetAddress resolved = resolvedSocketAddress.getAddress(); if (resolved == null || resolved.isAnyLocalAddress() || resolved.isLoopbackAddress()) { try { resolvedSocketAddress = InetSocketAddress.createUnresolved(InetAddress.getLocalHost().getCanonicalHostName(), address.getPort()); } catch (UnknownHostException e) { } } return resolvedSocketAddress; }
Source:
<code>private static String getLocalCanonicalHostName() { try { return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase(Locale.US); } catch (UnknownHostException e) { <START> throw new RuntimeException(e); <END> } }</code><technical_language>UncheckedIOException</technical_language>

Target:
private static String getLocalCanonicalHostName() { try { return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase(Locale.US); } catch (UnknownHostException e) { throw new UncheckedIOException(e); } }
Source:
<code><START> public AdvanceResult advanceNursery(final AdvancingNursery advanceInfo, final Workbook workbook) throws RuleException, MiddlewareQueryException, FieldbookException { <END> return this.namingConventionService.advanceNursery(advanceInfo, workbook); }</code><technical_language>MiddlewareQueryException is a run time exception is required part of method signature. invalid in signature, Sonar report a _Major_ category violation</technical_language>

Target:
public AdvanceResult advanceNursery(final AdvancingNursery advanceInfo, final Workbook workbook) throws RuleException, FieldbookException { return this.namingConventionService.advanceNursery(advanceInfo, workbook); }
Source:
<code>public void testFollow() { TmfTraceManager traceManager = TmfTraceManager.getInstance(); ITmfTrace ust = traceManager.getActiveTrace(); assertNotNull(ust); ITmfTrace kernelTest = CtfTmfTestTraceUtils.getTrace(CtfTestTrace.CONTEXT_SWITCHES_KERNEL); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, kernelTest.getPath(), TRACETYPE_ID); SWTBotEditor kernelEditor = SWTBotUtils.activateEditor(fBot, kernelTest.getName()); fBot.editorByTitle(kernelTest.getName()); ITmfTrace kernel = traceManager.getActiveTrace(); assertNotNull(kernel); SWTBotTable kernelEventTable = kernelEditor.bot().table(); SWTBotTableItem kernelEvent = kernelEventTable.getTableItem(5); kernelEvent.contextMenu("Follow time updates from other traces").click(); SWTBotUtils.activateEditor(fBot, ust.getName()); TmfTimeRange r = updateTimeRange(ust, UST_START + SECOND, UST_START + 2 * SECOND); IWorkbenchPart part = fOriginalViewBot.getViewReference().getPart(false); assertTrue(part instanceof AbstractTimeGraphView); AbstractTimeGraphView abstractTimeGraphView = (AbstractTimeGraphView) part; fBot.waitUntil(new PinAndCloneCondition(abstractTimeGraphView, ust, r)); <START> <END> SWTBotUtils.activateEditor(fBot, kernel.getName()); fBot.waitUntil(new PinAndCloneCondition(abstractTimeGraphView, kernel, r)); kernelTest.dispose(); }</code><technical_language>// assert (other|kernel|target|following)? trace changed</technical_language>

Target:
public void testFollow() { TmfTraceManager traceManager = TmfTraceManager.getInstance(); ITmfTrace ust = traceManager.getActiveTrace(); assertNotNull(ust); ITmfTrace kernelTest = CtfTmfTestTraceUtils.getTrace(CtfTestTrace.CONTEXT_SWITCHES_KERNEL); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, kernelTest.getPath(), TRACETYPE_ID); SWTBotEditor kernelEditor = SWTBotUtils.activateEditor(fBot, kernelTest.getName()); fBot.editorByTitle(kernelTest.getName()); ITmfTrace kernel = traceManager.getActiveTrace(); assertNotNull(kernel); SWTBotTable kernelEventTable = kernelEditor.bot().table(); SWTBotTableItem kernelEvent = kernelEventTable.getTableItem(5); kernelEvent.contextMenu("Follow time updates from other traces").click(); SWTBotUtils.activateEditor(fBot, ust.getName()); TmfSignalManager.dispatchSignal(new TmfWindowRangeUpdatedSignal(this, RANGE, ust)); IWorkbenchPart part = fOriginalViewBot.getViewReference().getPart(false); assertTrue(part instanceof AbstractTimeGraphView); AbstractTimeGraphView abstractTimeGraphView = (AbstractTimeGraphView) part; fBot.waitUntil(new PinAndCloneCondition(abstractTimeGraphView, ust, RANGE)); SWTBotUtils.activateEditor(fBot, kernel.getName()); fBot.waitUntil(new PinAndCloneCondition(abstractTimeGraphView, kernel, RANGE)); kernelTest.dispose(); }
Source:
<code>public boolean isCorrectRequiredValue(ValueResult result) { if (result == null || !result.isValueDefined()) { return false; } final String value = result.getValueObject(); final boolean correct; final TextAreaType type = TextAreaType.fromCode(getType()); if (type == TextAreaType.DATE) { correct = isCorrectRequiredDateValue(value); } else if (type == TextAreaType.NUMBER) { correct = isCorrectRequiredNumberValue(value); } else { correct = isCorrectRequiredStringValue(value); <START> } <END> return correct; }</code><technical_language>@Raphcal, future-proof introducing else if (type == TextAreaType.TEXT || type == TextAreaType.PARAGRAPH) a violent catchall else { // throw }. In swith cases else if enumeration, ask explicitly a catchall (ie default a global else) do pertinent if add element enum</technical_language>

Target:
public boolean isCorrectRequiredValue(ValueResult result) { if (result == null || !result.isValueDefined()) { return false; } final String value = result.getValueObject(); final boolean correct; final TextAreaType type = TextAreaType.fromCode(getType()); if (type != null) switch (type) { case DATE: correct = isCorrectRequiredDateValue(value); break; case NUMBER: correct = isCorrectRequiredNumberValue(value); break; case PARAGRAPH: case TEXT: correct = isCorrectRequiredStringValue(value); break; default: throw new UnsupportedOperationException("Given type '" + type + "' is not supported yet."); } else { Log.warn("No textarea type is specified for the textarea element '" + getLabel() + "'. Using paragraph instead."); correct = isCorrectRequiredStringValue(value); } return correct; }
Source:
<code><START> public static ByteBuffer enlargeBuffer(ByteBuffer buffer, final int sessionProposedCapacity) { <END> if (sessionProposedCapacity > buffer.capacity()) { buffer = ByteBuffer.allocate(sessionProposedCapacity); } else { buffer = ByteBuffer.allocate(buffer.capacity() * 2); } return buffer; }</code><technical_language>Add Preconditions.checkArgument checks verify passed buffer is null sessionProposedCapacity is greater zero</technical_language>

Target:
public static ByteBuffer enlargeBuffer(ByteBuffer buffer, final int sessionProposedCapacity) { if (buffer == null || sessionProposedCapacity < 0) { return buffer; } if (sessionProposedCapacity > buffer.capacity()) { buffer = ByteBuffer.allocate(sessionProposedCapacity); } else { buffer = ByteBuffer.allocate(buffer.capacity() * 2); } return buffer; }
Source:
<code><START> protected void addWorkerToIdleChain(Worker worker) { <END> while (true) { Worker casWorker = idleWorker.get(); worker.nextIdleWorker = casWorker; if (idleWorker.compareAndSet(casWorker, worker)) { break; } } }</code><technical_language>Interesting design. this run issues spinning a lot idleWorker is a lot of contention</technical_language>

Target:
protected void addWorkerToIdleChain(Worker worker) { idleWorkerCount.incrementAndGet(); while (true) { Worker casWorker = idleWorker.get(); worker.nextIdleWorker = casWorker; if (idleWorker.compareAndSet(casWorker, worker)) { break; } } }
Source:
<code>public void send(DatastreamProducerRecord record, SendCallback sendCallback) { try { validateEventRecord(record); record.serializeEvents(_datastreamTask.getDestinationSerDes()); String destination = record.getDestination().orElse(_datastreamTask.getDatastreamDestination().getConnectionString()); record.setEventsSendTimestamp(System.currentTimeMillis()); _transportProvider.send(destination, record, <START> (metadata, exception) -> onSendCallback(metadata, exception, sendCallback, record)); <END> } catch (Exception e) { String errorMessage = String.format("Failed send the event %s exception %s", record, e); _logger.warn(errorMessage, e); if (_skipBadMessagesEnabled) { _logger.error("Skipping Message. task: ; error: {}", _datastreamTask, e); _dynamicMetricsManager.createOrUpdateCounter(MODULE, _datastreamName, SKIPPED_BAD_MESSAGES_RATE, 1); } else { throw new DatastreamRuntimeException(errorMessage, e); } } if (Instant.now().isAfter(_lastFlushTime.plus(_flushInterval))) { flush(); } }</code><technical_language>if toString() of DatastreamProducerRecord, prints out partition id key. I this is good enough</technical_language>

Target:
public void send(DatastreamProducerRecord record, SendCallback sendCallback) { try { validateEventRecord(record); record.serializeEvents(_datastreamTask.getDestinationSerDes()); String destination = record.getDestination().orElse(_datastreamTask.getDatastreamDestination().getConnectionString()); record.setEventsSendTimestamp(System.currentTimeMillis()); _transportProvider.send(destination, record, (metadata, exception) -> onSendCallback(metadata, exception, sendCallback, record)); } catch (Exception e) { String errorMessage = String.format("Failed send the event %s exception %s", record, e); _logger.warn(errorMessage, e); if (_skipBadMessagesEnabled) { _logger.error("Skipping Message. task: ; error: {}", _datastreamTask, e); _dynamicMetricsManager.createOrUpdateCounter(MODULE, _datastreamName, SKIPPED_BAD_MESSAGES_COUNTER, 1); } else { throw new DatastreamRuntimeException(errorMessage, e); } } if (Instant.now().isAfter(_lastFlushTime.plus(_flushInterval))) { flush(); } }
Source:
<code>public void cancelSetupTotp() throws Exception { doAIA(); loginPage.login("test-user@localhost", "password"); totpPage.assertCurrent(); totpPage.cancel(); <START> assertRedirectSuccess(); <END> }</code><technical_language>Check error code/description</technical_language>

Target:
public void cancelSetupTotp() throws Exception { doAIA(); loginPage.login("test-user@localhost", "password"); totpPage.assertCurrent(); totpPage.cancel(); assertRedirectSuccess(); assertCancelMessage(); }
Source:
<code>Map<Class<?>, List<RunnerTestDescriptorAwareFilter>> resolve(EngineDiscoveryRequest request, Predicate<Class<?>> classFilter) { Map<Class<?>, List<RunnerTestDescriptorAwareFilter>> filteredTestClasses = new LinkedHashMap<>(); BiConsumer<Class<?>, RunnerTestDescriptorAwareFilter> addFilter = (testClass, <START> filter) -> filteredTestClasses.computeIfAbsent(testClass, key -> new LinkedList<>()).add(filter); <END> methodSelectorResolver.resolve(request, classFilter, addFilter); uniqueIdSelectorResolver.resolve(request, classFilter, addFilter); return filteredTestClasses; }</code><technical_language>@stefanbirkner I question LinkedList here, I understand ArrayList, main alternative, performs modern hardware exploit processor caches due array internally, LinkedList due pointers</technical_language>

Target:
Map<Class<?>, List<RunnerTestDescriptorAwareFilter>> resolve(EngineDiscoveryRequest request, Predicate<Class<?>> classFilter) { Map<Class<?>, List<RunnerTestDescriptorAwareFilter>> filteredTestClasses = new LinkedHashMap<>(); BiConsumer<Class<?>, RunnerTestDescriptorAwareFilter> addFilter = (testClass, filter) -> filteredTestClasses.computeIfAbsent(testClass, key -> new ArrayList<>()).add(filter); methodSelectorResolver.resolve(request, classFilter, addFilter); uniqueIdSelectorResolver.resolve(request, classFilter, addFilter); return filteredTestClasses; }
Source:
<code>public void testOnActiveFilterAdded() { ActiveFilterItem testActiveFilterItem = new ActiveFilterItem(Constants.INSTANCE.State(), "test lable", null, Arrays.asList("Active"), null); presenter.onActiveFilterAdded(testActiveFilterItem); verify(getView()).checkSelectFilter(Constants.INSTANCE.State(), "Active"); <START> ActiveFilterItem activeWithErrorsFilterItem = new ActiveFilterItem("errorCount", "test lable", null, Arrays.asList("0"), null); <END> presenter.onActiveFilterAdded(activeWithErrorsFilterItem); verify(getView()).checkSelectFilter(Constants.INSTANCE.Errors(), "true"); ActiveFilterItem activeWithoutErrorsFilterItem = new ActiveFilterItem("errorCount", "test lable", null, Arrays.asList("1"), null); presenter.onActiveFilterAdded(activeWithoutErrorsFilterItem); verify(getView()).checkSelectFilter(Constants.INSTANCE.Errors(), "false"); }</code><technical_language>lable->label</technical_language>

Target:
public void testOnActiveFilterAdded() { ActiveFilterItem testActiveFilterItem = new ActiveFilterItem(Constants.INSTANCE.State(), "test label", null, Arrays.asList("Active"), null); presenter.onActiveFilterAdded(testActiveFilterItem); verify(getView()).checkSelectFilter(Constants.INSTANCE.State(), "Active"); ActiveFilterItem activeWithErrorsFilterItem = new ActiveFilterItem("errorCount", "test label", null, Arrays.asList("0"), null); presenter.onActiveFilterAdded(activeWithErrorsFilterItem); verify(getView()).checkSelectFilter(Constants.INSTANCE.Errors(), "0"); ActiveFilterItem activeWithoutErrorsFilterItem = new ActiveFilterItem("errorCount", "test label", null, Arrays.asList("1"), null); presenter.onActiveFilterAdded(activeWithoutErrorsFilterItem); verify(getView()).checkSelectFilter(Constants.INSTANCE.Errors(), "1"); }
Source:
<code>public String toString() { String version = ""; if (major != null) { version += String.valueOf(major); } if (minor != null) { String minorInString = String.valueOf(minor); if (minorInString.length() < 2) { <START> minorInString = "0" + minorInString; <END> } version += "." + minorInString; } if (patch != null) { version += "." + patch; } return version; }</code><technical_language>This means new Version("1-1").toString() 1.01? a bit odd it? parts strings (in fact entire string) convert numbers demand? Alternatively, store original string in addition numbers</technical_language>

Target:
public String toString() { return originalRepresentation.replace('-', '.'); }
Source:
<code>public Map<String, Object> getMetadata(@NonNull String section) { if (section != null) { return impl.getMetadata(section); } else { <START> error("getMetadata"); <END> return null; } }</code><technical_language>I logging sense for accessor method</technical_language>

Target:
public Map<String, Object> getMetadata(@NonNull String section) { if (section != null) { return impl.getMetadata(section); } else { logNull("getMetadata"); return null; } }
Source:
<code>public HadoopDruidIndexerConfig getHadoopDruidIndexerConfig() { if(config == null) { try { if (argumentSpec.startsWith("{")) { config = HadoopDruidIndexerConfig.fromString(argumentSpec); } else { <START> URI argumentSpecUri = new URI(argumentSpec); <END> String argumentSpecScheme = argumentSpecUri.getScheme(); if ((argumentSpecScheme == null) || argumentSpecScheme.equals("file")) { config = HadoopDruidIndexerConfig.fromFile(new File(argumentSpecUri.getPath())); } else { config = HadoopDruidIndexerConfig.fromDistributedFileSystem(argumentSpec); } } } catch (Exception e) { throw Throwables.propagate(e); } } return config; }</code><technical_language>argumentSpec is a valid URI, a simple path? paths . .. valid URIs</technical_language>

Target:
public HadoopDruidIndexerConfig getHadoopDruidIndexerConfig() { if(config == null) { try { if (argumentSpec.startsWith("{")) { config = HadoopDruidIndexerConfig.fromString(argumentSpec); } else { File localConfigFile = null; try { final URI argumentSpecUri = new URI(argumentSpec); final String argumentSpecScheme = argumentSpecUri.getScheme(); if (argumentSpecScheme == null || argumentSpecScheme.equals("file")) { localConfigFile = new File(argumentSpecUri.getPath()); } } catch (URISyntaxException e) { localConfigFile = new File(argumentSpec); } if (localConfigFile != null) { config = HadoopDruidIndexerConfig.fromFile(localConfigFile); } else { config = HadoopDruidIndexerConfig.fromDistributedFileSystem(argumentSpec); } } } catch (Exception e) { throw Throwables.propagate(e); } } return config; }
Source:
<code>public TimelineSyncImpl(final ZooKeeperHolder zooKeeperHolder, final UUIDGenerator uuidGenerator) { this.thisId = uuidGenerator.randomUUID().toString(); <START> this.log = LoggerFactory.getLogger("timelines.sync." + thisId); <END> this.zooKeeperHolder = zooKeeperHolder; this.initializeZkStructure(); }</code><technical_language>is idea of thisId including in log? I understand TimelineSyncImpl Nakadi instance. instance IP id avoid creating more case need map some ID instance IP</technical_language>

Target:
public TimelineSyncImpl(final ZooKeeperHolder zooKeeperHolder, final UUIDGenerator uuidGenerator) throws InterruptedException { this.nodeId = uuidGenerator.randomUUID().toString(); this.zooKeeperHolder = zooKeeperHolder; this.initializeZkStructure(); }
Source:
<code>public SourceConfiguration build() { final Set<String> remainingParams = new HashSet(); <START> requiredParameters.stream() <END> .filter(s -> !configMap.containsKey(s)) .forEach(s -> remainingParams.add(s)); if (!remainingParams.isEmpty()) { final StringBuilder stringBuilder = new StringBuilder("Missing Configuration for " + this.getClass().getName()); stringBuilder.append(": ["); remainingParams.stream() .forEach(s -> stringBuilder.append(s + ", ")); stringBuilder.append("]"); throw new IllegalStateException(stringBuilder.toString()); } return new DefaultSourceConfigurationImpl(configMap); }</code><technical_language>This code good me. clean this code, map.keySet(). get remainingParams .removeAll method in Set</technical_language>

Target:
public SourceConfiguration build() { Stream<String> missingParams = requiredParameters.stream() .filter(s -> !configMap.containsKey(s)); if (missingParams.count() > 0) { final StringBuilder stringBuilder = new StringBuilder("Missing Configuration for " + this.getClass().getName()); stringBuilder.append(": ["); missingParams .forEach(s -> stringBuilder.append(s + ", ")); stringBuilder.append("]"); throw new IllegalStateException(stringBuilder.toString()); } return new DefaultSourceConfigurationImpl(configMap); }
Source:
<code>public Response commitBranch(long branchUuid, long destinationBranchUuid, BranchCommitOptions options) { BranchReadable srcBranch = getBranchById(branchUuid); BranchReadable destBranch = getBranchById(destinationBranchUuid); ArtifactReadable committer = getArtifactById(COMMON_ID, options.getCommitterId()); Callable<TransactionReadable> op = getBranchOps().commitBranch(committer, srcBranch, destBranch); TransactionReadable tx = executeCallable(op); if (options.isArchive()) { Callable<?> op2 = getBranchOps().archiveUnarchiveBranch(srcBranch, ArchiveOperation.ARCHIVE); executeCallable(op2); } UriInfo uriInfo = getUriInfo(); URI location = getTxLocation(uriInfo, tx); <START> <END> activityLog.createEntry(BRANCH_OPERATION_TYPEID, ActivityLog.INITIAL_STATUS, String.format( "Branch Operation Commit Branch {branchUUID: %s srcBranch: %s destBranch: %s accountId: %s serverId: %s clientId: %s}", branchUuid, srcBranch.toString(), destBranch.toString(), accountId, serverId, clientId)); return Response.created(location).entity(asTransaction(tx)).build(); }</code><technical_language>try/catch</technical_language>

Target:
public Response commitBranch(long branchUuid, long destinationBranchUuid, BranchCommitOptions options) { BranchReadable srcBranch = getBranchById(branchUuid); BranchReadable destBranch = getBranchById(destinationBranchUuid); ArtifactReadable committer = getArtifactById(COMMON_ID, options.getCommitterId()); Callable<TransactionReadable> op = getBranchOps().commitBranch(committer, srcBranch, destBranch); TransactionReadable tx = executeCallable(op); if (options.isArchive()) { Callable<?> op2 = getBranchOps().archiveUnarchiveBranch(srcBranch, ArchiveOperation.ARCHIVE); executeCallable(op2); } UriInfo uriInfo = getUriInfo(); URI location = getTxLocation(uriInfo, tx); try { activityLog.createEntry(BRANCH_OPERATION_TYPEID, ActivityLog.INITIAL_STATUS, String.format( "Branch Operation Commit Branch {branchUUID: %s srcBranch: %s destBranch: %s accountId: %s serverId: %s clientId: %s}", branchUuid, srcBranch.toString(), destBranch.toString(), RestUtil.getAccountId(httpHeaders), RestUtil.getServerId(httpHeaders), RestUtil.getClientId(httpHeaders))); } catch (OseeCoreException ex) { OseeLog.log(ActivityLog.class, OseeLevel.SEVERE_POPUP, ex); } return Response.created(location).entity(asTransaction(tx)).build(); }
Source:
<code>protected void removeChildVisual(final EditPart childEditPart) { <START> boolean visible = true; if (childEditPart.getModel() instanceof AdapterDeclaration) { visible = isVarVisible(); } <END> if (childEditPart instanceof InterfaceEditPart){ if (((InterfaceEditPart) childEditPart).getModel().isIsInput()) { IFigure child = ((GraphicalEditPart) childEditPart).getFigure(); if (((InterfaceEditPart) childEditPart).isEvent()) { getLeftEventInterfaceContainer().remove(child); } else { if (visible) { getLeftVarInterfaceContainer().remove(child); } else{ getLeftInterfaceContainer().remove(child); } } } else { IFigure child = ((GraphicalEditPart) childEditPart).getFigure(); if (((InterfaceEditPart) childEditPart).isEvent()) { getRightEventInterfaceContainer().remove(child); } else { if (visible) { getRightVarInterfaceContainer().remove(child); } else { getRightInterfaceContainer().remove(child); } } } } else { super.removeChildVisual(childEditPart); } }</code><technical_language>readable if this moved isVarVisible function</technical_language>

Target:
protected void removeChildVisual(final EditPart childEditPart) { if (childEditPart instanceof InterfaceEditPart) { IFigure child = ((GraphicalEditPart) childEditPart).getFigure(); getChildVisualContainer(childEditPart).remove(child); } else { super.removeChildVisual(childEditPart); } }
Source:
<code>public ResponseEntity<?> getAppList() { <START> org.geoserver.platform.resource.Resource appRoot = scriptManager.app(); <END> List<Resource> apps = Resources.list(appRoot, Resources.DirectoryFilter.INSTANCE); JSONArray array = new JSONArray(); for (org.geoserver.platform.resource.Resource f : apps) { array.add(f.name()); } JSONObject obj = new JSONObject(); obj.put("scripts", array); return new ResponseEntity<String>(obj.toString(2), HttpStatus.OK); }</code><technical_language>I need full package anymore, importing Restlet Resource anymore</technical_language>

Target:
public ResponseEntity<?> getAppList() { Resource appRoot = scriptManager.app(); List<Resource> apps = Resources.list(appRoot, Resources.DirectoryFilter.INSTANCE); JSONArray array = new JSONArray(); for (Resource f : apps) { array.add(f.name()); } JSONObject obj = new JSONObject(); obj.put("scripts", array); return new ResponseEntity<String>(obj.toString(2), HttpStatus.OK); }
Source:
<code>protected void execute() { chassis.moveCartesian(controller.getX(), controller.getY(), controller.getTurnSpeed()); motorSpeeds = chassis.getMotorSpeeds(); StringBuilder motorSpeedsString = new StringBuilder(); motorSpeedsString.append("Motor speeds: "); for (int i = 0; i < motorSpins.length; i++) { LogKitten.d(Double.toString(motorSpeeds[i])); motorSpins[i].set(motorSpeeds[i]); motorSpeedsString.append(motorSpeeds[i]); <START> motorSpeedsString.append(' '); <END> } LogKitten.d("ChassisMove executing"); LogKitten.d(motorSpeedsString.toString()); }</code><technical_language>prevent a trailing space string, I move this previous line remove trailing space line 80</technical_language>

Target:
protected void execute() { chassis.moveCartesian(controller.getX(), controller.getY(), controller.getTurnSpeed()); motorSpeeds = chassis.getMotorSpeeds(); StringBuilder motorSpeedsString = new StringBuilder(); motorSpeedsString.append("Motor speeds:"); for (int i = 0; i < motorSpins.length; i++) { LogKitten.d(Double.toString(motorSpeeds[i])); motorSpins[i].set(motorSpeeds[i]); motorSpeedsString.append(' '); motorSpeedsString.append(motorSpeeds[i]); } LogKitten.d("ChassisMove executing"); LogKitten.d(motorSpeedsString.toString()); }
Source:
<code>private int openSocket(final int port) throws IOException { serverSocket = new ServerSocket(port); <START> String threadName = String.format("elasticjob-snapshot-service-%d", port); <END> new Thread(() -> { while (!closed) { try { process(serverSocket.accept()); } catch (final IOException ex) { if (isIgnoredException()) { return; } log.error("ElasticJob: Snapshot service open socket failure, error is: ", ex); } } }, threadName).start(); return serverSocket.getLocalPort(); }</code><technical_language>Thread name actual port</technical_language>

Target:
private int openSocket(final int port) throws IOException { serverSocket = new ServerSocket(port); int localPort = serverSocket.getLocalPort(); String threadName = String.format("elasticjob-snapshot-service-%d", localPort); new Thread(() -> { while (!closed) { try { process(serverSocket.accept()); } catch (final IOException ex) { if (isIgnoredException()) { return; } log.error("ElasticJob: Snapshot service open socket failure, error is: ", ex); } } }, threadName).start(); return localPort; }
Source:
<code>public Object evaluateOn(Object o, FunctionWithArgs f, boolean deepEvaluation) { if (f.getArgs()==null) throw new IllegalStateException("Invalid function-only expression '"+f.getFunction()+"'"); Class<?> clazz; if (o instanceof Class) { clazz = (Class<?>)o; } else { clazz = o.getClass(); } if (!(clazz.getPackage().getName().startsWith(BrooklynDslCommon.class.getPackage().getName()))) throw new IllegalArgumentException("Not permitted to invoke function on '"+clazz+"' (outside allowed package scope)"); String fn = f.getFunction(); fn = Strings.removeFromStart(fn, "$brooklyn:"); if (fn.startsWith("function.")) { for (Class<?> c : clazz.getClasses()) { if (c.equals(BrooklynDslCommon.Functions.class)) { <START> if (o instanceof Class) { <END> o = c; } break; } } fn = Strings.removeFromStart(fn, "function."); } try { List<Object> args = new ArrayList<Object>(); for (Object arg: f.getArgs()) { args.add( deepEvaluation ? evaluate(arg, true) : arg ); } Optional<Object> v = Reflections.invokeMethodWithArgs(o, fn, args); if (v.isPresent()) return v.get(); } catch (Exception e) { Exceptions.propagateIfFatal(e); throw Exceptions.propagate(new InvocationTargetException(e, "Error invoking '"+fn+"' on '"+o+"'")); } throw new IllegalArgumentException("No such function '"+fn+"' on "+o); }</code><technical_language>obvious why. do expect passed in (i.e. is o)? clazz a sub-type of (or concrete type) BrooklynDslCommon.Functions</technical_language>

Target:
public Object evaluateOn(Object o, FunctionWithArgs f, boolean deepEvaluation) { if (f.getArgs()==null) throw new IllegalStateException("Invalid function-only expression '"+f.getFunction()+"'"); Class<?> clazz; if (o instanceof Class) { clazz = (Class<?>)o; } else { clazz = o.getClass(); } if (!(clazz.getPackage().getName().startsWith(BrooklynDslCommon.class.getPackage().getName()))) throw new IllegalArgumentException("Not permitted to invoke function on '"+clazz+"' (outside allowed package scope)"); String fn = f.getFunction(); fn = Strings.removeFromStart(fn, "$brooklyn:"); if (fn.startsWith("function.")) { o = BrooklynDslCommon.Functions.class; fn = Strings.removeFromStart(fn, "function."); } try { List<Object> args = new ArrayList<>(); for (Object arg: f.getArgs()) { args.add( deepEvaluation ? evaluate(arg, true) : arg ); } Optional<Object> v = Reflections.invokeMethodWithArgs(o, fn, args); if (v.isPresent()) return v.get(); } catch (Exception e) { Exceptions.propagateIfFatal(e); throw Exceptions.propagate(new InvocationTargetException(e, "Error invoking '"+fn+"' on '"+o+"'")); } throw new IllegalArgumentException("No such function '"+fn+"' on "+o); }
Source:
<code>public void signalConnectionLost(final RtuDevice rtu) { LOGGER.info("Sending connection lost signal for device {}.", rtu.getDeviceIdentification()); final GetDataResponseDto dataResponse = new GetDataResponseDto(Arrays.asList(new GetDataSystemIdentifierDto( SYSTEM_ID, SYSTEM_TYPE, Arrays.asList(new MeasurementDto(MEASUREMENT_ID, MEASUREMENT_NODE, 0, <START> new DateTime(DateTimeZone.UTC), 1.0))))); <END> final String correlationUid = this.createCorrelationUid(rtu); final String organisationIdentification = rtu.getOwner().getOrganisationIdentification(); final String deviceIdentification = rtu.getDeviceIdentification(); this.adHocManagementService.handleGetDataResponse(dataResponse, deviceIdentification, organisationIdentification, correlationUid, DeviceFunction.GET_DATA.toString(), ResponseMessageResultType.OK, null); }</code><technical_language>Create a constant field a meaningful name for 1.0 increase readability/maintainability</technical_language>

Target:
public void signalConnectionLost(final RtuDevice rtu) { LOGGER.info("Sending connection lost signal for device {}.", rtu.getDeviceIdentification()); final GetDataResponseDto dataResponse = new GetDataResponseDto(Arrays.asList(new GetDataSystemIdentifierDto( SYSTEM_ID, SYSTEM_TYPE, Arrays.asList(new MeasurementDto(MEASUREMENT_ID, MEASUREMENT_NODE, 0, new DateTime(DateTimeZone.UTC), MEASUREMENT_VALUE_ALARM_ON))))); final String correlationUid = this.createCorrelationUid(rtu); final String organisationIdentification = rtu.getOwner().getOrganisationIdentification(); final String deviceIdentification = rtu.getDeviceIdentification(); this.adHocManagementService.handleGetDataResponse(dataResponse, deviceIdentification, organisationIdentification, correlationUid, DeviceFunction.GET_DATA.toString(), ResponseMessageResultType.OK, null); }
Source:
<code>public String executeNeo4jQuery(String queryName, Map<String, String> parameters, String returnType) throws AsyncExecutionException { String query = env.getProperty(queryName); if (parameters != null) { for (String paraName : parameters.keySet()) { <START> query = query.replace("{" + paraName + "}", "'"+parameters.get(paraName)+"'"); <END> } } logger.debug("Running query: " + query); ResponseEntity<String> response = executeQuery(query, returnType); HttpStatus status = response.getStatusCode(); String resbody = response.getBody(); if (status == HttpStatus.BAD_REQUEST || status == HttpStatus.INTERNAL_SERVER_ERROR) { String errorMessage = resbody.substring(resbody.indexOf("<message>"), resbody.indexOf("</message>")); throw new AsyncExecutionException(errorMessage); } QStoreAsyncResult asyncResult = getResponseFromXML(resbody); String pollURL = asyncResult.getPollurl(); long delay = Long.parseLong(env.getProperty("qstore.rest.delay")); String res = getQueryResult(pollURL); asyncResult = getResponseFromXML(res); while (asyncResult != null && asyncResult.getQueryStatus().equals(RUNNING.name())) { try { Thread.sleep(delay); res = getQueryResult(pollURL); asyncResult = getResponseFromXML(res); } catch (InterruptedException e) { throw new AsyncExecutionException(e); } } return asyncResult.getResult(); }</code><technical_language>pretty breaking other queries here. test that</technical_language>

Target:
public String executeNeo4jQuery(String queryName, Map<String, String> parameters, String returnType) throws AsyncExecutionException { String query = env.getProperty(queryName); if (parameters != null) { for (String paraName : parameters.keySet()) { query = query.replace("{" + paraName + "}", parameters.get(paraName)); } } logger.debug("Running query: " + query); ResponseEntity<String> response = executeQuery(query, returnType); HttpStatus status = response.getStatusCode(); String resbody = response.getBody(); if (status == HttpStatus.BAD_REQUEST || status == HttpStatus.INTERNAL_SERVER_ERROR) { String errorMessage = resbody.substring(resbody.indexOf("<message>"), resbody.indexOf("</message>")); throw new AsyncExecutionException(errorMessage); } QStoreAsyncResult asyncResult = getResponseFromXML(resbody); String pollURL = asyncResult.getPollurl(); long delay = Long.parseLong(env.getProperty("qstore.rest.delay")); String res = getQueryResult(pollURL); asyncResult = getResponseFromXML(res); while (asyncResult != null && asyncResult.getQueryStatus().equals(RUNNING.name())) { try { Thread.sleep(delay); res = getQueryResult(pollURL); asyncResult = getResponseFromXML(res); } catch (InterruptedException e) { throw new AsyncExecutionException(e); } } return asyncResult.getResult(); }
Source:
<code>public static void setDonationURL() { try { Class donationManager = Class.forName("openblocks.common.DonationURLManager"); Method instance = donationManager.getMethod("instance"); Method url = donationManager.getMethod("addUrl"); <START> url.invoke(instance.invoke(null),Reference.ID,"<LINK_0>"); <END> } catch (Exception e) { e.printStackTrace(); } }</code><technical_language>URL is "<LINK_1>", fyi</technical_language>

Target:
public static void setDonationURL() { try { Class donationManager = Class.forName("openblocks.common.DonationURLManager"); Method instance = donationManager.getMethod("instance"); Method url = donationManager.getMethod("addUrl"); url.invoke(instance.invoke(null),Reference.ID,"<LINK_1>"); } catch (Exception e) { e.printStackTrace(); } }
Source:
<code>public void shouldNotCloseTaskWithinCommitIfTaskMigratedException() { mockTaskInitialization(); EasyMock.expect(t1.commitNeeded()).andReturn(true); t1.commit(); EasyMock.expectLastCall().andThrow(new TaskMigratedException()); EasyMock.replay(t1); addAndInitTask(); try { assignedTasks.commit(); fail("Should have thrown TaskMigratedException."); <START> } catch (final TaskMigratedException expected) { <END> assertThat(assignedTasks.runningTaskIds(), equalTo(Collections.singleton(taskId1))); } EasyMock.verify(t1); }</code><technical_language>This logic simplified as: private void verifyExceptionalState(ThrowingRunnable action) { assertThrows(TaskMigratedException.class, action); // This task closed a zombie other tasks onPartitionsLost assertThat(assignedTasks.runningTaskIds(), equalTo(singleTaskId)); EasyMock.verify(t1); } new test needs put in intended action. singleTaskId is a class level parameter I defined replace singleton list, is highly required</technical_language>

Target:
public void shouldNotCloseTaskWithinCommitIfTaskMigratedException() { mockTaskInitialization(); EasyMock.expect(t1.commitNeeded()).andReturn(true); t1.commit(); EasyMock.expectLastCall().andThrow(new TaskMigratedException()); EasyMock.replay(t1); addAndInitTask(); verifyTaskMigratedExceptionDoesNotCloseTask( () -> assignedTasks.commit()); }