auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public <T> T createProxies( <START> ServiceDiscoveryConfiguration discoveryConfig, String serviceName, Class<T> serviceClass) { <END> Optional<ServiceConfiguration> maybeServiceConfig = discoveryConfig.getServiceConfiguration(serviceName); if (!maybeServiceConfig.isPresent()) { throw new RuntimeException("Unable to find the configuration for " + serviceName + "."); } return createProxies(maybeServiceConfig.get(), discoveryConfig.defaultSecurity(), serviceClass); }</code><technical_language>param in line</technical_language>

Target:
public <T> T createProxies( ServiceDiscoveryConfiguration discoveryConfig, String serviceName, Class<T> serviceClass) { ServiceConfiguration serviceConfig = Preconditions.checkNotNull( discoveryConfig.getServices().get(serviceName), "Unable to find the configuration for " + serviceName + "."); Optional<SSLSocketFactory> socketFactory = Optional.absent(); Optional<SslConfiguration> sslConfig = discoveryConfig.getSslConfiguration(serviceName); if (sslConfig.isPresent()) { socketFactory = Optional.of(SslSocketFactories.createSslSocketFactory(sslConfig.get())); } Set<String> uris = Sets.newHashSet(serviceConfig.uris()); return createProxy(socketFactory, uris, serviceClass); }
Source:
<code>boolean group() { if (!character('[')) { return false; } if (!range()) { return false; } CpuGroup group = new CpuGroup(); addCpuRangeToGroup(group); while (character(',')) { if (!range()) { return false; } addCpuRangeToGroup(group); } if (!character(']')) { return false; } if (character(':')) { if (!integer()) { return false; } group.threadCount = integer; if (group.threadCount == 0) { error("Thread count can't be 0."); } else if (group.threadCount > group.cpus.size()) { <START> error("Thread count be larger than number of cpu's in the group. " <END> + "Thread count = " + group.threadCount + " cpus:" + group.cpus); } } else { group.threadCount = group.cpus.size(); } groups.add(group); return true; }</code><technical_language>Missing "cannot"</technical_language>

Target:
boolean group() { if (!character('[')) { return false; } if (!range()) { return false; } CpuGroup group = new CpuGroup(); addCpuRangeToGroup(group); while (character(',')) { if (!range()) { return false; } addCpuRangeToGroup(group); } if (!character(']')) { return false; } if (character(':')) { if (!integer()) { return false; } group.threadCount = integer; if (group.threadCount == 0) { error("Thread count can't be 0."); } else if (group.threadCount > group.cpus.size()) { error("Thread count can't be larger than number of cpu's in the group. " + "Thread count = " + group.threadCount + " cpus:" + group.cpus); } } else { group.threadCount = group.cpus.size(); } groups.add(group); return true; }
Source:
<code>private void updateSession( @Nonnull final MemcachedBackupSession session, @Nonnull final BackupSessionService backupSessionService ) { final Future<BackupResult> result = backupSessionService.backupSession( session, true ); try { if ( result.get().getStatus() != BackupResultStatus.SUCCESS ) { _log.warn( "Update for session (after unsuccessful ping) did not return SUCCESS, but " + result.get() ); } } catch ( final ExecutionException e ) { _log.warn( "An exception occurred when trying to update session " + session.getIdInternal(), e ); <START> } catch ( final InterruptedException e ) { <END> _log.warn( "Got interrupted while trying to update session " + session.getIdInternal(), e ); } }</code><technical_language>do catch this InterruptedException? If a good reason catch it, interrupted status restored</technical_language>

Target:
private void updateSession( @Nonnull final MemcachedBackupSession session, @Nonnull final BackupSessionService backupSessionService ) throws InterruptedException { final Future<BackupResult> result = backupSessionService.backupSession( session, true ); try { if ( result.get().getStatus() != BackupResultStatus.SUCCESS ) { _log.warn( "Update for session (after unsuccessful ping) did not return SUCCESS, but " + result.get() ); } } catch ( final ExecutionException e ) { _log.warn( "An exception occurred when trying to update session " + session.getIdInternal(), e ); } }
Source:
<code>public byte[] serialize(PendingFileRecoverable pendingFileRecoverable) { if (!(pendingFileRecoverable instanceof HadoopPathBasedPartFileWriter.HadoopPathBasedPendingFileRecoverable)) { throw new UnsupportedOperationException("Only HadoopPathBasedPendingFileRecoverable is supported."); } HadoopPathBasedPendingFileRecoverable hadoopRecoverable = (HadoopPathBasedPendingFileRecoverable) pendingFileRecoverable; Path path = hadoopRecoverable.getPath(); Path inProgressPath = hadoopRecoverable.getInProgressPath(); byte[] pathBytes = path.toUri().toString().getBytes(CHARSET); byte[] inProgressBytes = inProgressPath.toUri().toString().getBytes(CHARSET); <START> byte[] targetBytes = new byte[8 + pathBytes.length + 4 + inProgressBytes.length]; <END> ByteBuffer bb = ByteBuffer.wrap(targetBytes).order(ByteOrder.LITTLE_ENDIAN); bb.putInt(MAGIC_NUMBER); bb.putInt(pathBytes.length); bb.put(pathBytes); bb.putInt(inProgressBytes.length); bb.put(inProgressBytes); return targetBytes; }</code><technical_language>12 + pathBytes.length + inProgressBytes.length</technical_language>

Target:
public byte[] serialize(PendingFileRecoverable pendingFileRecoverable) { if (!(pendingFileRecoverable instanceof HadoopPathBasedPartFileWriter.HadoopPathBasedPendingFileRecoverable)) { throw new UnsupportedOperationException("Only HadoopPathBasedPendingFileRecoverable is supported."); } HadoopPathBasedPendingFileRecoverable hadoopRecoverable = (HadoopPathBasedPendingFileRecoverable) pendingFileRecoverable; Path path = hadoopRecoverable.getTargetFilePath(); Path inProgressPath = hadoopRecoverable.getTempFilePath(); byte[] pathBytes = path.toUri().toString().getBytes(CHARSET); byte[] inProgressBytes = inProgressPath.toUri().toString().getBytes(CHARSET); byte[] targetBytes = new byte[12 + pathBytes.length + inProgressBytes.length]; ByteBuffer bb = ByteBuffer.wrap(targetBytes).order(ByteOrder.LITTLE_ENDIAN); bb.putInt(MAGIC_NUMBER); bb.putInt(pathBytes.length); bb.put(pathBytes); bb.putInt(inProgressBytes.length); bb.put(inProgressBytes); return targetBytes; }
Source:
<code>public void validateCreateWithIncorrectJarFile() { deployment.setFile(noJar); Throwable throwable = catchThrowable(() -> deploymentValidator.validate(CREATE, deployment)); assertThat(throwable).isNotNull(); assertThat(throwable).isInstanceOf(IllegalArgumentException.class); <START> assertThat(throwable).hasMessageContaining("File does not contain valid JAR content:"); <END> }</code><technical_language>chain assertions if like: assertThat(throwable) .isInstanceOf(IllegalArgumentException.class); .hasMessageContaining("File valid JAR content:"); note AssertJ's assertions do a null check, need isNotNull() helps clarify test</technical_language>

Target:
public void validateCreateWithIncorrectJarFile() { deployment.setFile(noJar); assertThatThrownBy(() -> deploymentValidator.validate(CREATE, deployment)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("File does not contain valid JAR content:"); }
Source:
<code>public FilterResult filtered(HttpMessage message) { String uri = message.getRequestHeader().getURI().toString(); String contentType = message.getResponseHeader() .getHeader(HttpHeader.CONTENT_TYPE) .toLowerCase(Locale.ROOT); <START> String responseBodyStart = StringUtils.left(message.getResponseBody().toString(), 250) .toLowerCase(Locale.ROOT); <END> if (uri.endsWith(".graphql") || uri.endsWith(".graphqls") || contentType.startsWith("application/graphql")) { return FilterResult.WANTED; } if (responseBodyStart.contains("__schema") || responseBodyStart.contains("graphql")) { return FilterResult.WANTED; } return FilterResult.NOT_FILTERED; }</code><technical_language>delayed check, avoids creating strings unnecessarily</technical_language>

Target:
public FilterResult filtered(HttpMessage message) { if (MessageValidator.validate(message) != MessageValidator.Result.INVALID) { return FilterResult.WANTED; } return FilterResult.NOT_FILTERED; }
Source:
<code>public void writeEncryptedCopyTo_wrongKeyLength() { <START> byte[] wrongLentKey = new byte[42]; <END> File destination = new File(configFactory.getRoot(), "wrong_key.realm"); thrown.expect(IllegalArgumentException.class); realm.writeEncryptedCopyTo(destination, wrongLentKey); }</code><technical_language>wrongKeyLength</technical_language>

Target:
public void writeEncryptedCopyTo_wrongKeyLength() { byte[] wrongLengthKey = new byte[42]; File destination = new File(configFactory.getRoot(), "wrong_key.realm"); thrown.expect(IllegalArgumentException.class); realm.writeEncryptedCopyTo(destination, wrongLengthKey); }
Source:
<code>private long removeFile(Path path) { try { if (!useTrash || !fs.moveToTrash(path)) { fs.deleteRecursively(path); } <START> return 1; <END> } catch (FileNotFoundException ex) { } catch (IOException ex) { log.error("Unable to delete wal {}", path, ex); } return 0; }</code><technical_language>Recursive delete counts 1 removed</technical_language>

Target:
private long removeFile(Path path) { try { if (!useTrash || !fs.moveToTrash(path)) { fs.deleteRecursively(path); } return 1; } catch (FileNotFoundException ex) { log.debug("Attempted to delete WAL that did not exists : {}", path, ex.getMessage()); } catch (IOException ex) { log.error("Unable to delete wal {}", path, ex); } return 0; }
Source:
<code>public void testSuspendLongRunningCondition() throws Exception { String typeName = "MethodCall"; IJavaLineBreakpoint first = createLineBreakpoint(19, typeName); createConditionalLineBreakpoint(27, typeName, "for (int x = 0; x < 1000; x++) { System.out.println(x);} Thread.sleep(1000); return true;", true); IJavaThread thread = null; try { thread = launchToLineBreakpoint(typeName, first); IStackFrame top = thread.getTopStackFrame(); assertNotNull("Missing top frame", top); thread.resume(); long start = System.currentTimeMillis(); while ((System.currentTimeMillis() - start) <= DEFAULT_TIMEOUT && !thread.isPerformingEvaluation()) { Thread.sleep(10); } assertTrue("Expected evaluation for second breakpoint", thread.isPerformingEvaluation()); thread.suspend(); TestUtil.waitForJobs(getName(), 100, DEFAULT_TIMEOUT, ProcessConsole.class); assertTrue("Thread should be suspended", thread.isSuspended()); IJavaStackFrame frame = (IJavaStackFrame) thread.getTopStackFrame(); assertNotNull("Missing top frame", frame); assertEquals("Wrong location", "calculateSum", frame.getName()); } finally { <START> removeAllBreakpoints(); terminateAndRemove(thread); <END> } }</code><technical_language>Is reason is order changed? other tests do differently</technical_language>

Target:
public void testSuspendLongRunningCondition() throws Exception { String typeName = "MethodCall"; IJavaLineBreakpoint first = createLineBreakpoint(19, typeName); createConditionalLineBreakpoint(27, typeName, "for (int x = 0; x < 1000; x++) { System.out.println(x);} Thread.sleep(1000); return true;", true); IJavaThread thread= null; try { thread= launchToLineBreakpoint(typeName, first); IStackFrame top = thread.getTopStackFrame(); assertNotNull("Missing top frame", top); thread.resume(); long start = System.currentTimeMillis(); while ((System.currentTimeMillis() - start) <= DEFAULT_TIMEOUT && !thread.isPerformingEvaluation()) { Thread.sleep(10); } assertTrue("Expected evaluation for second breakpoint", thread.isPerformingEvaluation()); thread.suspend(); TestUtil.waitForJobs(getName(), 100, DEFAULT_TIMEOUT, ProcessConsole.class); assertTrue("Thread should be suspended", thread.isSuspended()); IJavaStackFrame frame = (IJavaStackFrame) thread.getTopStackFrame(); assertNotNull("Missing top frame", frame); assertEquals("Wrong location", "calculateSum", frame.getName()); } finally { terminateAndRemove(thread); removeAllBreakpoints(); } }
Source:
<code>public void verifyCategoryExhibition() { <START> Assertion.assertTrue(categoryExhibition.size() == 4); <END> }</code><technical_language>is need wait here</technical_language>

Target:
public void verifyCategoryExhibition() { waitForElementByElement(categoryExhibition.get(0)); Assertion.assertTrue(categoryExhibition.size() == 4); }
Source:
<code>public Iterator<T> iterator() { return new Iterator<T>() { private int index = 0; @Override public boolean hasNext() { return index < trie.size(); } @Override public T next() { final int trieIndex = index + indexShift; index++; <START> return trie.get(trieIndex).get(); <END> } }; }</code><technical_language>impression is, do: java return new Iterator<T>() { private int index = indexShift; private final size = trie.size() + indexShift; @Override public boolean hasNext() { return index < size; } @Override public T next() { return trie.get(index++).get(); } }</technical_language>

Target:
public Iterator<T> iterator() { return new Iterator<T>() { private int index = indexShift; private final int size = trie.size() + indexShift; @Override public boolean hasNext() { return index < size; } @Override public T next() { return trie.get(index++).get(); } }; }
Source:
<code>public void testlookupBySubscriptionIds() { Product product = new Product("someProduct", "An Extremely Great Product", owner, 10L); productCurator.create(product); Pool p = new Pool(owner, product, new HashSet<Product>(), 1L, new Date(), new Date(), "contract", "account", "order"); String subId1 = Util.generateDbUUID(); p.setSourceSubscription(new SourceSubscription(subId1, "master")); poolCurator.create(p); Pool p2 = new Pool(owner, product, new HashSet<Product>(), 1L, new Date(), new Date(), "contract", "account", "order"); String subId2 = Util.generateDbUUID(); p2.setSourceSubscription(new SourceSubscription(subId2, "master")); poolCurator.create(p2); Pool p3 = new Pool(owner, product, new HashSet<Product>(), 1L, new Date(), new Date(), "contract", "account", "order"); String subId3 = Util.generateDbUUID(); p3.setSourceSubscription(new SourceSubscription(subId3, "master")); poolCurator.create(p3); List<Pool> pools = poolCurator.lookupBySubscriptionIds(Arrays.asList(subId1, subId2)); assertEquals(2, pools.size()); assertTrue(pools.contains(p)); assertTrue(pools.contains(p2)); assertTrue(!pools.contains(p3)); <START> <END> }</code><technical_language>Extraneous whitespace</technical_language>

Target:
public void testlookupBySubscriptionIds() { Product product = new Product("someProduct", "An Extremely Great Product", owner, 10L); productCurator.create(product); Pool p = new Pool(owner, product, new HashSet<Product>(), 1L, new Date(), new Date(), "contract", "account", "order"); String subId1 = Util.generateDbUUID(); p.setSourceSubscription(new SourceSubscription(subId1, "master")); poolCurator.create(p); Pool p2 = new Pool(owner, product, new HashSet<Product>(), 1L, new Date(), new Date(), "contract", "account", "order"); String subId2 = Util.generateDbUUID(); p2.setSourceSubscription(new SourceSubscription(subId2, "master")); poolCurator.create(p2); Pool p3 = new Pool(owner, product, new HashSet<Product>(), 1L, new Date(), new Date(), "contract", "account", "order"); String subId3 = Util.generateDbUUID(); p3.setSourceSubscription(new SourceSubscription(subId3, "master")); poolCurator.create(p3); List<Pool> pools = poolCurator.lookupBySubscriptionIds(Arrays.asList(subId1, subId2)); assertEquals(2, pools.size()); assertThat(pools, hasItems(p, p2)); assertThat(pools, not(hasItem(p3))); }
Source:
<code>public void setReceivedAtWithSystemTimeInUTC() throws Exception { final EventType eventType = buildDefaultEventType(); final JSONObject event = buildBusinessEvent(); assertThat(event.getJSONObject("metadata").optString("received_at"), isEmptyString()); try { <START> org.joda.time.DateTimeUtils.setCurrentMillisFixed(0); <END> strategy.enrich(event, eventType); } finally { org.joda.time.DateTimeUtils.setCurrentMillisSystem(); } assertThat(event.getJSONObject("metadata").getString("received_at"), equalTo("1970-01-01T00:00:00.000Z")); }</code><technical_language>a full-name import here? I conflicts</technical_language>

Target:
public void setReceivedAtWithSystemTimeInUTC() throws Exception { final EventType eventType = buildDefaultEventType(); final JSONObject event = buildBusinessEvent(); assertThat(event.getJSONObject("metadata").optString("received_at"), isEmptyString()); try { DateTimeUtils.setCurrentMillisFixed(0); strategy.enrich(event, eventType); } finally { DateTimeUtils.setCurrentMillisSystem(); } assertThat(event.getJSONObject("metadata").getString("received_at"), equalTo("1970-01-01T00:00:00.000Z")); }
Source:
<code>private DateTime getLocalToday(final Long accountId) { final Optional<TimeZoneHistory> optionalTimeZone = this.timeZoneHistoryDAODynamoDB.getCurrentTimeZone(accountId); if (optionalTimeZone.isPresent()) { final int offsetMillis = optionalTimeZone.get().offsetMillis; return DateTime.now(DateTimeZone.UTC).plusMillis(offsetMillis).withTimeAtStartOfDay(); } <START> return DateTime.now(DateTimeZone.UTC).withTimeAtStartOfDay(); <END> }</code><technical_language>if want Fancy, rewrite this as: java final Optional<TimeZoneHistory> timeZone = this.timeZoneHistoryDAODynamoDB.getCurrentTimeZone(accountId); final Optional<DateTime> nowForUser = timeZone.transform(new Function<? super TimeZoneHistory, DateTime>() { @Override public DateTime apply(TimeZoneHistory history) { return DateTime.now(DateTimeZone.UTC) .plusMillis(history.offsetMillis) .withTimeAtStartOfDay(); } }); return nowForUser.or(new Supplier<? extends DateTime>() { @Override public DateTime get() { return DateTime.now(DateTimeZone.UTC).withTimeAtStartOfDay(); } });</technical_language>

Target:
private DateTime getLocalToday(final Long accountId) { final Optional<TimeZoneHistory> optionalTimeZone = this.timeZoneHistoryDAODynamoDB.getCurrentTimeZone(accountId); final DateTime now = DateTime.now(DateTimeZone.UTC).withTimeAtStartOfDay(); if (optionalTimeZone.isPresent()) { return now.plusMillis(optionalTimeZone.get().offsetMillis); } return now; }
Source:
<code>public void check() { Preconditions.checkState(sslSocketFactory().isPresent() == trustManager().isPresent(), <START> "Must set either both sslSocketFactory and TrustManager, or neither"); <END> }</code><technical_language>read: "Must set SslSocketFactory TrustManager, neither" "Must set sslSocketFactory trustManager, neither"</technical_language>

Target:
public void check() { Preconditions.checkState(sslSocketFactory().isPresent() == trustManager().isPresent(), "Must set either both SslSocketFactory and TrustManager, or neither"); }
Source:
<code>public Void apply(KVariable k) { <START> hasConfigVar = true; <END> return null; }</code><technical_language>this done</technical_language>

Target:
public void apply(KVariable k) { hasConfigVar = true; }
Source:
<code>private void displayLangLinks() { if (languageEntries.size() == 0) { langLinksEmpty.setEmptyText(R.string.langlinks_empty); ViewAnimations.crossFade(langLinksProgress, langLinksEmpty); } else { adapter = new LangLinksAdapter(languageEntries, getEntriesByAppLanguages()); langLinksEmpty.setEmptyText(R.string.langlinks_no_match); langLinksList.setAdapter(adapter); langLinksList.setLayoutManager(new LinearLayoutManager(this)); searchActionModeCallback = new LanguageSearchCallback(); disposables.add(ServiceFactory.get(app.getWikiSite()).getSiteMatrix() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(SiteMatrix::getSites) .subscribe(sites -> { langLinksProgress.setVisibility(View.INVISIBLE); siteInfoList = sites; adapter.notifyDataSetChanged(); }, throwable -> { <START> langLinksProgress.setVisibility(View.INVISIBLE); adapter.notifyDataSetChanged(); <END> })); ViewAnimations.crossFade(langLinksProgress, langLinksList); } invalidateOptionsMenu(); }</code><technical_language>move codes a doFinally() do in end? .map(SiteMatrix::getSites) .doFinally(() -> { langLinksProgress.setVisibility(View.INVISIBLE); adapter.notifyDataSetChanged(); }) .subscribe(..)</technical_language>

Target:
private void displayLangLinks() { if (languageEntries.size() == 0) { langLinksEmpty.setEmptyText(R.string.langlinks_empty); ViewAnimations.crossFade(langLinksProgress, langLinksEmpty); } else { adapter = new LangLinksAdapter(languageEntries, getEntriesByAppLanguages()); langLinksEmpty.setEmptyText(R.string.langlinks_no_match); langLinksList.setAdapter(adapter); langLinksList.setLayoutManager(new LinearLayoutManager(this)); searchActionModeCallback = new LanguageSearchCallback(); disposables.add(ServiceFactory.get(app.getWikiSite()).getSiteMatrix() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(SiteMatrix::getSites) .subscribe(sites -> siteInfoList = sites, L::e, () -> { langLinksProgress.setVisibility(View.INVISIBLE); adapter.notifyDataSetChanged(); })); ViewAnimations.crossFade(langLinksProgress, langLinksList); } invalidateOptionsMenu(); }
Source:
<code>public void testBuilderWithGivenSchema() { TableSchema oriSchema = TableSchema.builder() .field("a", DataTypes.INT().notNull()) .field("b", DataTypes.STRING()) .field("c", DataTypes.INT(), "a + 1") .field("t", DataTypes.TIMESTAMP(3)) .primaryKey("ct1", new String[] {"a"}) .watermark("t", "t", DataTypes.TIMESTAMP(3)) .build(); TableSchema newSchema = TableSchemaUtils.builderWithGivenSchema(oriSchema).build(); <START> final String expected = "root\n" + " |-- a: INT NOT NULL\n" + " |-- b: STRING\n" + " |-- c: INT AS a + 1\n" + " |-- t: TIMESTAMP(3)\n" + " |-- WATERMARK FOR t AS t\n" + " |-- CONSTRAINT ct1 PRIMARY KEY (a)\n"; assertEquals(expected, newSchema.toString()); <END> }</code><technical_language>nit: A simpler verification for this is assertEquals(oriSchema, newSchema)</technical_language>

Target:
public void testBuilderWithGivenSchema() { TableSchema oriSchema = TableSchema.builder() .field("a", DataTypes.INT().notNull()) .field("b", DataTypes.STRING()) .field("c", DataTypes.INT(), "a + 1") .field("t", DataTypes.TIMESTAMP(3)) .primaryKey("ct1", new String[] {"a"}) .watermark("t", "t", DataTypes.TIMESTAMP(3)) .build(); TableSchema newSchema = TableSchemaUtils.builderWithGivenSchema(oriSchema).build(); assertEquals(oriSchema, newSchema); }
Source:
<code>public void onCompleted() { if (once.compareAndSet(0, 1)) { long c = produced; <START> if (c != 0L) { <END> parent.produced(c); } parent.completeInner(); } }</code><technical_language>Move c!=0 test produced method? need assign produced c changed another thread due Observable contract</technical_language>

Target:
public void onCompleted() { if (once.compareAndSet(false, true)) { ConcatSubscriber<T> p = parent; p.produced(produced); p.completeInner(); } }
Source:
<code>public void stop() { synchronized (startStopSync) { if (!started) { LOG.debug("Already stopped, ignoring"); return; } try { <START> serviceDiscovery.close(); <END> } catch (IOException e) { throw Throwables.propagate(e); } started = false; } }</code><technical_language>need call un-register</technical_language>

Target:
public void stop() { synchronized (startStopSync) { if (!started) { LOG.debug("Already stopped, ignoring"); return; } announcer.unannounce(announcePath); LOG.info("Unannouncing start time on [%s]", announcePath); started = false; } }
Source:
<code>public void channelRead0(ChannelHandlerContext ctx, HttpObject in) { responseParts.offer(ReferenceCountUtil.retain(in)); if (in instanceof HttpResponse && in.getDecoderResult().isSuccess()) { isKeepAlive = HttpHeaders.isKeepAlive((HttpResponse) in); } else if (in.getDecoderResult().isFailure()) { Throwable cause = in.getDecoderResult().cause(); if (cause instanceof Exception) { <START> exception = (Exception) in.getDecoderResult().cause(); <END> } else { exception = new Exception("Encountered Throwable when trying to decode response. Message: " + cause.getMessage()); } invokeFutureAndCallback(); } if (in instanceof LastHttpContent) { if (isKeepAlive) { invokeFutureAndCallback(); } else { ctx.close(); } } }</code><technical_language>do this, exception = (Exception)</technical_language>

Target:
public void channelRead0(ChannelHandlerContext ctx, HttpObject in) { responseParts.offer(ReferenceCountUtil.retain(in)); if (in instanceof HttpResponse && in.getDecoderResult().isSuccess()) { isKeepAlive = HttpHeaders.isKeepAlive((HttpResponse) in); } else if (in.getDecoderResult().isFailure()) { Throwable cause = in.getDecoderResult().cause(); if (cause instanceof Exception) { exception = (Exception) cause; } else { exception = new Exception("Encountered Throwable when trying to decode response. Message: " + cause.getMessage()); } invokeFutureAndCallback(); } if (in instanceof LastHttpContent) { if (isKeepAlive) { invokeFutureAndCallback(); } else { ctx.close(); } } }
Source:
<code>public void checkGroup(long userId, long groupId) throws SecurityException { if (!getGroupPermissions(userId).contains(groupId) && !isAdmin(userId)) { <START> Iterator<Long> iterator = getUserPermissions(userId).iterator(); <END> boolean managed = false; while (!managed && iterator.hasNext()) { managed = getGroupPermissions(iterator.next()).contains(groupId); } if (!managed) { throw new SecurityException("Group access denied"); } } }</code><technical_language>I easier do this: java for (int userId : getUserPermissions(userId)) { if (getGroupPermissions(userId).contains(groupId)) { return; } } throw new SecurityException("Group access denied");</technical_language>

Target:
public void checkGroup(long userId, long groupId) throws SecurityException { if (!getGroupPermissions(userId).contains(groupId) && !isAdmin(userId)) { checkManager(userId); for (long managedUserId : getUserPermissions(userId)) { if (getGroupPermissions(managedUserId).contains(groupId)) { return; } } throw new SecurityException("Group access denied"); } }
Source:
<code>public static String printRequestParameters(HttpServletRequest request) { StringBuilder requestParameters = new StringBuilder(); requestParameters.append('{'); for (Enumeration<?> f = request.getParameterNames(); f.hasMoreElements();) { String paramet = new String(f.nextElement().toString()); <START> requestParameters.append(paramet).append("::"); <END> String[] parameterValues = request.getParameterValues(paramet); for (int j = 0; j < parameterValues.length; j++) { requestParameters.append(parameterValues[j]).append(" } requestParameters.setLength(requestParameters.length() - 2); requestParameters.append(", "); } if (!requestParameters.toString().equals("{")) { requestParameters.setLength(requestParameters.length() - 2); } return requestParameters.append("}").toString(); }</code><technical_language>Small request: I this, rename paramet better, param</technical_language>

Target:
public static String printRequestParameters(HttpServletRequest request) { StringBuilder requestParameters = new StringBuilder(); requestParameters.append('{'); for (Enumeration<?> f = request.getParameterNames(); f.hasMoreElements();) { String param = new String(f.nextElement().toString()); requestParameters.append(param).append("::"); String[] parameterValues = request.getParameterValues(param); for (int j = 0; j < parameterValues.length; j++) { requestParameters.append(parameterValues[j]).append(" } requestParameters.setLength(requestParameters.length() - 2); requestParameters.append(", "); } if (!"{".equals(requestParameters.toString())) { requestParameters.setLength(requestParameters.length() - 2); } return requestParameters.append("}").toString(); }
Source:
<code><START> private Map<String, PartitionAssignor.Subscription> toOldGroupSubscription(GroupSubscription newSubscriptions) { <END> Map<String, PartitionAssignor.Subscription> oldSubscriptions = new HashMap<>(); for (Map.Entry<String, Subscription> entry : newSubscriptions.groupSubscription().entrySet()) { String member = entry.getKey(); Subscription newSubscription = entry.getValue(); oldSubscriptions.put(member, new PartitionAssignor.Subscription( newSubscription.topics(), newSubscription.userData())); } return oldSubscriptions; }</code><technical_language>This static too</technical_language>

Target:
private static Map<String, PartitionAssignor.Subscription> toOldGroupSubscription(GroupSubscription newSubscriptions) { Map<String, PartitionAssignor.Subscription> oldSubscriptions = new HashMap<>(); for (Map.Entry<String, Subscription> entry : newSubscriptions.groupSubscription().entrySet()) { String member = entry.getKey(); Subscription newSubscription = entry.getValue(); oldSubscriptions.put(member, new PartitionAssignor.Subscription( newSubscription.topics(), newSubscription.userData())); } return oldSubscriptions; }
Source:
<code>protected void trashDocument(CoreSession session, DocumentModel doc) { if (doc.getParentRef() == null) { session.removeDocument(doc.getRef()); } else { <START> if (!Boolean.parseBoolean(String.valueOf(doc.getContextData(DISABLE_TRASH_RENAMING)))) { <END> String name = mangleName(doc); session.move(doc.getRef(), doc.getParentRef(), name); } session.followTransition(doc, LifeCycleConstants.DELETE_TRANSITION); } }</code><technical_language>compare directly, need a String: if (!Boolean.TRUE.equals(doc.getContextData(DISABLE_TRASH_RENAMING)))</technical_language>

Target:
protected void trashDocument(CoreSession session, DocumentModel doc) { if (doc.getParentRef() == null) { session.removeDocument(doc.getRef()); } else { if (!Boolean.TRUE.equals(doc.getContextData(DISABLE_TRASH_RENAMING))) { String name = mangleName(doc); session.move(doc.getRef(), doc.getParentRef(), name); } session.followTransition(doc, LifeCycleConstants.DELETE_TRANSITION); } }
Source:
<code>public static Field constructField(java.lang.reflect.Field field) { if (field == null) { return null; } return new Field() { @Override public void setAccessible(boolean flag) { field.setAccessible(flag); } @Override public boolean isSynthetic() { return field.isSynthetic(); } @Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) { return field.isAnnotationPresent(annotationClass); } @Override public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { return field.getAnnotation(annotationClass); } @Override public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) { return field.getAnnotationsByType(annotationClass); } @Override public Annotation[] getDeclaredAnnotations() { return field.getDeclaredAnnotations(); } @Override public Annotation[] getAnnotations() { return field.getAnnotations(); } @Override public int getModifiers() { return field.getModifiers(); } @Override public String getName() { return field.getName(); } @Override public Object get(Object obj) throws IllegalArgumentException, IllegalAccessException { return field.get(obj); } @Override public Type<?> getType() { return new ClassType(field.getType()); } @Override public Type<?> getParameterizedType(Type<?> parentType, Optional<Integer> index) { if (parentType instanceof DynamicType) { return getType(); } java.lang.reflect.Type type = field.getGenericType(); if (type instanceof ParameterizedType && index.isPresent()) { return new ClassType( TypeUtils.getRawType( ((ParameterizedType) type).getActualTypeArguments()[index.get().intValue()], ((ClassType) parentType).getCls() ) ); } return new ClassType(TypeUtils.getRawType(type, ((ClassType) parentType).getCls())); } @Override public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException { field.set(obj, value); } @Override <START> public java.lang.reflect.Field getField() { <END> return field; } }; }</code><technical_language>want this method</technical_language>

Target:
public static Field constructField(java.lang.reflect.Field field) { if (field == null) { return null; } return new FieldType(field); }
Source:
<code>public void execute() throws MojoExecutionException, MojoFailureException { this.runtimeLocation = new BuildOutputDirectory(this.project.getBuild().getDirectory()).getChild("director"); <START> getDirectorRuntime(); <END> FeatureInstaller installer = constructFeatureInstaller(); installer.install(); }</code><technical_language>returned is used</technical_language>

Target:
public void execute() throws MojoExecutionException, MojoFailureException { this.runtimeLocation = new BuildOutputDirectory(this.project.getBuild().getDirectory()).getChild("director"); setDirectorRuntime(); FeatureInstaller installer = constructFeatureInstaller(); installer.install(); }
Source:
<code>private static void addUrlMappings(Context context, JSONObject obj) { Object test = context.getServletContext().getAttribute("org.jaggeryjs.serveFunction"); JSONArray arr = null; if (test != null) { arr = new JSONArray(); <START> JSONObject js1 = new JSONObject(); <END> JSONObject js2 = new JSONObject(); js1.put("url", "/*"); js1.put("path", File.pathSeparator + INDEX_JAG); arr.add(js1); } else { arr = (JSONArray) obj.get(JaggeryCoreConstants.JaggeryConfigParams.URL_MAPPINGS); } if (arr != null) { Map<String, Object> urlMappings = new HashMap<String, Object>(); for (Object mapObj : arr) { JSONObject mapping = (JSONObject) mapObj; String url = (String) mapping.get(JaggeryCoreConstants.JaggeryConfigParams.URL_MAPPINGS_URL); String path = (String) mapping.get(JaggeryCoreConstants.JaggeryConfigParams.URL_MAPPINGS_PATH); if (url != null && path != null) { path = path.startsWith("/") ? path : "/" + path; FilterMap filterMap = new FilterMap(); filterMap.setFilterName(JaggeryCoreConstants.JAGGERY_FILTER_NAME); filterMap.addURLPattern(url); context.addFilterMap(filterMap); if (url.equals("/")) { urlMappings.put("/", path); continue; } url = url.startsWith("/") ? url.substring(1) : url; List<String> parts = new ArrayList<String>(Arrays.asList(url.split("/", -1))); addMappings(urlMappings, parts, path); } else { log.error("Invalid url mapping in jaggery.conf url : " + url + ", path : " + path); } } context.getServletContext().setAttribute(CommonManager.JAGGERY_URLS_MAP, urlMappings); } }</code><technical_language>Add proper variable names, js1, js2 sort of names, explain doing</technical_language>

Target:
private static void addUrlMappings(Context context, JSONObject obj) { Object test = context.getServletContext().getAttribute("org.jaggeryjs.serveFunction"); JSONArray arr = null; if (test != null) { arr = new JSONArray(); JSONObject urlJSONObj = new JSONObject(); JSONObject pathJSONObj = new JSONObject(); urlJSONObj.put("url", "/*"); pathJSONObj.put("path", File.separator + INDEX_JAG); arr.add(urlJSONObj); } else { arr = (JSONArray) obj.get(JaggeryCoreConstants.JaggeryConfigParams.URL_MAPPINGS); } if (arr != null) { Map<String, Object> urlMappings = new HashMap<String, Object>(); for (Object mapObj : arr) { JSONObject mapping = (JSONObject) mapObj; String url = (String) mapping.get(JaggeryCoreConstants.JaggeryConfigParams.URL_MAPPINGS_URL); String path = (String) mapping.get(JaggeryCoreConstants.JaggeryConfigParams.URL_MAPPINGS_PATH); if (url != null && path != null) { path = path.startsWith("/") ? path : "/" + path; FilterMap filterMap = new FilterMap(); filterMap.setFilterName(JaggeryCoreConstants.JAGGERY_FILTER_NAME); filterMap.addURLPattern(url); context.addFilterMap(filterMap); if (url.equals("/")) { urlMappings.put("/", path); continue; } url = url.startsWith("/") ? url.substring(1) : url; List<String> parts = new ArrayList<String>(Arrays.asList(url.split("/", -1))); addMappings(urlMappings, parts, path); } else { log.error("Invalid url mapping in jaggery.conf url : " + url + ", path : " + path); } } context.getServletContext().setAttribute(CommonManager.JAGGERY_URLS_MAP, urlMappings); } }
Source:
<code>private Set<String> computeRoles(U user, T tenant, boolean isSystemTenant) { Set<String> roles = Sets.newTreeSet(); roles.add(UserInfo.PERMISSION_LOGGED_IN); roles.addAll(user.getUserAccountData().getPermissions().getPermissions().data()); roles.addAll(tenant.getTenantData().getPackageData().computeCombinedPermissions()); if (Strings.isFilled(tenant.getTenantData().getAccountNumber())) { roles.add("tenant-" + tenant.getTenantData().getAccountNumber()); } for (AdditionalRolesProvider rolesProvider : additionalRolesProviders) { rolesProvider.addAdditionalRoles(user, roles::add); } if (tenant.getMapper().select(tenant.getClass()).eq(Tenant.PARENT, tenant.getIdAsString()).exists()) { roles.add(PERMISSION_HAS_CHILDREN); } Set<String> transformedRoles = transformRoles(roles); <START> roles.add(PERMISSION_SYSTEM_TENANT_MEMBER); <END> if (isSystemTenant) { if (transformedRoles.contains(PERMISSION_MANAGE_SYSTEM)) { roles.add(PERMISSION_SYSTEM_TENANT); } transformedRoles = transformRoles(roles); } transformedRoles.removeAll(tenant.getTenantData().getPackageData().getRevokedPermissions().data()); return transformedRoles; }</code><technical_language>this of isSystemTenant if right</technical_language>

Target:
private Set<String> computeRoles(U user, T tenant, boolean isSystemTenant) { Set<String> roles = Sets.newTreeSet(); roles.add(UserInfo.PERMISSION_LOGGED_IN); roles.addAll(user.getUserAccountData().getPermissions().getPermissions().data()); roles.addAll(tenant.getTenantData().getPackageData().computeCombinedPermissions()); if (Strings.isFilled(tenant.getTenantData().getAccountNumber())) { roles.add("tenant-" + tenant.getTenantData().getAccountNumber()); } for (AdditionalRolesProvider rolesProvider : additionalRolesProviders) { rolesProvider.addAdditionalRoles(user, roles::add); } if (tenant.getMapper().select(tenant.getClass()).eq(Tenant.PARENT, tenant.getIdAsString()).exists()) { roles.add(PERMISSION_HAS_CHILDREN); } Set<String> transformedRoles = transformRoles(roles); if (isSystemTenant) { roles.add(PERMISSION_SYSTEM_TENANT_MEMBER); if (transformedRoles.contains(PERMISSION_MANAGE_SYSTEM)) { roles.add(PERMISSION_SYSTEM_TENANT); } transformedRoles = transformRoles(roles); } transformedRoles.removeAll(tenant.getTenantData().getPackageData().getRevokedPermissions().data()); return transformedRoles; }
Source:
<code>private Gson buildGsonWithAdaptersSerialize() { return new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") <START> .registerTypeAdapter(Observation.class, new Observation.ObservationSerializer()) <END> .registerTypeAdapter(Visit.class, new Visit.VisitSerializer()) .create(); }</code><technical_language>this is redundant</technical_language>

Target:
private Gson buildGsonWithAdaptersSerialize() { return new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") .registerTypeAdapter(VisitType.class, new VisitType.VisitTypeSerializer()) .registerTypeAdapter(Patient.class, new Patient.PatientSerializer()) .registerTypeAdapter(Location.class, new Location.LocationSerializer()) .create(); }
Source:
<code>public int getRowCountEstimateIncrease() { <START> if (rowCountEstimateIncrease < 1) { <END> return pageSize * 4; } else { return rowCountEstimateIncrease; } }</code><technical_language>replace rowCountEstimateIncrease < 0? rowCountEstimateIncrease is -1 >= 1. Otherwise, I 0 possible</technical_language>

Target:
public int getRowCountEstimateIncrease() { if (rowCountEstimateIncrease == -1) { return pageSize * DEFAULT_PAGE_INCREASE_COUNT; } else { assert rowCountEstimate > 0 : "0 is not an increase"; return rowCountEstimateIncrease; } }
Source:
<code>public void setFromBundle(Bundle data) { setName(data.getString("name")); setUsername(data.getString("username")); setUser_id(Integer.parseInt(data.getString("user_id"))); setPartner_id(Integer.parseInt(data.getString("partner_id"))); setTimezone(data.getString("timezone")); setIsactive(Boolean.parseBoolean(data.getString("isactive"))); try { setAvatar(data.getString("avatar")); } catch (Exception e) { setAvatar("false"); <START> } <END> setDatabase(data.getString("database")); setHost(data.getString("host")); setAndroidName(data.getString("android_name")); setPassword(data.getString("password")); setCompany_id(data.getString("company_id")); setAllowSelfSignedSSL(Boolean.parseBoolean(data .getString("allow_self_signed_ssl"))); setVersion_number(Integer.parseInt(data .getString("odoo_version_number"))); setVersion_serie(data.getString("odoo_version_serie")); setInstanceDatabase(data.getString("instance_database")); setInstanceUrl(data.getString("instance_url")); setOAuthLogin(Boolean.parseBoolean(data.getString("oauth_login"))); setClientId(data.getString("client_id")); }</code><technical_language>Remove this exception catch.. call..</technical_language>

Target:
public void setFromBundle(Bundle data) { setName(data.getString("name")); setUsername(data.getString("username")); setUser_id(Integer.parseInt(data.getString("user_id"))); setPartner_id(Integer.parseInt(data.getString("partner_id"))); setTimezone(data.getString("timezone")); setIsactive(Boolean.parseBoolean(data.getString("isactive"))); setAvatar(data.getString("avatar")); setDatabase(data.getString("database")); setHost(data.getString("host")); setAndroidName(data.getString("android_name")); setPassword(data.getString("password")); setCompany_id(data.getString("company_id")); setAllowSelfSignedSSL(Boolean.parseBoolean(data .getString("allow_self_signed_ssl"))); setVersion_number(Integer.parseInt(data .getString("odoo_version_number"))); setVersion_serie(data.getString("odoo_version_serie")); setInstanceDatabase(data.getString("instance_database")); setInstanceUrl(data.getString("instance_url")); setOAuthLogin(Boolean.parseBoolean(data.getString("oauth_login"))); setClientId(data.getString("client_id")); }
Source:
<code>public ResultModel toResultModel(String warningMessage) { if (StringUtils.isEmpty(keyClass)) { keyClass = "java.lang.String"; } if (StringUtils.isEmpty(valueClass)) { valueClass = "java.lang.String"; } ResultModel result = new ResultModel(); if (warningMessage != null && !warningMessage.isEmpty()) { <START> InfoResultModel info = result.addInfo(HEADER_INFO_SECTION); <END> info.addLine(warningMessage); } DataResultModel data = result.addData(DATA_INFO_SECTION); if (errorString != null) { data.addData("Message", errorString); data.addData(RESULT_FLAG, operationCompletedSuccessfully); return result; } data.addData(RESULT_FLAG, operationCompletedSuccessfully); if (infoString != null) { data.addData("Message", infoString); } if (isGet()) { toResultModel_isGet(data); } else if (isLocateEntry()) { toResultModel_isLocate(result, data); } else if (isPut()) { toResultModel_isPut(data); } else if (isRemove()) { toResultModel_isRemove(data); } return result; }</code><technical_language>more consistent call setHeader instead of addInfo, rename HEADER_INFO_SECTION WARNING_INFO_SECTION similar</technical_language>

Target:
public ResultModel toResultModel(String warningMessage) { if (StringUtils.isEmpty(keyClass)) { keyClass = "java.lang.String"; } if (StringUtils.isEmpty(valueClass)) { valueClass = "java.lang.String"; } ResultModel result = new ResultModel(); if (warningMessage != null && !warningMessage.isEmpty()) { InfoResultModel info = result.addInfo(WARNING_INFO_SECTION); info.addLine(warningMessage); } DataResultModel data = result.addData(DATA_INFO_SECTION); if (errorString != null) { data.addData("Message", errorString); data.addData(RESULT_FLAG, operationCompletedSuccessfully); return result; } data.addData(RESULT_FLAG, operationCompletedSuccessfully); if (infoString != null) { data.addData("Message", infoString); } if (isGet()) { toResultModel_isGet(data); } else if (isLocateEntry()) { toResultModel_isLocate(result, data); } else if (isPut()) { toResultModel_isPut(data); } else if (isRemove()) { toResultModel_isRemove(data); } return result; }
Source:
<code>public static Bridge fromBridgeConfig(BridgeConfig bridge) { if (bridge == null) return null; <START> org.slf4j.LoggerFactory.getLogger(Converter.class).error("HELLO {}", bridge.vxLanPortIds, bridge.vxLanPortId); <END> return new Bridge() .setName(bridge.name) .setAdminStateUp(bridge.adminStateUp) .setTunnelKey(bridge.tunnelKey) .setInboundFilter(bridge.inboundFilter) .setOutboundFilter(bridge.outboundFilter) .setVxLanPortId(bridge.vxLanPortId) .setVxLanPortIds(bridge.vxLanPortIds) .setProperties(bridge.properties); }</code><technical_language>delete</technical_language>

Target:
public static Bridge fromBridgeConfig(BridgeConfig bridge) { if (bridge == null) return null; return new Bridge() .setName(bridge.name) .setAdminStateUp(bridge.adminStateUp) .setTunnelKey(bridge.tunnelKey) .setInboundFilter(bridge.inboundFilter) .setOutboundFilter(bridge.outboundFilter) .setVxLanPortId(bridge.vxLanPortId) .setVxLanPortIds(bridge.vxLanPortIds) .setProperties(bridge.properties); }
Source:
<code>private static SwapLeg parseLeg( CsvRow row, String leg, FloatingRateIndex index, DayCount defaultFixedLegDayCount) { PayReceive payReceive = LoaderUtils.parsePayReceive(getValue(row, leg, DIRECTION_FIELD)); PeriodicSchedule accrualSch = parseAccrualSchedule(row, leg); PaymentSchedule paymentSch = parsePaymentSchedule(row, leg, accrualSch.getFrequency()); NotionalSchedule notionalSch = parseNotionalSchedule(row, leg); Optional<String> knownAmount = findValue(row, leg, KNOWN_AMOUNT_FIELD); if (knownAmount.isPresent()) { return KnownAmountSwapLeg.builder() .payReceive(payReceive) .accrualSchedule(accrualSch) .paymentSchedule(paymentSch) <START> .currency(notionalSch.getCurrency()) <END> .amount(ValueSchedule.of(LoaderUtils.parseDouble(knownAmount.get()))) .build(); } return parseRateCalculationLeg( row, leg, index, defaultFixedLegDayCount, payReceive, accrualSch, paymentSch, notionalSch); }</code><technical_language>Need parse currency separately notional schedule, notional schedule parsed in parseRateCalculationLeg. stands, notional mandatory for parsing KnownAmountSwapLeg true</technical_language>

Target:
private static SwapLeg parseLeg( CsvRow row, String leg, FloatingRateIndex index, DayCount defaultFixedLegDayCount) { PayReceive payReceive = LoaderUtils.parsePayReceive(getValue(row, leg, DIRECTION_FIELD)); PeriodicSchedule accrualSch = parseAccrualSchedule(row, leg); PaymentSchedule paymentSch = parsePaymentSchedule(row, leg, accrualSch.getFrequency()); Currency currency = Currency.of(getValueWithFallback(row, leg, CURRENCY_FIELD)); Optional<String> knownAmount = findValue(row, leg, KNOWN_AMOUNT_FIELD); if (knownAmount.isPresent()) { return KnownAmountSwapLeg.builder() .payReceive(payReceive) .accrualSchedule(accrualSch) .paymentSchedule(paymentSch) .currency(currency) .amount(ValueSchedule.of(LoaderUtils.parseDouble(knownAmount.get()))) .build(); } return parseRateCalculationLeg( row, leg, index, defaultFixedLegDayCount, payReceive, accrualSch, paymentSch); }
Source:
<code>public void testValidateModifiedBondSlavesWhenSlaveIsNotValid() throws Exception { Bond bond = createBond(); bond.setSlaves(Arrays.asList("slaveA", "slaveB")); ValidationResult cannotBeSlaveValidationResult = new ValidationResult(EngineMessage.NETWORK_INTERFACE_BOND_OR_VLAN_CANNOT_BE_SLAVE, ReplacementUtils.createSetVariableString(HostInterfaceValidator.VAR_NIC_NAME, bond.getName())); HostSetupNetworksValidator validator = new HostSetupNetworksValidatorBuilder() <START> .setParams(new ParametersBuilder().addBonds(CreateOrUpdateBond.fromBond(bond))) <END> .build(); doTestValidateModifiedBondSlaves( spy(validator), ValidationResult.VALID, cannotBeSlaveValidationResult, failsWith(cannotBeSlaveValidationResult)); }</code><technical_language>#838</technical_language>

Target:
public void testValidateModifiedBondSlavesWhenSlaveIsNotValid() throws Exception { CreateOrUpdateBond createOrUpdateBond = createNewCreateOrUpdateBond(Guid.newGuid(), "bond1", "slaveA", "slaveB"); ValidationResult cannotBeSlaveValidationResult = new ValidationResult(EngineMessage.NETWORK_INTERFACE_BOND_OR_VLAN_CANNOT_BE_SLAVE, ReplacementUtils.createSetVariableString(HostInterfaceValidator.VAR_NIC_NAME, createOrUpdateBond.getName())); HostSetupNetworksValidator validator = new HostSetupNetworksValidatorBuilder() .setParams(new ParametersBuilder().addBonds(createOrUpdateBond)) .build(); doTestValidateModifiedBondSlaves( spy(validator), ValidationResult.VALID, cannotBeSlaveValidationResult, failsWith(cannotBeSlaveValidationResult)); }