auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void addAddOnWrapper(AddOn addOn, AddOnWrapper.Status status) { AddOnWrapper aow = createAddOnWrapper(addOn, status); int idx = 0; for (; idx < getAddOnWrappers().size(); idx++) { <START> if (comparator != null) { <END> if (comparator.compare(aow, getAddOnWrappers().get(idx)) < 0) { break; } } } getAddOnWrappers().add(idx, aow); fireTableRowsInserted(idx, idx); refreshEntries(); }</code><technical_language>Consider moving this if statement loop, need loop if comparator (and in case idx is position, i.e. getAddOnWrappers().size().)</technical_language>

Target:
protected void addAddOnWrapper(AddOn addOn, AddOnWrapper.Status status) { AddOnWrapper aow = createAddOnWrapper(addOn, status); int idx = 0; if (comparator != null) { for (; idx < getAddOnWrappers().size(); idx++) { if (comparator.compare(aow, getAddOnWrappers().get(idx)) < 0) { break; } getAddOnWrappers().add(idx, aow); } } else { idx = getAddOnWrappers().size(); getAddOnWrappers().add(aow); } fireTableRowsInserted(idx, idx); refreshEntries(); }
Source:
<code>public void testFailureWhenLastChunkFailed() throws IOException { ChannelOutboundHandlerAdapter failLast = new ChannelOutboundHandlerAdapter() { private int passedWrites; @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (++this.passedWrites < 4) { ctx.write(msg, promise); } else { <START> promise.tryFailure(new RuntimeException()); <END> } } }; EmbeddedChannel ch = new EmbeddedChannel(failLast, new ChunkedWriteHandler()); ChannelFuture r = ch.writeAndFlush(new ChunkedFile(TMP, 1024 * 16)); ch.close().awaitUninterruptibly(); assertFalse(r.isSuccess()); assertTrue(r.cause() instanceof RuntimeException); int read = 0; for (;;) { ByteBuf buffer = ch.readOutbound(); if (buffer == null) { break; } read += buffer.readableBytes(); buffer.release(); } assertEquals(1024 * 16 * 3, read); }</code><technical_language>need call ReferenceCountUtil.release(msg) failing promise</technical_language>

Target:
public void testFailureWhenLastChunkFailed() throws IOException { ChannelOutboundHandlerAdapter failLast = new ChannelOutboundHandlerAdapter() { private int passedWrites; @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (++this.passedWrites < 4) { ctx.write(msg, promise); } else { ReferenceCountUtil.release(msg); promise.tryFailure(new RuntimeException()); } } }; EmbeddedChannel ch = new EmbeddedChannel(failLast, new ChunkedWriteHandler()); ChannelFuture r = ch.writeAndFlush(new ChunkedFile(TMP, 1024 * 16)); assertTrue(ch.finish()); assertFalse(r.isSuccess()); assertTrue(r.cause() instanceof RuntimeException); int read = 0; for (;;) { ByteBuf buffer = ch.readOutbound(); if (buffer == null) { break; } read += buffer.readableBytes(); buffer.release(); } assertEquals(1024 * 16 * 3, read); }
Source:
<code>private void waitForLocalPlayerId() { log.debug("Getting localPlayerId from host"); String line = socket.readLine(); log.debug("got: " + line); if(line == null) { <START> log.error("Host disconnect while waiting for initial config, BAIL OUT"); <END> System.exit(-1); } try { JsonObject obj = parser.parse(line).getAsJsonObject(); setLocalPlayerId(obj.get(PROP_ROUTE_YOU_ARE).getAsInt()); log.debug("Got localPlayerId: "+getLocalPlayerId()); } catch(Exception e) { log.error("IO Exception while waiting for local player ID"); cleanup(); } }</code><technical_language>Null again... confused..</technical_language>

Target:
private void waitForLocalPlayerId() { log.debug("Getting localPlayerId from host"); String line = socket.readLine(); log.debug("got: " + line); if(!socket.isValid()) { log.error("Host disconnect while waiting for initial config, BAIL OUT"); System.exit(-1); } try { JsonObject obj = parser.parse(line).getAsJsonObject(); setLocalPlayerId(obj.get(PROP_ROUTE_YOU_ARE).getAsInt()); log.debug("Got localPlayerId: "+getLocalPlayerId()); } catch(Exception e) { log.error("IO Exception while waiting for local player ID"); cleanup(); } }
Source:
<code>public void testUserNotLoggedIn() throws Exception { currentPage.logout(); <START> AppPage.getNewPageInstance(browser, IndexPage.class); <END> ______TS("student pages"); verifyRedirectToLogin(Const.ActionURIs.STUDENT_HOME_PAGE); ______TS("instructor pages"); verifyRedirectToLogin(Const.ActionURIs.INSTRUCTOR_HOME_PAGE); ______TS("admin pages"); verifyRedirectToLogin(Const.ActionURIs.ADMIN_HOME_PAGE); }</code><technical_language>nice standardised this :+1:</technical_language>

Target:
public void testUserNotLoggedIn() throws Exception { currentPage.logout(); AppPage.getNewPageInstance(browser, HomePage.class); ______TS("student pages"); verifyRedirectToLogin(Const.ActionURIs.STUDENT_HOME_PAGE); ______TS("instructor pages"); verifyRedirectToLogin(Const.ActionURIs.INSTRUCTOR_HOME_PAGE); ______TS("admin pages"); verifyRedirectToLogin(Const.ActionURIs.ADMIN_HOME_PAGE); }
Source:
<code>private static List<Object> flattenNonRecursive(Collection<? extends Object> list) { List<Object> result = new ArrayList<>(); LinkedList<Object> stack = new LinkedList<>(list); while (!stack.isEmpty()) { Object e = stack.pop(); if (e instanceof List<?>) stack.addAll(0, (List<?>)e); else <START> result.add(e); <END> } return result; }</code><technical_language>format as: java if (e instanceof List<?>) stack.addAll(0, (List<?>)e); else result.add(e);</technical_language>

Target:
private static List<Object> flattenNonRecursive(Collection<? extends Object> list) { List<Object> result = new ArrayList<>(); for (Object item : list) { if (item instanceof List<?>) result.addAll(0, (List<?>)item); else result.add(item); } return result; }
Source:
<code>protected InputStream createFileInputStream(Path path) throws FileNotFoundException, IOException { final java.nio.file.Path nioPath = createJavaNioPath(path); InputStream stream = null; try { <START> stream = Files.newInputStream(nioPath, java.nio.file.StandardOpenOption.READ); <END> } catch (AccessDeniedException e) { throw new IOException(e.getMessage() + " (Permission denied)", e); } byte[] buf = new byte[1]; int buflen = 0; try { buflen = stream.read(buf, 0, 1); } catch (IOException e) { if (e.getMessage().equals("Is a directory")) { throw new IOException(path.toString() + " (Is a directory)", e); } throw e; } if (buflen == -1 ) { return stream; } return new SequenceInputStream(new ByteArrayInputStream(buf, 0, buflen), stream); }</code><technical_language>debugging, I culprits of breaking internal tests. is this line. I why, returning new FileInputStream(nioPath.toFile()) works, Files.newInputStream doesn't. checks for instanceof FileInputStream -- of shouldn't, do -- while love fix that, I can. So, open FileInputStream here? other error is logic in lines 490..511. Again, frustratingly, I idea wrong. considering this logic -- matter reasonable -- serve goal of this PR (i.e. support non-ASCII characters), is essential it, OK removing it</technical_language>

Target:
protected InputStream createFileInputStream(Path path) throws FileNotFoundException, IOException { return new FileInputStream(createJavaIoFile(path)); }
Source:
<code>public static void main(String[] args) { String endpoint = args[0]; String username = args[1]; String password = args[2]; ContextBuilder contextBuilder = ContextBuilder.newBuilder(DIMENSIONDATA_CLOUDCONTROL_PROVIDER); DimensionDataCloudControlApi api = contextBuilder .endpoint(endpoint) .credentials(username, password) .modules(ImmutableSet.<Module>of(new SLF4JLoggingModule())) .buildApi(DimensionDataCloudControlApi.class); <START> Injector injector = contextBuilder.buildInjector(); <END> final String networkDomainName = "jclouds-example"; String networkDomainId = getNetworkDomainId(api, networkDomainName); final String serverName = "jclouds-server"; final String vlanName = "jclouds-example-vlan"; deleteServer(api, injector, serverName); deleteVlan(api, injector, vlanName, networkDomainId); deleteNetworkDomain(api, injector, networkDomainId); deleteTagKey(api, "jclouds"); }</code><technical_language>do this, building context twice. Instead: java ApiContext<DimensionDataCloudControlApi> ctx = ContextBuilder.newBuilder(DIMENSIONDATA_CLOUDCONTROL_PROVIDER) .endpoint(endpoint) .credentials(username, password) .modules(ImmutableSet.of(new SLF4JLoggingModule())) .build(); Injector injector = ctx.utils().injector(); DimensionDataCloudControlApi api = ctx.getApi(); remember close ctx in a finally clause</technical_language>

Target:
public static void main(String[] args) { String endpoint = args[0]; String username = args[1]; String password = args[2]; try (ApiContext<DimensionDataCloudControlApi> ctx = ContextBuilder.newBuilder(DIMENSIONDATA_CLOUDCONTROL_PROVIDER) .endpoint(endpoint) .credentials(username, password) .modules(ImmutableSet.of(new SLF4JLoggingModule())) .build()) { Injector injector = ctx.utils().injector(); DimensionDataCloudControlApi api = ctx.getApi(); final String networkDomainName = "jclouds-example"; String networkDomainId = getNetworkDomainId(api, networkDomainName); final String serverName = "jclouds-server"; final String vlanName = "jclouds-example-vlan"; deleteServer(api, injector, serverName); deleteVlan(api, injector, vlanName, networkDomainId); deleteNetworkDomain(api, injector, networkDomainId); deleteTagKey(api, "jclouds"); } }
Source:
<code>private static List<Object> removeIndirection(List<Object> justificationList) { <START> final List<Object> l = justificationList.stream() <END> .flatMap(item -> { if (item instanceof LogicalTuple) { return removeIndirection((LogicalTuple) item).stream(); } else { return Stream.of(item); } }).collect(Collectors.toList()); return l; }</code><technical_language>return collect() result storing in l</technical_language>

Target:
private static List<Object> removeIndirection(List<Object> justificationList) { return justificationList.stream() .flatMap(item -> { if (item instanceof DroolsLogicalTuple) { return removeIndirection((DroolsLogicalTuple) item).stream(); } else { return Stream.of(item); } }).collect(Collectors.toList()); }
Source:
<code>private File folderWhiteListBin(File folder) { String[] children = folder.list(); <START> children = (children == null ? new String[0] : children); <END> for( int i = 0; i < children.length; i++ ) { Matcher m = WHITELIST_PATTERN.matcher(children[i]); if( m.matches()) { return new File(folder, children[i]); } } return null; }</code><technical_language>simply return null if children is null? a 0-length string effect is visible</technical_language>

Target:
private File folderWhiteListBin(File folder) { String[] children = folder.list(); if( children == null ) return null; for( int i = 0; i < children.length; i++ ) { Matcher m = WHITELIST_PATTERN.matcher(children[i]); if( m.matches()) { return new File(folder, children[i]); } } return null; }
Source:
<code>private void copyUploadDirectoryToAgents() throws IOException { log.info("WORKING DIRECTORY:" + WORKING_DIRECTORY); if (!UPLOAD_DIRECTORY.exists()) { <START> log.debug("Skipping upload, since no upload file in working directory"); <END> return; } log.info("UPLOAD DIRECTORY:" + UPLOAD_HOME); List<File> files = Utils.getFilesFromClassPath(UPLOAD_HOME); for (String ip : agentsClient.getPublicAddresses()){ for (File file : files){ String syncCommand = format("rsync -avv -e \"ssh %s\" %s %s@%s:hazelcast-stabilizer-%s/workers/%s/", props.get("SSH_OPTIONS", ""), file , props.get("USER"), ip, getVersion(), testSuite.id); bash.execute(syncCommand); } log.info(" " + ip + " copied"); } log.info(format("Finished copying '+%s+' to agents", UPLOAD_HOME)); }</code><technical_language>is a good message</technical_language>

Target:
private void copyUploadDirectoryToAgents() throws IOException { if (!UPLOAD_DIRECTORY.exists()) { log.debug("Skipping upload, since no upload file in working directory"); return; } log.info(format("Starting uploading '+%s+' to agents", UPLOAD_DIRECTORY.getAbsolutePath())); List<File> files = Utils.getFilesFromClassPath(UPLOAD_DIRECTORY.getAbsolutePath()); for (String ip : agentsClient.getPublicAddresses()){ log.info(format(" Uploading '+%s+' to agent %s", UPLOAD_DIRECTORY.getAbsolutePath(), ip)); for (File file : files){ String syncCommand = format("rsync -avv -e \"ssh %s\" %s %s@%s:hazelcast-stabilizer-%s/workers/%s/", props.get("SSH_OPTIONS", ""), file , props.get("USER"), ip, getVersion(), testSuite.id); bash.execute(syncCommand); } log.info(" " + ip + " copied"); } log.info(format("Finished uploading '+%s+' to agents", UPLOAD_DIRECTORY.getAbsolutePath())); }
Source:
<code>private Callback setProducerCallback() { return new Callback() { @Override public void onCompletion(RecordMetadata recordMetadata, Exception e) { <START> if(e != null) { <END> if(recordMetadata.topic().equals(config.getMetricTopic())) { metricLost.incrementAndGet(); } else if (recordMetadata.topic().equals(config.getAlertTopic())) { alertLost.incrementAndGet(); } else { invalidLost.incrementAndGet(); } } } }; }</code><technical_language>add log.debug("Event send failed [%s]", e.getMessage()); in case wants exception</technical_language>

Target:
private Callback setProducerCallback() { return (recordMetadata, e) -> { if (e != null) { log.debug("Event send failed [%s]", e.getMessage()); if (recordMetadata.topic().equals(config.getMetricTopic())) { metricLost.incrementAndGet(); } else if (recordMetadata.topic().equals(config.getAlertTopic())) { alertLost.incrementAndGet(); } else { invalidLost.incrementAndGet(); } } }; }
Source:
<code>public ZkRoutingDataWriter(String namespace, String zkAddress) { if (namespace == null || namespace.isEmpty()) { throw new IllegalArgumentException("namespace cannot be null or empty!"); } _namespace = namespace; if (zkAddress == null || zkAddress.isEmpty()) { throw new IllegalArgumentException("Zk address cannot be null or empty!"); } _zkAddress = zkAddress; _zkClient = DedicatedZkClientFactory.getInstance() .buildZkClient(new HelixZkClient.ZkConnectionConfig(zkAddress), new HelixZkClient.ZkClientConfig().setZkSerializer(new ZNRecordSerializer())); try { _zkClient.createPersistent(MetadataStoreRoutingConstants.ROUTING_DATA_PATH); } catch (ZkNodeExistsException e) { } <START> <END> ZNRecord myServerInfo = new ZNRecord("dummy hostname"); _leaderElection = new ZkDistributedLeaderElection(_zkClient, MetadataStoreRoutingConstants.LEADER_ELECTION_ZNODE, myServerInfo); }</code><technical_language>get hostname instead of dummy hostname</technical_language>

Target:
public ZkRoutingDataWriter(String namespace, String zkAddress) { if (namespace == null || namespace.isEmpty()) { throw new IllegalArgumentException("namespace cannot be null or empty!"); } _namespace = namespace; if (zkAddress == null || zkAddress.isEmpty()) { throw new IllegalArgumentException("Zk address cannot be null or empty!"); } _zkClient = DedicatedZkClientFactory.getInstance() .buildZkClient(new HelixZkClient.ZkConnectionConfig(zkAddress), new HelixZkClient.ZkClientConfig().setZkSerializer(new ZNRecordSerializer())); try { _zkClient.createPersistent(MetadataStoreRoutingConstants.ROUTING_DATA_PATH, true); } catch (ZkNodeExistsException e) { } ZNRecord myServerInfo = new ZNRecord("dummy hostname"); _leaderElection = new ZkDistributedLeaderElection(_zkClient, MetadataStoreRoutingConstants.LEADER_ELECTION_ZNODE, myServerInfo); }
Source:
<code>public void loadImage(String image, String filepath) throws DockerAccessException { <START> ImageName name = new ImageName(image); <END> String url = urlBuilder.loadImage(); try { delegate.post(url, new File(filepath), new BodyAndStatusResponseHandler(), HTTP_OK); } catch (IOException e) { throw new DockerAccessException(e, "Unable to load %s", filepath); } }</code><technical_language>name is</technical_language>

Target:
public void loadImage(String image, String filepath) throws DockerAccessException { String url = urlBuilder.loadImage(); try { delegate.post(url, new File(filepath), new BodyAndStatusResponseHandler(), HTTP_OK); } catch (IOException e) { throw new DockerAccessException(e, "Unable to load %s", filepath); } }
Source:
<code>private boolean isValidCardio2eDateTime (String dateTime) { boolean isValid = false; int dateTimeIntArray = cardio2eDateTimeToInt (dateTime); int year, month, day, hour, minute; Calendar myCalendar; year = dateTimeIntArray [0]; month = dateTimeIntArray [1]; day = dateTimeIntArray [2]; hour = dateTimeIntArray [3]; minute = dateTimeIntArray [4]; if ((year >= CARDIO2E_DATE_MIN_YEAR) && (year <= CARDIO2E_DATE_MAX_YEAR) && (month >=1) && (month <=12) && (day >=1) && (day <=31) && (hour >=0) && (hour <=23) && (minute >=0) && (minute <=59)){ try { myCalendar = new GregorianCalendar (year, (month-1), 1); if (day <= myCalendar.getActualMaximum(Calendar.DAY_OF_MONTH)){ isValid = true; } } catch (Exception e) { <START> e.printStackTrace(); <END> } } return isValid; }</code><technical_language>This needs a log statement</technical_language>

Target:
private boolean isValidCardio2eDateTime(String dateTime) { boolean isValid = false; int dateTimeIntArray[] = cardio2eDateTimeToInt(dateTime); int year, month, day, hour, minute; Calendar myCalendar; year = dateTimeIntArray[0]; month = dateTimeIntArray[1]; day = dateTimeIntArray[2]; hour = dateTimeIntArray[3]; minute = dateTimeIntArray[4]; if ((year >= CARDIO2E_DATE_MIN_YEAR) && (year <= CARDIO2E_DATE_MAX_YEAR) && (month >= 1) && (month <= 12) && (day >= 1) && (day <= 31) && (hour >= 0) && (hour <= 23) && (minute >= 0) && (minute <= 59)) { try { myCalendar = new GregorianCalendar(year, (month - 1), 1); if (day <= myCalendar.getActualMaximum(Calendar.DAY_OF_MONTH)) { isValid = true; } } catch (Exception ex) { isValid = false; } } return isValid; }
Source:
<code>public void setProperty(Object instance, String propertyName, Object value) throws ConversionException { try { DelegatingResourceHandler<? extends T> handler; try { handler = getResourceHandler((T) instance); } catch (Exception e) { handler = this; } Method annotatedSetter = findSetterMethod(handler, propertyName); if (annotatedSetter != null) { Type expectedType = annotatedSetter.getGenericParameterTypes()[1]; value = ConversionUtil.convert(value, expectedType); annotatedSetter.invoke(handler, instance, value); return; } String override = remappedProperties.get(propertyName); if (override != null) propertyName = override; Method setter = PropertyUtils.getPropertyDescriptor(instance, propertyName).getWriteMethod(); Type setterType = setter.getGenericParameterTypes()[0]; if (setterType instanceof TypeVariable<?>) { setterType = ConversionUtil.getTypeVariableClass(instance, (TypeVariable<?>) setterType); <START> } <END> value = ConversionUtil.convert(value, setterType); if (value instanceof Collection) { Collection<?> newCollection = (Collection<?>) value; Object oldValue = PropertyUtils.getProperty(instance, propertyName); if (oldValue instanceof Collection) { Collection collection = (Collection) oldValue; collection.clear(); collection.addAll(newCollection); } else { PropertyUtils.setProperty(instance, propertyName, value); } } else { PropertyUtils.setProperty(instance, propertyName, value); } } catch (Exception ex) { throw new ConversionException(propertyName + " on " + instance.getClass(), ex); } }</code><technical_language>I this piece is moved ConversionUtil.convert</technical_language>

Target:
public void setProperty(Object instance, String propertyName, Object value) throws ConversionException { try { DelegatingResourceHandler<? extends T> handler; try { handler = getResourceHandler((T) instance); } catch (Exception e) { handler = this; } Method annotatedSetter = findSetterMethod(handler, propertyName); if (annotatedSetter != null) { Type expectedType = annotatedSetter.getGenericParameterTypes()[1]; value = ConversionUtil.convert(value, expectedType); annotatedSetter.invoke(handler, instance, value); return; } String override = remappedProperties.get(propertyName); if (override != null) propertyName = override; Method setter = PropertyUtils.getPropertyDescriptor(instance, propertyName).getWriteMethod(); value = ConversionUtil.convert(value, setter.getGenericParameterTypes()[0], instance); if (value instanceof Collection) { Collection<?> newCollection = (Collection<?>) value; Object oldValue = PropertyUtils.getProperty(instance, propertyName); if (oldValue instanceof Collection) { Collection collection = (Collection) oldValue; collection.clear(); collection.addAll(newCollection); } else { PropertyUtils.setProperty(instance, propertyName, value); } } else { PropertyUtils.setProperty(instance, propertyName, value); } } catch (Exception ex) { throw new ConversionException(propertyName + " on " + instance.getClass(), ex); } }
Source:
<code>private Optional<APIProductIdentifier> getProductIdIfExists(ResultSet rs) throws SQLException { <START> String productProvider = rs.getString("API_TYPE"); <END> if (rs.wasNull() || StringUtils.isEmpty(productProvider)) { return Optional.empty(); } String productName = rs.getString("API_NAME"); String productVersion = rs.getString("API_VERSION"); APIProductIdentifier productIdentifier = new APIProductIdentifier (productProvider, productName, productVersion); return Optional.of(productIdentifier); }</code><technical_language>This a bug, assigning API_TYPE provider variable</technical_language>

Target:
private Optional<APIProductIdentifier> getProductIdIfExists(ResultSet rs) throws SQLException { String type = rs.getString("API_TYPE"); if (rs.wasNull() || StringUtils.isEmpty(type)) { return Optional.empty(); } String productName = rs.getString("API_NAME"); String productVersion = rs.getString("API_VERSION"); String productProvider = rs.getString("API_PROVIDER"); APIProductIdentifier productIdentifier = new APIProductIdentifier (productProvider, productName, productVersion); return Optional.of(productIdentifier); }
Source:
<code>public void findFirstAsync_emittedOnSubscribe() { realm.beginTransaction(); realm.createObject(AllTypes.class).setColumnLong(42); realm.commitTransaction(); final AllTypes asyncObj = realm.where(AllTypes.class).findFirstAsync(); subscription = asyncObj.<AllTypes>asFlowable().subscribe(rxObject -> { assertTrue(rxObject.isFrozen()); assertFalse(rxObject.isValid()); <START> if (rxObject.isLoaded()) { <END> assertTrue(rxObject.isValid()); assertEquals(42, rxObject.getColumnLong()); } else { assertFalse(rxObject.isValid()); } disposeSuccessfulTest(realm); }); }</code><technical_language>Is Realm.refresh() here</technical_language>

Target:
public void findFirstAsync_emittedOnSubscribe() { realm.beginTransaction(); realm.createObject(AllTypes.class).setColumnLong(42); realm.commitTransaction(); final AllTypes asyncObj = realm.where(AllTypes.class).findFirstAsync(); subscription = asyncObj.<AllTypes>asFlowable().subscribe(rxObject -> { assertTrue(rxObject.isFrozen()); if (rxObject.isLoaded()) { assertTrue(rxObject.isValid()); assertEquals(42, rxObject.getColumnLong()); } else { assertFalse(rxObject.isValid()); } disposeSuccessfulTest(realm); }); }
Source:
<code>public void initialize(AdvancedCache<?, ?> cache) { if (searchQuery == null) { QueryEngine<?> queryEngine = getQueryEngine(cache); searchQuery = queryEngine.buildSearchQuery(queryString, namedParameters); } <START> } <END></code><technical_language>this pass some information target type, sortable fields projections. is longer case</technical_language>

Target:
public void initialize(AdvancedCache<?, ?> cache) { if (searchQuery == null) { QueryEngine<?> queryEngine = getQueryEngine(cache); searchQuery = queryEngine.buildSearchQuery(queryString, namedParameters); if (timeout > 0) { searchQuery.failAfter(timeout, TimeUnit.NANOSECONDS); } } }
Source:
<code>public void testGetAttributeAsDoubleList() { final VariantContext context = basicBuilder .attribute("DefaultIntegerList", new int[5]) .attribute("ListWithMissing", new Object[]{1, null, null}) .attribute("IntegerList", new int[]{0, 1, 2, 3}) .attribute("DoubleList", new double[]{1.8, 1.6, 2.1}) .attribute("StringList", new String[]{"1", "2"}) .attribute("NotNumeric", new String[]{"A", "B"}) .make(); Assert.assertEquals(context.getAttributeAsDoubleList("DefaultIntegerList", 5), Arrays.asList(0d, 0d, 0d, 0d, 0d)); Assert.assertEquals(context.getAttributeAsDoubleList("ListWithMissing", 5), Arrays.asList(1d, 5d, 5d)); Assert.assertEquals(context.getAttributeAsDoubleList("IntegerList", 5), Arrays.asList(0d, 1d, 2d, 3d)); Assert.assertEquals(context.getAttributeAsDoubleList("DoubleList", 5), Arrays.asList(1.8, 1.6, 2.1)); Assert.assertEquals(context.getAttributeAsDoubleList("StringList", 5), Arrays.asList(1d, 2d)); try { context.getAttributeAsIntList("NotNumeric", 5); <START> Assert.fail(); <END> } catch (Exception e) { } }</code><technical_language>point of this try/catch block</technical_language>

Target:
public void testGetAttributeAsDoubleList() { final VariantContext context = basicBuilder .attribute("Empty", new int[0]) .attribute("DefaultIntegerList", new int[5]) .attribute("ListWithMissing", new Object[]{1, null, null}) .attribute("IntegerList", new int[]{0, 1, 2, 3}) .attribute("DoubleList", new double[]{1.8, 1.6, 2.1}) .attribute("StringList", new String[]{"1", "2"}) .attribute("NotNumeric", new String[]{"A", "B"}) .make(); Assert.assertTrue(context.getAttributeAsDoubleList("Empty", 5).isEmpty()); Assert.assertEquals(context.getAttributeAsDoubleList("DefaultIntegerList", 5), Arrays.asList(0d, 0d, 0d, 0d, 0d)); Assert.assertEquals(context.getAttributeAsDoubleList("ListWithMissing", 5), Arrays.asList(1d, 5d, 5d)); Assert.assertEquals(context.getAttributeAsDoubleList("IntegerList", 5), Arrays.asList(0d, 1d, 2d, 3d)); Assert.assertEquals(context.getAttributeAsDoubleList("DoubleList", 5), Arrays.asList(1.8, 1.6, 2.1)); Assert.assertEquals(context.getAttributeAsDoubleList("StringList", 5), Arrays.asList(1d, 2d)); Assert.assertThrows(() -> context.getAttributeAsDoubleList("NotNumeric", 5)); Assert.assertTrue(context.getAttributeAsDoubleList("MissingList", 5).isEmpty()); }
Source:
<code>public AWSRequestSignerV4(String identity, String credential, Crypto crypto) { this.crypto = crypto; this.identity = identity; <START> this.credential = credential; <END> }</code><technical_language>above. Add Preconditions.checkNotNull checks mandatory fields</technical_language>

Target:
public AWSRequestSignerV4(String identity, String credential, Crypto crypto) { this.crypto = checkNotNull(crypto); this.identity = checkNotNull(identity); this.credential = checkNotNull(credential); }
Source:
<code>public void testProtectedEndpointBadCredentials401() { try { RULE.getJerseyTest().target("/protected").request() .header(HttpHeaders.AUTHORIZATION, "Basic c25lYWt5LWJhc3RhcmQ6YXNkZg==") .get(String.class); <START> failBecauseExceptionWasNotThrown(WebApplicationException.class); <END> } catch (WebApplicationException e) { assertThat(e.getResponse().getStatus()).isEqualTo(401); assertThat(e.getResponse().getHeaders().get(HttpHeaders.WWW_AUTHENTICATE)) .containsOnly("Basic realm=\"SUPER SECRET STUFF\""); } }</code><technical_language>question NotAuthorizedException</technical_language>

Target:
public void testProtectedEndpointBadCredentials401() { try { RULE.getJerseyTest().target("/protected").request() .header(HttpHeaders.AUTHORIZATION, "Basic c25lYWt5LWJhc3RhcmQ6YXNkZg==") .get(String.class); failBecauseExceptionWasNotThrown(NotAuthorizedException.class); } catch (NotAuthorizedException e) { assertThat(e.getResponse().getStatus()).isEqualTo(401); assertThat(e.getResponse().getHeaders().get(HttpHeaders.WWW_AUTHENTICATE)) .containsOnly("Basic realm=\"SUPER SECRET STUFF\""); } }
Source:
<code>public static <T extends CoveragePoNNormalizationResult> List<String> retrieveSamplesWithArmLevelEvents(final CoveragePanelOfNormals<T> qcPoN, final JavaSparkContext ctx) { Utils.nonNull(qcPoN, "QC PoN cannot be null."); final List<String> result; logger.info("Tangent normalizing all normals in the PoN..."); final CoveragePoNNormalizationResult qcNormalization = qcPoN.normalizeNormalsInPoN(ctx); final Map<String, Double> contigToMedian = getContigToMedianCRMap(qcNormalization.getProfile()); if (ctx == null) { final List<ReadCountCollection> singleSampleTangentNormalizedReadCounts = createIndividualReadCountCollections(qcNormalization.getProfile()); <START> result = identifySamplesWithSuspiciousContigs(singleSampleTangentNormalizedReadCounts, contigToMedian); <END> } else { final JavaRDD<ReadCountCollection> parallelSingleSampleTangentNormalizedReadCounts = createParallelIndividualReadCountCollections(qcNormalization.getProfile(), ctx); result = identifySamplesWithSuspiciousContigs(parallelSingleSampleTangentNormalizedReadCounts, ctx, contigToMedian); } return result; }</code><technical_language>Instead of declaring result initializing above, return identifySamplesWith. . . below</technical_language>

Target:
public static <T extends CoveragePoNNormalizationResult> List<String> retrieveSamplesWithArmLevelEvents(final CoveragePanelOfNormals<T> qcPoN, final JavaSparkContext ctx) { Utils.nonNull(qcPoN, "QC PoN cannot be null."); logger.info("Tangent normalizing all normals in the PoN..."); final CoveragePoNNormalizationResult qcNormalization = qcPoN.normalizeNormalsInPoN(ctx); final Map<String, Double> contigToMedian = getContigToMedianCRMap(qcNormalization.getProfile()); if (ctx == null) { final List<ReadCountCollection> singleSampleTangentNormalizedReadCounts = createIndividualReadCountCollections(qcNormalization.getProfile()); return identifySamplesWithSuspiciousContigs(singleSampleTangentNormalizedReadCounts, contigToMedian); } final JavaRDD<ReadCountCollection> parallelSingleSampleTangentNormalizedReadCounts = createParallelIndividualReadCountCollections(qcNormalization.getProfile(), ctx); return identifySamplesWithSuspiciousContigs(parallelSingleSampleTangentNormalizedReadCounts, ctx, contigToMedian); }
Source:
<code>public static void deleteTempDirectory(File temp) throws IOException { File[] files = temp.listFiles(); <START> if (files != null) { END> for (File f : files) { if (f.isDirectory()) { deleteTempDirectory(f); } else { if (!(f.delete())) { throw new IOException("Could not delete temp file: " + f.getAbsolutePath()); } } } } if (!(temp.delete())) { throw new IOException( "Could not delete temp file: " + temp.getAbsolutePath()); } }</code><technical_language>FileUtils.delete() instead</technical_language>

Target:
public static void deleteTempDirectory(File temp) throws IOException { File[] files = temp.listFiles(); if (files != null) { for (File f : files) { if (f.isDirectory()) { deleteTempDirectory(f); } else { f.delete(); } } } if (!(temp.delete())) { throw new IOException( "Could not delete temp file: " + temp.getAbsolutePath()); } }
Source:
<code>public ValidationResult profileValid(Guid clusterId) { if (nic.getVnicProfileId() != null) { VnicProfile vnicProfile = getDbFacade().getVnicProfileDao().get(nic.getVnicProfileId()); if (vnicProfile == null) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_VNIC_PROFILE_NOT_EXISTS); } Network network = getNetworkByVnicProfile(vnicProfile); if (network == null || !isNetworkInCluster(network, clusterId)) { return new ValidationResult(VdcBllMessages.NETWORK_NOT_EXISTS_IN_CURRENT_CLUSTER); } if (!FeatureSupported.networkQoS(version) <START> && getDbFacade().getQosDao().get(vnicProfile.getNetworkQosId()) != null) <END> return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_NETWROK_QOS_IS_NOT_SUPPORTED, clusterVersion()); } return ValidationResult.VALID; }</code><technical_language>I need verify existence of networkQoS in database. is enough block operation if user selected a vnic profile vnicProfile.getNetworkQosId() is other null</technical_language>

Target:
public ValidationResult profileValid(Guid clusterId) { if (nic.getVnicProfileId() != null) { VnicProfile vnicProfile = getDbFacade().getVnicProfileDao().get(nic.getVnicProfileId()); if (vnicProfile == null) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_VNIC_PROFILE_NOT_EXISTS); } Network network = getNetworkByVnicProfile(vnicProfile); if (network == null || !isNetworkInCluster(network, clusterId)) { return new ValidationResult(VdcBllMessages.NETWORK_NOT_EXISTS_IN_CURRENT_CLUSTER); } if (!FeatureSupported.networkQoS(version) && vnicProfile.getNetworkQosId() != null) return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_NETWROK_QOS_IS_NOT_SUPPORTED, clusterVersion()); } return ValidationResult.VALID; }
Source:
<code>public static OcrTranslateApiMessage fromPubsubData(byte[] data) throws IllegalArgumentException { String jsonStr = new String(Base64.getDecoder().decode(data)); OcrTranslateApiMessage ocrMessage = gson.fromJson(jsonStr, OcrTranslateApiMessage.class); <START> String text = ocrMessage.getText(); String filename = ocrMessage.getFilename(); String targetLang = ocrMessage.getLang(); <END> if (text == null) { throw new IllegalArgumentException("Missing text parameter"); } if (filename == null) { throw new IllegalArgumentException("Missing filename parameter"); } if (targetLang == null) { throw new IllegalArgumentException("Missing lang parameter"); } return ocrMessage; }</code><technical_language>class, access directly. reason accessors</technical_language>

Target:
public static OcrTranslateApiMessage fromPubsubData(byte[] data) { String jsonStr = new String(Base64.getDecoder().decode(data), StandardCharsets.UTF_8); Map<String, String> jsonMap = gson.fromJson(jsonStr, Map.class); return new OcrTranslateApiMessage( jsonMap.get("text"), jsonMap.get("filename"), jsonMap.get("lang")); }
Source:
<code>public static void setTool(Tool tool) { if (K.tool != null) { assert false : "Can only call setTool once"; <START> } <END> K.tool = tool; }</code><technical_language>java assert (K.tool == null) : "Can call setTool once"; instead</technical_language>

Target:
public static void setTool(Tool tool) { assert K.tool == null : "Can only call setTool once"; K.tool = tool; }
Source:
<code>private void evaluateMaintenanceHostCommandProgress(List<Guid> childCmdIds, CommandBase<?> rootCommand) { UpgradeHostParameters parameters = (UpgradeHostParameters) rootCommand.getParameters(); VdsDynamic host = vdsDynamicDao.get(parameters.getVdsId()); switch (host.getStatus()) { case PreparingForMaintenance: break; case Maintenance: switch (getMaintenanceCmdStatus(childCmdIds)) { case FAILED: case ENDED_WITH_FAILURE: log.info("Host '{}' is on maintenance mode. But not invoking Upgrade process because moving to " + "maintenance completed with failure, please see logs for details.", getHostName(parameters.getVdsId())); handleActionFailed(rootCommand, parameters); break; case SUCCEEDED: case ENDED_SUCCESSFULLY: log.info("Host '{}' is on maintenance mode. Proceeding with Upgrade process.", getHostName(parameters.getVdsId())); invokeHostUpgrade(rootCommand, parameters); break; case <START> UNKNOWN: <END> if (childCmdIds.isEmpty()) { log.info("Host '{}' is on maintenance mode. Proceeding with Upgrade process.", getHostName(parameters.getVdsId())); invokeHostUpgrade(rootCommand, parameters); } break; default: break; } break; default: if (isMaintenanceCommandExecuted(childCmdIds) || hasMaintenanceCmdFailed(childCmdIds)) { handleActionFailed(rootCommand, parameters); } break; } }</code><technical_language>Is a possibility UNKNOWN set for this host for other cases proceed maintenance if desired case ? UNKNOWN is default status if callback set only</technical_language>

Target:
private void evaluateMaintenanceHostCommandProgress(List<Guid> childCmdIds, CommandBase<?> rootCommand) { UpgradeHostParameters parameters = (UpgradeHostParameters) rootCommand.getParameters(); VdsDynamic host = vdsDynamicDao.get(parameters.getVdsId()); switch (host.getStatus()) { case PreparingForMaintenance: break; case Maintenance: if (childCmdIds.isEmpty()) { logAndinvokeHostUpgrade(rootCommand, parameters); break; } switch (getMaintenanceCmdStatus(childCmdIds)) { case FAILED: case ENDED_WITH_FAILURE: log.info("Host '{}' is on maintenance mode. But not invoking Upgrade process because moving to " + "maintenance completed with failure, please see logs for details.", getHostName(parameters.getVdsId())); handleActionFailed(rootCommand, parameters); break; case SUCCEEDED: case ENDED_SUCCESSFULLY: logAndinvokeHostUpgrade(rootCommand, parameters); break; case UNKNOWN: log.info("Host '{}' is on maintenance mode. But not invoking Upgrade process because moving to " + "maintenance command is in UNKNOWN status.", getHostName(parameters.getVdsId())); break; default: log.info("Host '{}' is on maintenance mode. But not invoking Upgrade process because moving to " + "maintenance command is in unhandled status '{}'.", getHostName(parameters.getVdsId()), host.getStatus()); break; } break; default: if (isMaintenanceCommandExecuted(childCmdIds) || hasMaintenanceCmdFailed(childCmdIds)) { handleActionFailed(rootCommand, parameters); } break; } }
Source:
<code>public Clue investigate() { <START> if (getResponse() == null || getResponse().getCrn() == null || getResponse().getStackV4Response() == null) { <END> return null; } AuditEventV4Responses auditEvents = AuditUtil.getAuditEvents( getTestContext().getMicroserviceClient(CloudbreakClient.class), CloudbreakEventService.DATAHUB_RESOURCE_TYPE, null, getResponse().getCrn()); boolean hasSpotTermination = getResponse().getStackV4Response().getInstanceGroups().stream() .flatMap(ig -> ig.getMetadata().stream()) .anyMatch(metadata -> InstanceStatus.DELETED_BY_PROVIDER == metadata.getInstanceStatus()); return new Clue("SDX", auditEvents, getResponse(), hasSpotTermination); }</code><technical_language>If a crn in response stackresponse, means response other useful info in it. I a solution handle NPE in hasSpotTermination assignment, this: boolean hasSpotTermination = Optional.ofNullable(getResponse().getStackV4Response()) .map(stack -> stack.getInstanceGroups()) .stream() .flatMap(ig -> ig.getMetadata().stream()) .anyMatch(metadata -> InstanceStatus.DELETED_BY_PROVIDER == metadata.getInstanceStatus()); This add response report NPE. is other Investigables this issue, please check too</technical_language>

Target:
public Clue investigate() { if (getResponse() == null || getResponse().getCrn() == null) { return null; } AuditEventV4Responses auditEvents = AuditUtil.getAuditEvents( getTestContext().getMicroserviceClient(CloudbreakClient.class), CloudbreakEventService.DATAHUB_RESOURCE_TYPE, null, getResponse().getCrn()); boolean hasSpotTermination = (getResponse().getStackV4Response() == null) ? false : getResponse().getStackV4Response().getInstanceGroups().stream() .flatMap(ig -> ig.getMetadata().stream()) .anyMatch(metadata -> InstanceStatus.DELETED_BY_PROVIDER == metadata.getInstanceStatus()); return new Clue("SDX", auditEvents, getResponse(), hasSpotTermination); }
Source:
<code><START> private String initMatchOwnerEntityNode(EntityKeyMetadata ownerEntityKeyMetadata) { <END> StringBuilder queryBuilder = new StringBuilder( "MATCH " ); appendEntityNode( "owner", ownerEntityKeyMetadata, queryBuilder ); return queryBuilder.toString(); }</code><technical_language>static</technical_language>

Target:
private static String initMatchOwnerEntityNode(EntityKeyMetadata ownerEntityKeyMetadata) { StringBuilder queryBuilder = new StringBuilder(); appendMatchOwnerEntityNode( queryBuilder, ownerEntityKeyMetadata ); return queryBuilder.toString(); }
Source:
<code>public String toString() { <START> return MoreObjects.toStringHelper(this) <END> .add("configurationBinding", configurationBinding) .toString(); }</code><technical_language>Static import</technical_language>

Target:
public String toString() { return toStringHelper(this) .add("configurationBinding", configurationBinding) .toString(); }
Source:
<code>private boolean generateDefaultDomainName (final Configuration configuration, final DaoManager storage) { try{ final String defaultOrganization = "ORafbe225ad37541eba518a74248f0ac4c"; final String hostname = configuration.getString("hostname"); Organization organization = storage.getOrganizationsDao().getOrganization(new Sid(defaultOrganization)); <START> if(organization != null){ <END> if(hostname != null && !hostname.trim().equals("")){ if(logger.isInfoEnabled()) logger.info("Generate Default Domain Name based on RC hostname: "+hostname); organization = organization.setDomainName(hostname); storage.getOrganizationsDao().updateOrganization(organization); }else{ logger.error("Unable to generateDefaultDomainName hostname property is null in restcomm.xml"); return false; } }else{ logger.error("Unable to generateDefaultDomainName default org not found"); return false; } }catch(Exception e){ logger.error("Unable to generateDefaultDomainName {}", e); return false; } return true; }</code><technical_language>@maria-farooq create a new Organization in case default is null</technical_language>

Target:
private boolean generateDefaultDomainName (final Configuration configuration, final DaoManager storage) { try{ final Sid defaultOrganization = new Sid("ORafbe225ad37541eba518a74248f0ac4c"); final String hostname = configuration.getString("hostname"); if(hostname != null && !hostname.trim().equals("")){ if(logger.isInfoEnabled()) logger.info("Generate Default Domain Name based on RC hostname: "+hostname); }else{ logger.error("Unable to generateDefaultDomainName hostname property is null in restcomm.xml"); return false; } Organization organization = storage.getOrganizationsDao().getOrganization(defaultOrganization); if(organization == null){ storage.getOrganizationsDao().addOrganization(new Organization(defaultOrganization, hostname, DateTime.now(), DateTime.now())); }else{ organization = organization.setDomainName(hostname); storage.getOrganizationsDao().updateOrganization(organization); } }catch(Exception e){ logger.error("Unable to generateDefaultDomainName {}", e); return false; } return true; }
Source:
<code>public JSONObject sendHarbormasterMessage(String phid, boolean pass, UnitResults unitResults, Map<String, String> coverage) throws ConduitAPIException, IOException { <START> JSONObject params = new JSONObject(); <END> params.element("type", pass ? "pass" : "fail") .element("buildTargetPHID", phid); List<JSONObject> unit = new ArrayList<JSONObject>(); if (unitResults != null) { unit.addAll(unitResults.toHarbormaster()); } if (coverage != null) { JSONObject coverageUnit = new JSONObject() .element("result", "pass") .element("name", "Coverage Data") .element("coverage", coverage); unit.add(coverageUnit); } if (!unit.isEmpty()) { params.element("unit", unit); } return this.callConduit("harbormaster.sendmessage", params); }</code><technical_language>craft params JSON end</technical_language>

Target:
public JSONObject sendHarbormasterMessage(String phid, boolean pass, UnitResults unitResults, Map<String, String> coverage) throws ConduitAPIException, IOException { List<JSONObject> unit = new ArrayList<JSONObject>(); if (unitResults != null) { unit.addAll(unitResults.toHarbormaster()); } if (coverage != null) { JSONObject coverageUnit = new JSONObject() .element("result", "pass") .element("name", "Coverage Data") .element("coverage", coverage); unit.add(coverageUnit); } JSONObject params = new JSONObject(); params.element("type", pass ? "pass" : "fail") .element("buildTargetPHID", phid); if (!unit.isEmpty()) { params.element("unit", unit); } return this.callConduit("harbormaster.sendmessage", params); }
Source:
<code>private Optional<X509Certificate> getClientCertFromXfccHeaderEnvoyFormatted( List<String> xfccHeaderValues) { if (xfccHeaderValues.size() == 0) { return Optional.empty(); } else if (xfccHeaderValues.size() > 1) { <START> logger.warn("Keywhiz only supports one certificate set in the header", XFCC_HEADER_NAME); <END> return Optional.empty(); } String[] keyValuePairs = xfccHeaderValues.get(0).split(";"); for (String pair : keyValuePairs) { String[] keyValue = pair.split("="); if (keyValue.length != 2) { logger.warn("Got entry in header that wasn't a key/value pair: {}", XFCC_HEADER_NAME, pair); continue; } if (!CERT_KEY.equals(keyValue[0])) { continue; } return parseCertFromCertField(keyValue[1]); } logger.warn("Unable to find in header; no client ID parsed from header", CERT_KEY, XFCC_HEADER_NAME); return Optional.empty(); }</code><technical_language>cleaner multiple certs found, is supported. reader of this error message needs guess happened</technical_language>

Target:
private Optional<X509Certificate> getClientCertFromXfccHeaderEnvoyFormatted( List<String> xfccHeaderValues) { if (xfccHeaderValues.size() == 0) { return Optional.empty(); } else if (xfccHeaderValues.size() > 1) { logger.warn( "Keywhiz only supports one header, but were provided", XFCC_HEADER_NAME, xfccHeaderValues.size()); return Optional.empty(); } XfccHeader xfccHeader; try { xfccHeader = XfccHeader.parse(xfccHeaderValues.get(0)); } catch (XfccHeader.ParseException e) { logger.warn(format("Unable to parse input %s header", XFCC_HEADER_NAME), e); return Optional.empty(); } if (xfccHeader.elements.length == 0) { logger.warn("No data provided in header", XFCC_HEADER_NAME); return Optional.empty(); } else if (xfccHeader.elements.length > 1) { logger.warn( "Keywhiz only supports one certificate set in the header, but were provided", XFCC_HEADER_NAME, xfccHeader.elements.length); return Optional.empty(); } List<String> certValues = Arrays.stream(xfccHeader.elements[0].pairs) .filter((pair) -> CERT_KEY.equalsIgnoreCase(pair.key)) .map((pair) -> pair.value) .collect(Collectors.toUnmodifiableList()); if (certValues.size() == 0) { logger.warn("Unable to find in header; no client ID parsed from header", CERT_KEY, XFCC_HEADER_NAME); return Optional.empty(); } else if (certValues.size() > 1) { logger.warn( "Keywhiz only supports one key in the header, but were provided", CERT_KEY, XFCC_HEADER_NAME, certValues.size()); return Optional.empty(); } return parseUrlEncodedPem(certValues.get(0)); }
Source:
<code>public Potion getPotion() { <START> return toRemove; <END> }</code><technical_language>getPotion() return a field named potion. toRemove is a good name here, match</technical_language>

Target:
public Potion getPotion() { return this.potion; }
Source:
<code>public T moveTo(int x, int y) { <START> return moveTo(useAbsolute(x, y)); <END> }</code><technical_language>@param x change in x coordinate move through. - @param y change in y coordinate move through</technical_language>

Target:
public T moveTo(int x, int y) { return moveTo(point(x, y)); }
Source:
<code>public void fetchKeysAndValuesInvokesGetValuesForKeys() throws Exception { PartitionedRegion spyPartitionedRegion = spy(partitionedRegion); VersionedObjectList values = mock(VersionedObjectList.class); ServerConnection serverConnection = mock(ServerConnection.class); Set<Integer> failures = mock(Set.class); InternalDistributedMember member = mock(InternalDistributedMember.class); Set<Integer> buckets = new HashSet<>(); buckets.add(1); FetchKeysMessage.FetchKeysResponse fetchKeysResponse = mock(FetchKeysMessage.FetchKeysResponse.class); doReturn(fetchKeysResponse).when(spyPartitionedRegion).getFetchKeysResponse(member, 1); <START> Set keys = mock(Set.class); <END> when(fetchKeysResponse.waitForKeys()).thenReturn(keys); doNothing().when(spyPartitionedRegion).getValuesForKeys(values, serverConnection, keys); spyPartitionedRegion.fetchKeysAndValues(values, serverConnection, failures, member, null, buckets); verify(failures, never()).add(1); verify(spyPartitionedRegion).getValuesForKeys(values, serverConnection, keys); }</code><technical_language>a real Set instead of a mock</technical_language>

Target:
public void fetchKeysAndValuesInvokesGetValuesForKeys() throws Exception { PartitionedRegion spyPartitionedRegion = spy(partitionedRegion); VersionedObjectList values = mock(VersionedObjectList.class); ServerConnection serverConnection = mock(ServerConnection.class); Set<Integer> failures = new HashSet<>(); InternalDistributedMember member = mock(InternalDistributedMember.class); Set<Integer> buckets = new HashSet<>(); buckets.add(1); FetchKeysMessage.FetchKeysResponse fetchKeysResponse = mock(FetchKeysMessage.FetchKeysResponse.class); doReturn(fetchKeysResponse).when(spyPartitionedRegion).getFetchKeysResponse(member, 1); Set keys = new HashSet(); when(fetchKeysResponse.waitForKeys()).thenReturn(keys); doNothing().when(spyPartitionedRegion).getValuesForKeys(values, serverConnection, keys); spyPartitionedRegion.fetchKeysAndValues(values, serverConnection, failures, member, null, buckets); verify(spyPartitionedRegion).getValuesForKeys(values, serverConnection, keys); assertThat(failures.contains(1)).isFalse(); }