auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
SolrQuery getQuery() { StringBuilder querySB = new StringBuilder(); if (StringUtils.isNotBlank(afterDate) && StringUtils.isNotBlank(beforeDate)) { querySB.append("[").append(afterDate).append(" TO ").append(beforeDate).append("]"); } else if (StringUtils.isNotBlank(afterDate) && StringUtils.isBlank(beforeDate)) { querySB.append("[").append(afterDate).append(" TO NOW").append("]"); } else if (StringUtils.isBlank(afterDate) && StringUtils.isNotBlank(beforeDate)) { querySB.append("[").append(EARLY_TIME).append(" TO ").append(beforeDate).append("]"); } SolrQuery query; if (querySB.length() > 0) { query = new SolrQuery(field + ":" + querySB.toString()); } else { query = new SolrQuery("*:*"); } SortClause sort = new SortClause("metacard.created_tdt", ORDER.desc); query.setSort(sort); query.addSort(new SortClause("id_txt", ORDER.desc)); query.setParam(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark); query.setRows(Math.max(PAGE_SIZE, WRITE_TXN_SIZE)); return query; }

Target:
SolrQuery getQuery() { StringBuilder querySB = new StringBuilder(); if (StringUtils.isNotBlank(afterDate) && StringUtils.isNotBlank(beforeDate)) { querySB.append("[").append(afterDate).append(" TO ").append(beforeDate).append("]"); } else if (StringUtils.isNotBlank(afterDate) && StringUtils.isBlank(beforeDate)) { querySB.append("[").append(afterDate).append(" TO NOW").append("]"); } else if (StringUtils.isBlank(afterDate) && StringUtils.isNotBlank(beforeDate)) { querySB.append("[").append(EARLY_TIME).append(" TO ").append(beforeDate).append("]"); } SolrQuery query; if (querySB.length() > 0) { query = new SolrQuery(field + ":" + querySB.toString()); } else { query = new SolrQuery("*:*"); } SortClause sort = new SortClause("metacard.modified_tdt", ORDER.desc); query.setSort(sort); query.addSort(new SortClause("id_txt", ORDER.desc)); query.setParam(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark); query.setRows(PAGE_SIZE); return query; }
Source:
public SynchronizationBackend(File syncFile, boolean throwErrors) throws IOException { int res; fSyncFile = syncFile; if (syncFile == null) { return; } if (!syncFile.exists()) { if (throwErrors) { throw new IOException("Selected synchronization file does not exist"); } return; } if (syncFile.length() <= 0) { if (throwErrors) { throw new IOException("Invalid synchronization file selected, " + "target file is empty"); } return; } FileInputStream fis = new FileInputStream(syncFile); ByteBuffer buffer = ByteBuffer.allocate(HEADER_SIZE); FileChannel fc = fis.getChannel(); buffer.clear(); fc.read(buffer); buffer.flip(); res = buffer.getInt(); if (res != SYNC_FILE_MAGIC_NUMBER) { fc.close(); fis.close(); throw new IOException("Selected file does not" + "look like a synchronization file"); } res = buffer.getInt(); if (res != MAJOR_VERSION) { fc.close(); fis.close(); throw new IOException("Select synchronization file is of an older " + "format. Synchronization will have to be computed again."); } res = buffer.getInt(); fc.close(); fis.close(); }

Target:
public SynchronizationBackend(File syncFile, boolean throwErrors) throws IOException { int res; fSyncFile = syncFile; if (syncFile == null) { return; } if (!syncFile.exists()) { if (throwErrors) { throw new IOException("Selected synchronization file does not exist"); } return; } if (syncFile.length() <= 0) { if (throwErrors) { throw new IOException("Invalid synchronization file selected, " + "target file is empty"); } return; } FileInputStream fis = new FileInputStream(syncFile); ByteBuffer buffer = ByteBuffer.allocate(HEADER_SIZE); FileChannel fc = fis.getChannel(); buffer.clear(); fc.read(buffer); buffer.flip(); res = buffer.getInt(); if (res != SYNC_FILE_MAGIC_NUMBER) { fc.close(); fis.close(); throw new IOException("Selected file does not" + "look like a synchronization file"); } res = buffer.getInt(); if (res != FILE_VERSION) { fc.close(); fis.close(); throw new IOException("Select synchronization file is of an older " + "format. Synchronization will have to be computed again."); } res = buffer.getInt(); fc.close(); fis.close(); }
Source:
private static File getTempDir() { File tempDir; if (System.getProperty("os.name").toLowerCase().equals("linux")){ tempDir = new File("/var/tmp"); }else { tempDir = new File(System.getProperty("java.io.tmpdir")); } if (tempDir.exists() && tempDir.isDirectory() && tempDir.canWrite()) { return tempDir; } try { File tempFile = File.createTempFile("_ganttproject_autosave", ".empty"); tempDir = tempFile.getParentFile(); if (tempDir.exists() && tempDir.isDirectory() && tempDir.canWrite()) { return tempDir; } } catch (IOException e) { GPLogger.getLogger(DocumentManager.class).log(Level.WARNING, "Can't get parent of the temp file", e); } GPLogger.getLogger(DocumentManager.class).warning("Failed to find temporary directory"); return null; }

Target:
private static File getTempDir() { File tempDir; if (SystemUtils.IS_OS_LINUX ){ tempDir = new File("/var/tmp"); if (tempDir.exists() && tempDir.isDirectory() && tempDir.canWrite()) { return tempDir; } } tempDir = new File(System.getProperty("java.io.tmpdir")); if (tempDir.exists() && tempDir.isDirectory() && tempDir.canWrite()) { return tempDir; } try { File tempFile = File.createTempFile("_ganttproject_autosave", ".empty"); tempDir = tempFile.getParentFile(); if (tempDir.exists() && tempDir.isDirectory() && tempDir.canWrite()) { return tempDir; } } catch (IOException e) { GPLogger.getLogger(DocumentManager.class).log(Level.WARNING, "Can't get parent of the temp file", e); } GPLogger.getLogger(DocumentManager.class).warning("Failed to find temporary directory"); return null; }
Source:
protected boolean AddVmImages() { List<DiskImage> disks = DbFacade.getInstance().getDiskImageDAO().getAllForVm( getParameters().getVmStaticData().getvmt_guid()); if (disks.isEmpty() && !getParameters().getVmStaticData().getvmt_guid().equals(Guid.Empty)) { throw new VdcBLLException(VdcBllErrors.VM_TEMPLATE_CANT_LOCATE_DISKS_IN_DB); } DiskImageBase defBootDisk = LinqUtils.firstOrNull(getVmDisks(), new Predicate<DiskImageBase>() { @Override public boolean eval(DiskImageBase diskImageBase) { return diskImageBase.getboot(); } }); if (defBootDisk != null) { for (DiskImageBase diskImageBase : getVmDisks()) { if (diskImageBase != defBootDisk) diskImageBase.setboot(false); } } return (disks.size()>0) ? ConcreteAddVmImages(disks.get(0).getId()): true; }

Target:
protected boolean AddVmImages() { List<DiskImage> disks = DbFacade.getInstance().getDiskImageDAO().getAllForVm( getParameters().getVmStaticData().getvmt_guid()); if (disks.isEmpty() && !getParameters().getVmStaticData().getvmt_guid().equals(Guid.Empty)) { throw new VdcBLLException(VdcBllErrors.VM_TEMPLATE_CANT_LOCATE_DISKS_IN_DB); } DiskImageBase defBootDisk = LinqUtils.firstOrNull(getVmDisks(), new Predicate<DiskImageBase>() { @Override public boolean eval(DiskImageBase diskImageBase) { return diskImageBase.getboot(); } }); if (defBootDisk != null) { for (DiskImageBase diskImageBase : getVmDisks()) { if (diskImageBase != defBootDisk) diskImageBase.setboot(false); } } return (!disks.isEmpty()) ? ConcreteAddVmImages(disks.get(0).getId()) : true; }
Source:
private DefaultEnvironment buildEnvironment(EnvironmentType environmentType) { DefaultEnvironment defaultEnvironment = new DefaultEnvironment(environmentType); defaultEnvironment.setup(); return defaultEnvironment; }

Target:
private DefaultEnvironment buildEnvironment(EnvironmentType environmentType) { DefaultEnvironment defaultEnvironment = new DefaultEnvironment(environmentType); return defaultEnvironment; }
Source:
private SelectionListener createListener() { final SelectionListener listener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { resetProperties(); } @Override public void widgetDefaultSelected(SelectionEvent e) { } }; return listener; }

Target:
private SelectionListener createListener() { final SelectionListener listener = new SelectionListener() { @Override public void widgetSelected(final SelectionEvent e) { resetProperties(); } @Override public void widgetDefaultSelected(final SelectionEvent e) { } }; return listener; }
Source:
static ChannelStateWriteRequest write(long checkpointId, InputChannelInfo info, CloseableIterator<Buffer> iterator) { return new CheckpointInProgressRequest( "writeInput", checkpointId, writer -> { while (iterator.hasNext()) { Buffer buffer = iterator.next(); checkArgument(buffer.isBuffer()); writer.writeInput(info, buffer); } }, throwable -> { try { iterator.close(); } catch (Exception e) { final RuntimeException re = new RuntimeException("unable to close iterator", e); re.addSuppressed(throwable); throw re; } }, false); }

Target:
static ChannelStateWriteRequest write(long checkpointId, InputChannelInfo info, CloseableIterator<Buffer> iterator) { return new CheckpointInProgressRequest( "writeInput", checkpointId, writer -> { while (iterator.hasNext()) { Buffer buffer = iterator.next(); try { checkArgument(buffer.isBuffer()); } catch (Exception e) { buffer.recycleBuffer(); throw e; } writer.writeInput(info, buffer); } }, throwable -> iterator.close(), false); }
Source:
public ClientSession getClientSession(boolean transacted) throws Exception { log.debug("Creating new ActiveMQ session..."); ClientSessionFactory csf = this.getClientSessionFactory(); ClientSession session = transacted ? csf.createTransactedSession() : csf.createSession(true, false); log.debug("Created new ActiveMQ session: {}", session); return session; }

Target:
public ClientSession getClientSession(boolean transacted) throws Exception { log.debug("Creating new ActiveMQ session..."); ClientSessionFactory csf = this.getClientSessionFactory(); ClientSession session = transacted ? csf.createTransactedSession() : csf.createSession(); log.debug("Created new ActiveMQ session: {}", session); return session; }
Source:
public void setParent(@Nullable Node parent, @Nullable MethodYield methodYield) { if (parent != null) { if (parents.isEmpty()) { programState.constraints.forEach((sv, c) -> { if (parent.programState.getConstraint(sv) != c) { addConstraint(sv, c); } }); programState.values.forEach((s, sv) -> { if (parent.programState.getValue(s) != sv) { learnedSymbols.add(new LearnedValue(sv, s)); } }); } if (parents.get(parent) == null) { parents.put(parent, methodYield); } } }

Target:
public void setParent(@Nullable Node parent, @Nullable MethodYield methodYield) { if (parent != null) { if (parents.isEmpty()) { programState.constraints.forEach((sv, c) -> { if (parent.programState.getConstraint(sv) != c) { addConstraint(sv, c); } }); programState.values.forEach((s, sv) -> { if (parent.programState.getValue(s) != sv) { learnedSymbols.add(new LearnedValue(sv, s)); } }); } addParent(parent, methodYield); } }
Source:
public Object runInTransaction() { try { EntityManager em = ensureEntityManager(entityManagerFactory); Object result = context.proceed(); em.flush(); EntityManagerHolder.getInstance().getThreadLocal().set(null); return result; } catch (Exception e) { logger.error("Failed to run operation in a new transaction", e); throwable = e; return null; } }

Target:
public Object runInTransaction() { try { EntityManager em = ensureEntityManager(entityManagerFactory); Object result = context.proceed(); if (!readOnly) { em.flush(); } EntityManagerHolder.getInstance().getThreadLocal().set(null); return result; } catch (Exception e) { logger.error("Failed to run operation in a new transaction", e); throwable = e; return null; } }
Source:
public boolean equals(Object obj) { if (obj == null || !(obj instanceof AsyncBase)) { return false; } return ((AsyncBase) obj).naturalKey.equals(naturalKey); }

Target:
public boolean equals(Object obj) { if (obj == null || !(obj instanceof AsyncBase) || this.getClass() != obj.getClass()) { return false; } return ((AsyncBase) obj).naturalKey.equals(naturalKey); }
Source:
public CompletionStage<Void> close() { if ( closed.compareAndSet( false, true ) ) { nettyChannelTracker.prepareToCloseChannels(); CompletableFuture<Void> allPoolClosedFuture = CompletableFuture.allOf( pools.entrySet().stream().map( entry -> { BoltServerAddress address = entry.getKey(); ExtendedChannelPool pool = entry.getValue(); log.info( "Closing connection pool towards %s", address ); return closePool( pool ).toCompletableFuture(); } ).toArray( CompletableFuture[]::new ) ); allPoolClosedFuture.whenComplete( ( ignored, pollCloseError ) -> { pools.clear(); if ( !ownsEventLoopGroup ) { completedWithNullIfNonError( closeFuture, pollCloseError ); } else { eventLoopGroup().shutdownGracefully( 200, 15_000, TimeUnit.MILLISECONDS ); Futures.asCompletionStage( eventLoopGroup().terminationFuture() ).whenComplete( ( ignore, eventLoopGroupTerminationError ) -> { CompletionException combinedErrors = combineErrors( pollCloseError, eventLoopGroupTerminationError ); completedWithNullIfNonError( closeFuture, combinedErrors ); } ); } } ); } return closeFuture; }

Target:
public CompletionStage<Void> close() { if ( closed.compareAndSet( false, true ) ) { nettyChannelTracker.prepareToCloseChannels(); CompletableFuture<Void> allPoolClosedFuture = closeAllPools(); allPoolClosedFuture.whenComplete( ( ignored, pollCloseError ) -> { pools.clear(); if ( !ownsEventLoopGroup ) { completeWithNullIfNoError( closeFuture, pollCloseError ); } else { shutdownEventLoopGroup( pollCloseError ); } } ); } return closeFuture; }
Source:
public void testDefaultOperation() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(AvoidStaticImportCheck.class); final String[] expected = { "23:27: " + getCheckMessage(MSG_KEY, "java.io.File.listRoots"), "25:42: " + getCheckMessage(MSG_KEY, "javax.swing.WindowConstants.*"), "26:42: " + getCheckMessage(MSG_KEY, "javax.swing.WindowConstants.*"), "27:27: " + getCheckMessage(MSG_KEY, "java.io.File.createTempFile"), "28:27: " + getCheckMessage(MSG_KEY, "java.io.File.pathSeparator"), "29:29: " + getCheckMessage(MSG_KEY, "java.lang.Math.E"), "30:29: " + getCheckMessage(MSG_KEY, "java.lang.Math.sqrt"), "31:113: " + getCheckMessage(MSG_KEY, "com.puppycrawl.tools.checkstyle.checks.imports." + "avoidstaticimport.InputAvoidStaticImportNestedClass.InnerClass"), "32:124: " + getCheckMessage(MSG_KEY, "com.puppycrawl.tools.checkstyle.checks.imports." + "avoidstaticimport.InputAvoidStaticImportNestedClass.InnerClass.one"), }; verify(checkConfig, getPath("InputAvoidStaticImportDefault.java"), expected); }

Target:
public void testDefaultOperation() throws Exception { final DefaultConfiguration checkConfig = createModuleConfig(AvoidStaticImportCheck.class); final String[] expected = { "23:27: " + getCheckMessage(MSG_KEY, "java.io.File.listRoots"), "25:42: " + getCheckMessage(MSG_KEY, "javax.swing.WindowConstants.*"), "26:27: " + getCheckMessage(MSG_KEY, "java.io.File.createTempFile"), "27:27: " + getCheckMessage(MSG_KEY, "java.io.File.pathSeparator"), "28:29: " + getCheckMessage(MSG_KEY, "java.lang.Math.E"), "29:29: " + getCheckMessage(MSG_KEY, "java.lang.Math.sqrt"), "30:113: " + getCheckMessage(MSG_KEY, "com.puppycrawl.tools.checkstyle.checks.imports." + "avoidstaticimport.InputAvoidStaticImportNestedClass.InnerClass"), "31:124: " + getCheckMessage(MSG_KEY, "com.puppycrawl.tools.checkstyle.checks.imports." + "avoidstaticimport.InputAvoidStaticImportNestedClass.InnerClass.one"), }; verify(checkConfig, getPath("InputAvoidStaticImportDefault.java"), expected); }
Source:
public boolean perform( Metadata metadata ) throws MetadataException { if ( metadata == null ) { return false; } List<Plugin> plugins = metadata.getPlugins(); for ( Plugin p : plugins ) { if ( p.getArtifactId().equals( plugin.getArtifactId() ) ) { if ( isPluginPrefixAndNameEquals( p, plugin ) ) { p.setName( plugin.getName() ); return false; } } } plugins.add( plugin ); Collections.sort( plugins, pluginComparator ); return true; }

Target:
public boolean perform( Metadata metadata ) throws MetadataException { if ( metadata == null ) { return false; } List<Plugin> plugins = metadata.getPlugins(); for ( Plugin p : plugins ) { if ( p.getArtifactId().equals( plugin.getArtifactId() ) ) { if ( isPluginPrefixAndArtifactIdEquals( p, plugin ) ) { p.setName( plugin.getName() ); return false; } } } plugins.add( plugin ); Collections.sort( plugins, pluginComparator ); return true; }
Source:
public void setFile(AbstractFile file) { WindowManager.getDefault().getMainWindow().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); abstractFile = file; htmlPanel.setHtmlText(getHtmlText(file)); WindowManager.getDefault().getMainWindow().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); }

Target:
public void setFile(AbstractFile file) { WindowManager.getDefault().getMainWindow().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); htmlPanel.setHtmlText(getHtmlText(file)); WindowManager.getDefault().getMainWindow().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); }
Source:
public void checkAttributeSyntax(PerunSessionImpl perunSession, String key, Attribute attribute) throws WrongAttributeValueException { if(attribute.getValue() == null) return; Map<String, String> map = attribute.valueAsMap(); if(map.isEmpty()) return; Set<String> mapKeys = map.keySet(); for(String mapKey: mapKeys) { if(mapKey == null) throw new WrongAttributeValueException(attribute, key, "Key in usedGids can't be null."); Matcher keyMatcher = keyPattern.matcher(mapKey); if(!keyMatcher.matches()) throw new WrongAttributeValueException(attribute, key, "Key in usedGids can be only in format 'Rx', 'Gx', 'Dx' where 'x' is positive integer."); String value = map.get(mapKey); if(value == null) throw new WrongAttributeValueException(attribute, key, "Value in usedGids can't be null."); Matcher valueMatcher = valuePattern.matcher(value); if(!valueMatcher.matches()) throw new WrongAttributeValueException(attribute, key, "Key in usedGids can be only positive integer."); } for(String mapKey: mapKeys) { if(mapKey.startsWith("D")) continue; String value = map.get(mapKey); if(map.containsKey("D" + value)) throw new WrongAttributeValueException(attribute, key, "This gid can't be depleted and used at the same time!"); } }

Target:
public void checkAttributeSyntax(PerunSessionImpl perunSession, String key, Attribute attribute) throws WrongAttributeValueException { if(attribute.getValue() == null) return; Map<String, String> map = attribute.valueAsMap(); Set<String> mapKeys = map.keySet(); for(String mapKey: mapKeys) { if(mapKey == null) throw new WrongAttributeValueException(attribute, key, "Key in usedGids can't be null."); Matcher keyMatcher = keyPattern.matcher(mapKey); if(!keyMatcher.matches()) throw new WrongAttributeValueException(attribute, key, "Key in usedGids can be only in format 'Rx', 'Gx', 'Dx' where 'x' is positive integer."); String value = map.get(mapKey); if(value == null) throw new WrongAttributeValueException(attribute, key, "Value in usedGids can't be null."); Matcher valueMatcher = valuePattern.matcher(value); if(!valueMatcher.matches()) throw new WrongAttributeValueException(attribute, key, "Key in usedGids can be only positive integer."); } for(String mapKey: mapKeys) { if(mapKey.startsWith("D")) continue; String value = map.get(mapKey); if(map.containsKey("D" + value)) throw new WrongAttributeValueException(attribute, key, "This gid can't be depleted and used at the same time!"); } }
Source:
private void purgeMediaToPostAssociationsIfNotInPostAnymore() { ArrayList<MediaModel> allMedia = new ArrayList<>(); Set<MediaModel> failedMedia = mUploadStore.getFailedMediaForPost(mPost); Set<MediaModel> completedMedia = mUploadStore.getCompletedMediaForPost(mPost); Set<MediaModel> uploadingMedia = mUploadStore.getUploadingMediaForPost(mPost); allMedia.addAll(failedMedia); allMedia.addAll(completedMedia); allMedia.addAll(uploadingMedia); if (allMedia != null && !allMedia.isEmpty()) { HashSet<MediaModel> mediaToDeleteAssociationFor = new HashSet<>(); for (MediaModel media : allMedia) { if (!AztecEditorFragment.isMediaInPostBody(this, mPost.getContent(), String.valueOf(media.getId()))) { mediaToDeleteAssociationFor.add(media); } } if (!mediaToDeleteAssociationFor.isEmpty()) { UploadStore.ClearMediaPayload clearMediaPayload = new UploadStore.ClearMediaPayload(mPost, mediaToDeleteAssociationFor); mDispatcher.dispatch(UploadActionBuilder.newClearMediaForPostAction(clearMediaPayload)); } } }

Target:
private void purgeMediaToPostAssociationsIfNotInPostAnymore() { ArrayList<MediaModel> allMedia = new ArrayList<>(); allMedia.addAll(mUploadStore.getFailedMediaForPost(mPost)); allMedia.addAll(mUploadStore.getCompletedMediaForPost(mPost)); allMedia.addAll(mUploadStore.getUploadingMediaForPost(mPost)); if (!allMedia.isEmpty()) { HashSet<MediaModel> mediaToDeleteAssociationFor = new HashSet<>(); for (MediaModel media : allMedia) { if (!AztecEditorFragment.isMediaInPostBody(this, mPost.getContent(), String.valueOf(media.getId()))) { mediaToDeleteAssociationFor.add(media); } } if (!mediaToDeleteAssociationFor.isEmpty()) { UploadStore.ClearMediaPayload clearMediaPayload = new UploadStore.ClearMediaPayload(mPost, mediaToDeleteAssociationFor); mDispatcher.dispatch(UploadActionBuilder.newClearMediaForPostAction(clearMediaPayload)); } } }
Source:
public void testFindMappingEntryEmptyExternal() { final Optional<ExternalVnicProfileMapping> actual = underTest.findMappingEntry(NETWORK_NAME, VNIC_PROFILE1_NAME, Arrays.asList(emptySourceMapping)); assertFalse(actual.isPresent()); }

Target:
public void testFindMappingEntryEmptyExternal() { final Optional<ExternalVnicProfileMapping> actual = underTest.findMappingEntry(NETWORK_NAME, VNIC_PROFILE1_NAME, singletonList(emptySourceMapping)); assertFalse(actual.isPresent()); }
Source:
public static void main(String[] argv) throws IOException { CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(OPTIONS, argv, true ); } catch (ParseException e) { return; } String[] args = cmd.getArgs(); InstancedConfiguration conf = new InstancedConfiguration(ConfigurationUtils.defaults()); conf.set(PropertyKey.USER_RPC_RETRY_MAX_DURATION, "5s", Source.DEFAULT); CollectInfo shell = new CollectInfo(conf); if (args.length < 2) { printHelp(String.format("Command %s requires at least %s arguments (%s provided)%n", 2, argv.length)); System.exit(-1); } int ret; if (cmd.hasOption(LOCAL_OPTION_NAME)) { System.out.println("Executing collectInfo locally"); ret = shell.collectInfoLocal(cmd); } else { System.out.println("Executing collectInfo on all nodes in the cluster"); ret = shell.collectInfoRemote(cmd); } shell.close(); System.exit(ret); }

Target:
public static void main(String[] argv) throws IOException { CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(OPTIONS, argv, true ); } catch (ParseException e) { return; } String[] args = cmd.getArgs(); InstancedConfiguration conf = new InstancedConfiguration(ConfigurationUtils.defaults()); conf.set(PropertyKey.USER_RPC_RETRY_MAX_DURATION, "5s", Source.DEFAULT); CollectInfo shell = new CollectInfo(conf); if (args.length < 2) { printHelp(String.format("Command requires at least %s arguments (%s provided)%n", 2, argv.length)); System.exit(-1); } int ret; if (cmd.hasOption(LOCAL_OPTION_NAME)) { System.out.println("Executing collectInfo locally"); ret = shell.collectInfoLocal(cmd); } else { System.out.println("Executing collectInfo on all nodes in the cluster"); ret = shell.collectInfoRemote(cmd); } shell.close(); System.exit(ret); }
Source:
private void updateFileTrackingInfo() throws IOException { try { File tempFile = new File(tempFilePath); FileWriter fw = new FileWriter(tempFile.getAbsoluteFile(), true); BufferedWriter bw = new BufferedWriter(fw); bw.write(fileName + "\n"); bw.close(); } catch (IOException ioe) { throw ioe; } }

Target:
private void updateFileTrackingInfo() throws IOException { try (FSDataOutputStream outputStream = fs.create(new Path(tempFilePath, file.getName() + ".txt"))) { outputStream.writeUTF(fileName); } }
Source:
public static void setFont(double size) { currentFont = new Font(currentFont.getFamily(), size); Globals.prefs.putDouble(JabRefPreferences.FONT_SIZE, size); }

Target:
public static void setFont(double size) { currentFont = new Font(currentFont.getFamily(), size); Globals.prefs.putInt(JabRefPreferences.FONT_SIZE, size); }
Source:
public void testReassemblyWithCorruptPage() throws Exception { DeltaByteArrayWriter writer = new DeltaByteArrayWriter(10, 100, new HeapByteBufferAllocator()); String lastValue = null; for (int i = 0; i < 10; i += 1) { lastValue = str(i); writer.writeBytes(Binary.fromString(lastValue)); } byte[] firstPageBytes = writer.getBytes().toByteArray(); writer.reset(); corruptWriter(writer, lastValue); for (int i = 10; i < 20; i += 1) { writer.writeBytes(Binary.fromString(str(i))); } byte[] corruptPageBytes = writer.getBytes().toByteArray(); DeltaByteArrayReader firstPageReader = new DeltaByteArrayReader(); firstPageReader.initFromPage(10, firstPageBytes, 0); for (int i = 0; i < 10; i += 1) { assertEquals(firstPageReader.readBytes().toStringUsingUTF8(), str(i)); } DeltaByteArrayReader corruptPageReader = new DeltaByteArrayReader(); corruptPageReader.initFromPage(10, corruptPageBytes, 0); try { corruptPageReader.readBytes(); fail("Corrupt page did not throw an exception when read"); } catch (ArrayIndexOutOfBoundsException e) { } DeltaByteArrayReader secondPageReader = new DeltaByteArrayReader(); secondPageReader.initFromPage(10, corruptPageBytes, 0); secondPageReader.setPreviousReader(firstPageReader); for (int i = 10; i < 20; i += 1) { assertEquals(secondPageReader.readBytes().toStringUsingUTF8(), str(i)); } }

Target:
public void testReassemblyWithCorruptPage() throws Exception { DeltaByteArrayWriter writer = getDeltaByteArrayWriter(); String lastValue = null; for (int i = 0; i < 10; i += 1) { lastValue = str(i); writer.writeBytes(Binary.fromString(lastValue)); } ByteBuffer firstPageBytes = writer.getBytes().toByteBuffer(); writer.reset(); corruptWriter(writer, lastValue); for (int i = 10; i < 20; i += 1) { writer.writeBytes(Binary.fromString(str(i))); } ByteBuffer corruptPageBytes = writer.getBytes().toByteBuffer(); DeltaByteArrayReader firstPageReader = new DeltaByteArrayReader(); firstPageReader.initFromPage(10, firstPageBytes, 0); for (int i = 0; i < 10; i += 1) { assertEquals(firstPageReader.readBytes().toStringUsingUTF8(), str(i)); } DeltaByteArrayReader corruptPageReader = new DeltaByteArrayReader(); corruptPageReader.initFromPage(10, corruptPageBytes, 0); try { corruptPageReader.readBytes(); fail("Corrupt page did not throw an exception when read"); } catch (ArrayIndexOutOfBoundsException e) { } DeltaByteArrayReader secondPageReader = new DeltaByteArrayReader(); secondPageReader.initFromPage(10, corruptPageBytes, 0); secondPageReader.setPreviousReader(firstPageReader); for (int i = 10; i < 20; i += 1) { assertEquals(secondPageReader.readBytes().toStringUsingUTF8(), str(i)); } }
Source:
public boolean isSelected() { if (parent != null) { return parent.isSelected(); } return selected; }

Target:
public boolean isSelected() { return selected; }
Source:
protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { rsp.setContentType("text/plain"); InputStream in = null; OutputStream out = null; try { if (file == null) { in = getServletContext().getResourceAsStream("/robots.txt"); } else { in = new FileInputStream(file); } out = rsp.getOutputStream(); byte[] buffer = new byte[1024]; int count = 0; while ((count = in.read(buffer)) != -1) { out.write(buffer, 0, count); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }

Target:
protected void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { rsp.setContentType("text/plain"); InputStream in = openRobotsFile(); try { OutputStream out = rsp.getOutputStream(); try { ByteStreams.copy(in, out); } finally { out.close(); } } finally { in.close(); } }
Source:
public static Map<String, ?> getMappingSource(final MutableTable table) { if (table.getColumnByName(FIELD_ID) == null) { final MutableColumn idColumn = new MutableColumn(FIELD_ID, ColumnType.STRING).setTable(table).setPrimaryKey( true); table.addColumn(0, idColumn); } final Map<String, Map<String, String>> propertiesMap = new LinkedHashMap<>(); for (Column column : table.getColumns()) { final String columnName = column.getName(); if (FIELD_ID.equals(columnName)) { continue; } final String fieldName = getValidatedFieldName(columnName); final Map<String, String> propertyMap = new HashMap<>(); final String type = getType(column); propertyMap.put("type", type); propertiesMap.put(fieldName, propertyMap); } final Map<String, Map<String, Map<String, String>>> mapping = new HashMap<>(); mapping.put("properties", propertiesMap); return mapping; }

Target:
public static Map<String, ?> getMappingSource(final MutableTable table) { if (table.getColumnByName(FIELD_ID) == null) { final MutableColumn idColumn = new MutableColumn(FIELD_ID, ColumnType.STRING).setTable(table).setPrimaryKey( true); table.addColumn(0, idColumn); } final Map<String, Map<String, String>> propertiesMap = new LinkedHashMap<>(); for (Column column : table.getColumns()) { final String columnName = column.getName(); if (FIELD_ID.equals(columnName)) { continue; } final String fieldName = getValidatedFieldName(columnName); final Map<String, String> propertyMap = new HashMap<>(); final String type = getType(column); propertyMap.put("type", type); propertiesMap.put(fieldName, propertyMap); } final Map<String, Map<String, Map<String, String>>> mapping = new HashMap<>(); mapping.put(ElasticSearchMetaData.PROPERTIES_KEY, propertiesMap); return mapping; }
Source:
public MenuController(final MainController mainController, final MenuBar menuBar) { this.mainController = mainController; menuBar.setUseSystemMenuBar(true); menuBar.getMenus().add(createMenu("_File", createWorkspaceLoader("Select Workspace Folder", new KeyCodeCombination(KeyCode.O, KeyCombination.CONTROL_DOWN)), createMenuItem("Exit", event -> mainController.exitProgram()))); menuBar.getMenus().add(createMenu("_Navigate", createMenuItem("Previous", new KeyCodeCombination(KeyCode.ESCAPE), event -> mainController.previousView()), createMenuItem("Show Phylogenetic tree", new KeyCodeCombination(KeyCode.Q, KeyCombination.CONTROL_DOWN), event -> mainController.toggleNewick()), createGenomeGraphLoader("Load Genome Graph", new KeyCodeCombination(KeyCode.L, KeyCombination.SHORTCUT_DOWN)))); menuBar.getMenus().add(createMenu("_Help", createMenuItem("Shortcuts", new KeyCodeCombination(KeyCode.F1), event -> mainController.toggleOverlay()))); }

Target:
public MenuController(final MainController mainController, final MenuBar menuBar) { this.mainController = mainController; this.menuBar = menuBar; initFileMenu(); initNavigateMenu(); initHelpMenu(); }
Source:
private void setupMigrations(Sprinkles sprinkles) { sprinkles.addMigration(getInitialMigration()); sprinkles.addMigration(getMigrationForVersion095()); }

Target:
private void setupMigrations(Sprinkles sprinkles) { sprinkles.addMigration(getInitialMigration()); sprinkles.addMigration(getMigrationToVersion_0_9_6()); }
Source:
private String limiterKey(Request request) { String pathTemplate = request.header(OkhttpTraceInterceptor.PATH_TEMPLATE_HEADER); if (pathTemplate == null) { return FALLBACK; } else { return request.url().host() + " " + request.method() + " " + pathTemplate; } }

Target:
private Key limiterKey(Request request) { String pathTemplate = request.header(OkhttpTraceInterceptor.PATH_TEMPLATE_HEADER); if (pathTemplate == null) { return ImmutableKey.builder().hostname(request.url().host()).build(); } else { return ImmutableKey.builder() .hostname(request.url().host()) .method(request.method()) .pathTemplate(pathTemplate) .build(); } }
Source:
protected <T> Observable buildUseCaseObservable(final Map<String, T> parameters) { if (parameters == null || !parameters.containsKey(KEY_SURVEY_GROUP_ID)) { return Observable.error(new IllegalArgumentException("missing survey group id")); } if (!connectivityStateManager.isConnectionAvailable()) { return Observable.just(new SyncResult(SyncResult.ResultCode.ERROR_NO_NETWORK, 0)); } return userRepository.mobileSyncAllowed().concatMap(new Func1<Boolean, Observable<SyncResult>>() { @Override public Observable<SyncResult> call(Boolean syncAllowed) { if (!syncAllowed && !connectivityStateManager.isWifiConnected()) { return Observable.just(new SyncResult( SyncResult.ResultCode.ERROR_SYNC_NOT_ALLOWED_OVER_3G, 0)); } else { return syncDataPoints(parameters); } } }); }

Target:
protected <T> Observable buildUseCaseObservable(final Map<String, T> parameters) { if (parameters == null || parameters.get(KEY_SURVEY_GROUP_ID) == null) { return Observable.error(new IllegalArgumentException("Missing survey group id")); } if (!connectivityStateManager.isConnectionAvailable()) { return Observable.just(new SyncResult(SyncResult.ResultCode.ERROR_NO_NETWORK, 0)); } return userRepository.mobileSyncAllowed().concatMap(new Func1<Boolean, Observable<SyncResult>>() { @Override public Observable<SyncResult> call(Boolean syncAllowed) { if (!syncAllowed && !connectivityStateManager.isWifiConnected()) { return Observable.just(new SyncResult( SyncResult.ResultCode.ERROR_SYNC_NOT_ALLOWED_OVER_3G, 0)); } else { return syncDataPoints(parameters); } } }); }
Source:
public Map<Integer, Long> getCursors(String streamName) { assert(m_0 == null); Map<Integer, Long> result = new TreeMap<>(); int blockOffset = m_slotManager.blockOffset(streamName); for(Integer pid : m_slotManager.m_localPartitionIds.keySet()) { result.put(pid, m_lb.get(blockOffset)); blockOffset++; } return result; }

Target:
public Map<Integer, Long> getCursors(String streamName) { assert(m_fileRef0 == null); Map<Integer, Long> result = new TreeMap<>(); Integer blockNum = m_slotMapper.streamNameToBlockNum(streamName); if (blockNum != null) { int blockOffset = m_slotMapper.blockOffset(blockNum) + 1; for(Integer pid : m_slotMapper.m_localPartitionIds.keySet()) { result.put(pid, m_lb.get(blockOffset)); blockOffset++; } } return result; }
Source:
public void createAvailabilityMetric( @Suspended final AsyncResponse asyncResponse, @ApiParam(required = true) MetricDefinition metricDefinition, @Context UriInfo uriInfo ) { if(metricDefinition.getType() != null && metricDefinition.getType() != MetricType.AVAILABILITY) { asyncResponse.resume(badRequest(new ApiError("MetricDefinition type does not match " + MetricType .AVAILABILITY.getText()))); } URI location = uriInfo.getBaseUriBuilder().path("/availability/{id}").build(metricDefinition.getId()); Metric<AvailabilityType> metric = new Metric<>(new MetricId<>(tenantId, AVAILABILITY, metricDefinition.getId()), metricDefinition.getTags(), metricDefinition.getDataRetention()); metricsService.createMetric(metric).subscribe(new MetricCreatedObserver(asyncResponse, location)); }

Target:
public void createAvailabilityMetric( @Suspended final AsyncResponse asyncResponse, @ApiParam(required = true) MetricDefinition metricDefinition, @Context UriInfo uriInfo ) { if(metricDefinition.getType() != null && MetricType.AVAILABILITY != metricDefinition.getType()) { asyncResponse.resume(badRequest(new ApiError("MetricDefinition type does not match " + MetricType .AVAILABILITY.getText()))); } URI location = uriInfo.getBaseUriBuilder().path("/availability/{id}").build(metricDefinition.getId()); Metric<AvailabilityType> metric = new Metric<>(new MetricId<>(tenantId, AVAILABILITY, metricDefinition.getId()), metricDefinition.getTags(), metricDefinition.getDataRetention()); metricsService.createMetric(metric).subscribe(new MetricCreatedObserver(asyncResponse, location)); }
Source:
public void StringUtilUnquote() throws Exception { Assert.assertTrue(StringUtil.unquoteString("\"\n\"").equals("\n")); Assert.assertTrue(StringUtil.unquoteString("\"\r\"").equals("\r")); Assert.assertTrue(StringUtil.unquoteString("\"\f\"").equals("\f")); Assert.assertTrue(StringUtil.unquoteString("\"\t\"").equals("\t")); Assert.assertTrue(StringUtil.unquoteString("\"\\x20\"").equals(" ")); Assert.assertTrue(StringUtil.unquoteString("\"\\u0020\"").equals(" ")); Assert.assertTrue(StringUtil.unquoteString("\"\\U00000020\"").equals(" ")); Assert.assertTrue(StringUtil.unquoteString("\"\\U00000020\"").equals(" ")); try { StringUtil.unquoteString("\"\\U00110000\""); throw new AssertionError(); } catch (IllegalArgumentException e) { } try { StringUtil.unquoteString("\"\\U0000d801\""); throw new AssertionError(); } catch (IllegalArgumentException e) { } }

Target:
public void StringUtilUnquote() throws Exception { Assert.assertTrue(StringUtil.unquoteString("\"\\n\"").equals("\n")); Assert.assertTrue(StringUtil.unquoteString("\"\\r\"").equals("\r")); Assert.assertTrue(StringUtil.unquoteString("\"\\f\"").equals("\f")); Assert.assertTrue(StringUtil.unquoteString("\"\\t\"").equals("\t")); Assert.assertTrue(StringUtil.unquoteString("\"\\x20\"").equals(" ")); Assert.assertTrue(StringUtil.unquoteString("\"\\u0020\"").equals(" ")); Assert.assertTrue(StringUtil.unquoteString("\"\\U00000020\"").equals(" ")); Assert.assertTrue(StringUtil.unquoteString("\"\\U00000020\"").equals(" ")); try { StringUtil.unquoteString("\"\\U00110000\""); throw new AssertionError(); } catch (IllegalArgumentException e) { } try { StringUtil.unquoteString("\"\\U0000d801\""); throw new AssertionError(); } catch (IllegalArgumentException e) { } }
Source:
public boolean canUserEditTemplate(PipelineTemplateConfig template, CaseInsensitiveString username, List<Role> roles) { return template.getAuthorization().getAdminsConfig().isAdmin(new AdminUser(username), roles); }

Target:
public boolean canUserEditTemplate(PipelineTemplateConfig template, CaseInsensitiveString username, List<Role> roles) { return template.getAuthorization().isUserAnAdmin(username, roles); }
Source:
public List<ElementEventsType> getElementEventTypes(final List<INetworkNodeInfo> networkNodeInfoList) { List<Future<ElementEventsType>> futureEvents = new ArrayList<>(); List<String> ids = new ArrayList<>(); networkNodeInfoList.forEach(networkNodeInfo -> { ids.add(networkNodeInfo.getId()); }); try { futureEvents.add(elementEventTypeDownloadService.getElementEventTypeAsync(ids)); } catch (QuadrigaException e1) { logger.error("An exception occured: " + e1); } List<ElementEventsType> elementEventsTypeList = new ArrayList<>(); for (Future<ElementEventsType> future : futureEvents) { ElementEventsType elementEventsType = null; try { elementEventsType = future.get(); logger.debug("Done with retrieving networks."); } catch (InterruptedException | ExecutionException e) { logger.error( "Unable to execute a qstore asynchronosly for relation event id: " + ids, e); } finally { if(elementEventsType != null) elementEventsTypeList.add(elementEventsType); } } return elementEventsTypeList; }

Target:
public List<ElementEventsType> getElementEventTypes(final List<INetworkNodeInfo> networkNodeInfoList) { List<Future<ElementEventsType>> futureEvents = new ArrayList<>(); List<String> ids = new ArrayList<>(); networkNodeInfoList.forEach(networkNodeInfo -> { ids.add(networkNodeInfo.getId()); }); try { futureEvents.add(elementEventTypeDownloadService.getElementEventTypeAsync(ids)); } catch (QuadrigaException e1) { logger.error("An exception occured: " + e1); } List<ElementEventsType> elementEventsTypeList = new ArrayList<>(); for (Future<ElementEventsType> future : futureEvents) { ElementEventsType elementEventsType = null; try { elementEventsType = future.get(); logger.debug("Done with retrieving networks."); } catch (InterruptedException | ExecutionException e) { logger.error( "Unable to execute a qstore asynchronosly for relation event id: " + ids, e); } finally { if(elementEventsType != null){ elementEventsTypeList.add(elementEventsType); } } } return elementEventsTypeList; }
Source:
public SearchStringCollector(EventBus eventBus) { eventBus.addHandler(ApplySearchStringEvent.getType(), event -> { String searchString = event.getSearchString(); int colonIndex = searchString.indexOf(':'); if (!activePresenters.contains(searchString.substring(0, colonIndex + 1))) { searchStringMap.put(searchString.substring(0, colonIndex + 1), searchString); } }); }

Target:
public SearchStringCollector(EventBus eventBus) { eventBus.addHandler(ApplySearchStringEvent.getType(), event -> { String searchString = event.getSearchString(); int colonIndex = searchString.indexOf(':'); if (colonIndex >= 0) { String defaultSearchString = searchString.substring(0, colonIndex + 1); if (!activePresenters.contains(defaultSearchString)) { searchStringMap.put(defaultSearchString, searchString); } } }); }
Source:
public abstract Object execute(ExecutionEvent event) throws ExecutionException; public IServer getServer(IModule module) { IServer toRepublish = null; if( module != null ) { IServer[] servers = ServerCore.getServers(); ArrayList<IServer> matched = new ArrayList<IServer>(); for( int i = 0; i < servers.length; i++ ) { boolean found = false; IModule[] deployed = servers[i].getModules(); for( int j = 0; j < deployed.length && !found; j++ ) if( deployed[j].getId().equals(module.getId())) found = true; if( found ) matched.add(servers[i]); } if( matched.size() == 0 || matched.size() > 1 ) { toRepublish = matched.get(0); } else toRepublish = matched.get(0); } return toRepublish; }

Target:
public abstract Object execute(ExecutionEvent event) throws ExecutionException; protected IModule getModule(IResource resource) { if (resource != null) { ArrayList<IModule> possibleModules = new ArrayList<IModule>(); IModuleArtifact[] moduleArtifacts = ServerPlugin.getModuleArtifacts(resource); if (moduleArtifacts != null && moduleArtifacts.length > 0) { for( int i = 0; i < moduleArtifacts.length; i++ ) { if( moduleArtifacts[i].getModule() != null && !possibleModules.contains(moduleArtifacts[i].getModule())) { possibleModules.add(moduleArtifacts[i].getModule()); } } } return promptForModule(possibleModules); } return null; }
Source:
public void testRenameProcessVariableForInitColumns(){ TaskListViewImpl taskListView = view; GridGlobalPreferences gridPreferences = new GridGlobalPreferences("test",taskListView.getInitColumns(),taskListView.getBannedColumns()); ListTable<TaskSummary> extendedPagedTable = new ListTable<TaskSummary>(gridPreferences); extendedPagedTable.getGridPreferencesStore().getColumnPreferences().add(new GridColumnPreference("Id",-1,"")); extendedPagedTable.getGridPreferencesStore().getColumnPreferences().add(new GridColumnPreference("performance",-1,"")); taskListView.initCellPreview(extendedPagedTable); final Column<TaskSummary, String> createdOnColumn = taskListView.createTextColumn(COLUMN_CREATED_ON, task -> DateUtils.getDateTimeStr(task.getCreatedOn())); ColumnMeta<TaskSummary> actionsColumnMeta = taskListView.initActionsColumn(); extendedPagedTable.addSelectionIgnoreColumn(actionsColumnMeta.getColumn()); List<ColumnMeta<TaskSummary>> columnMetas = taskListView.getGeneralColumnMetas(extendedPagedTable, createdOnColumn, actionsColumnMeta); assertEquals(15,columnMetas.size()); assertEquals(0,columnMetas.stream().filter(column -> column.getCaption().equals("Var_Id")) .collect(Collectors.toList()).size()); List<ColumnMeta<TaskSummary>> tmp = taskListView.renameProcessVariables(extendedPagedTable, columnMetas); columnMetas.addAll(tmp); assertEquals(17,columnMetas.size()); assertEquals(1, columnMetas.stream() .filter(column -> column.getCaption().equals("Var_Id")) .collect(Collectors.toList()).size()); }

Target:
public void testRenameProcessVariableForInitColumns(){ GridGlobalPreferences gridPreferences = new GridGlobalPreferences("test",view.getInitColumns(),view.getBannedColumns()); ListTable<TaskSummary> extendedPagedTable = new ListTable<TaskSummary>(gridPreferences); List<GridColumnPreference> gridColumnPreferenceList = extendedPagedTable.getGridPreferencesStore().getColumnPreferences(); gridColumnPreferenceList.add(new GridColumnPreference("Id",-1,"")); gridColumnPreferenceList.add(new GridColumnPreference("performance",-1,"")); view.initCellPreview(extendedPagedTable); final Column<TaskSummary, String> createdOnColumn = view.createTextColumn(COLUMN_CREATED_ON, task -> DateUtils.getDateTimeStr(task.getCreatedOn())); ColumnMeta<TaskSummary> actionsColumnMeta = view.initActionsColumn(); extendedPagedTable.addSelectionIgnoreColumn(actionsColumnMeta.getColumn()); List<ColumnMeta<TaskSummary>> columnMetas = view.getGeneralColumnMetas(extendedPagedTable, createdOnColumn, actionsColumnMeta); assertThat(columnMetas.stream()).extracting(c -> c.getCaption()).hasSize(15).doesNotContain("Var_Id"); List<ColumnMeta<TaskSummary>> tmp = view.renameVariables(extendedPagedTable, columnMetas); columnMetas.addAll(tmp); assertThat(columnMetas.stream()).extracting(c -> c.getCaption()).hasSize(17).containsOnlyOnce("Var_Id"); }
Source:
public KieServerRouter() { configRepositoryServiceLoader.forEach(repo -> repository = repo); log.info("KIE Server router repository implementation is " + repository); MANAGEMENT_SECURED = Boolean.parseBoolean(System.getProperty(KIE_ROUTER_MANAGEMENT_SECURED, "false")); IDENTITY_PROVIDER = System.getProperty(KieServerRouterConstants.KIE_ROUTER_IDENTITY_PROVIDER, "default"); }

Target:
public KieServerRouter() { this(MANAGEMENT_SECURED, IDENTITY_PROVIDER); }
Source:
public void testDoesNotCallbackWhenHeartbeatAlive() throws InterruptedException { ContainerHeartbeatClient client = mock(ContainerHeartbeatClient.class); CountDownLatch countDownLatch = new CountDownLatch(1); Runnable onExpired = countDownLatch::countDown; ContainerHeartbeatResponse response = new ContainerHeartbeatResponse(true); when(client.requestHeartbeat()).thenReturn(response); ScheduledExecutorService scheduler = buildScheduledExecutorService(); ContainerHeartbeatMonitor monitor = new ContainerHeartbeatMonitor(onExpired, client, scheduler); monitor.start(); boolean success = countDownLatch.await(2, TimeUnit.SECONDS); assertFalse(success); assertEquals(1, countDownLatch.getCount()); verify(scheduler, never()).schedule(any(Runnable.class), anyLong(), any()); monitor.stop(); verify(scheduler).shutdown(); }

Target:
public void testDoesNotCallbackWhenHeartbeatAlive() throws InterruptedException { ContainerHeartbeatResponse response = new ContainerHeartbeatResponse(true); when(this.containerHeartbeatClient.requestHeartbeat()).thenReturn(response); this.containerHeartbeatMonitor.start(); boolean fixedRateTaskCompleted = this.schedulerFixedRateExecutionLatch.await(2, TimeUnit.SECONDS); assertTrue("Did not complete heartbeat check", fixedRateTaskCompleted); verify(this.scheduler, never()).schedule(any(Runnable.class), anyLong(), any()); verify(this.onExpired, never()).run(); this.containerHeartbeatMonitor.stop(); verify(this.scheduler).shutdown(); }