auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void reportErrorForUnmappedTargetPropertiesIfRequired() { ReportingPolicyPrism unmappedTargetPolicy = getUnmappedTargetPolicy(); if ( method instanceof ForgedMethod ) { ForgedMethod forgedMethod = (ForgedMethod) this.method; if ( forgedMethod.isAutoMapping() ) { if ( targetProperties.isEmpty() || !unprocessedTargetProperties.isEmpty() ) { if ( forgedMethod.getHistory() == null ) { Type sourceType = this.method.getParameters().get( 0 ).getType(); Type targetType = this.method.getReturnType(); ctx.getMessager().printMessage( this.method.getExecutable(), Message.PROPERTYMAPPING_FORGED_MAPPING_NOT_FOUND, sourceType, targetType, targetType, sourceType ); } else { ForgedMethodHistory history = forgedMethod.getHistory(); ctx.getMessager().printMessage( this.method.getExecutable(), Message.PROPERTYMAPPING_MAPPING_NOT_FOUND, history.createSourcePropertyErrorMessage(), history.getTargetType(), history.createTargetPropertyName(), history.getTargetType(), history.getSourceType() ); } } } } else if ( !unprocessedTargetProperties.isEmpty() && unmappedTargetPolicy.requiresReport() ) { Message msg = unmappedTargetPolicy.getDiagnosticKind() == Diagnostic.Kind.ERROR ? Message.BEANMAPPING_UNMAPPED_TARGETS_ERROR : Message.BEANMAPPING_UNMAPPED_TARGETS_WARNING; ctx.getMessager().printMessage( method.getExecutable(), msg, MessageFormat.format( "{0,choice,1#property|1<properties}: \"{1}\"", unprocessedTargetProperties.size(), Strings.join( unprocessedTargetProperties.keySet(), ", " ) ) ); } }

Target:
private void reportErrorForUnmappedTargetPropertiesIfRequired() { ReportingPolicyPrism unmappedTargetPolicy = getUnmappedTargetPolicy(); if ( method instanceof ForgedMethod ) { ForgedMethod forgedMethod = (ForgedMethod) this.method; if ( forgedMethod.isAutoMapping() && ( targetProperties.isEmpty() || !unprocessedTargetProperties.isEmpty() ) ) { if ( forgedMethod.getHistory() == null ) { Type sourceType = this.method.getParameters().get( 0 ).getType(); Type targetType = this.method.getReturnType(); ctx.getMessager().printMessage( this.method.getExecutable(), Message.PROPERTYMAPPING_FORGED_MAPPING_NOT_FOUND, sourceType, targetType, targetType, sourceType ); } else { ForgedMethodHistory history = forgedMethod.getHistory(); ctx.getMessager().printMessage( this.method.getExecutable(), Message.PROPERTYMAPPING_MAPPING_NOT_FOUND, history.createSourcePropertyErrorMessage(), history.getTargetType(), history.createTargetPropertyName(), history.getTargetType(), history.getSourceType() ); } } } else if ( !unprocessedTargetProperties.isEmpty() && unmappedTargetPolicy.requiresReport() ) { Message msg = unmappedTargetPolicy.getDiagnosticKind() == Diagnostic.Kind.ERROR ? Message.BEANMAPPING_UNMAPPED_TARGETS_ERROR : Message.BEANMAPPING_UNMAPPED_TARGETS_WARNING; ctx.getMessager().printMessage( method.getExecutable(), msg, MessageFormat.format( "{0,choice,1#property|1<properties}: \"{1}\"", unprocessedTargetProperties.size(), Strings.join( unprocessedTargetProperties.keySet(), ", " ) ) ); } }
Source:
private static void setDropdown(Combo comboBox, INamedElement el, List<String> names) { comboBox.removeAll(); for (String name : names) { comboBox.add(name); } comboBox.select((null == el) ? names.size() - 1 : comboBox.indexOf(el.getName())); }

Target:
private static void setDropdown(Combo comboBox, INamedElement el, List<String> names) { comboBox.removeAll(); names.forEach(comboBox::add); comboBox.select((null == el) ? names.size() - 1 : comboBox.indexOf(el.getName())); }
Source:
@Override public void add(T entry) throws IOException { converter.toStream(entry, buffer); long size = buffer.size(); queueFile.add(buffer.readByteArray(), 0, (int) size); }

Target:
@Override public void add(T entry) throws IOException { Buffer buffer = new Buffer(); converter.toStream(entry, buffer); byte[] data = buffer.readByteArray(); queueFile.add(data, 0, data.length); }
Source:
void check(Data p) { Data y = p; }

Target:
void check(Data p) { Data y = p; Object z = p; }
Source:
public void deleteProjectData(@PathParam("project") String projectName) throws HistoryException { Project project = env.getProjects().get(projectName); if (project == null) { throw new IllegalStateException("cannot get project \"" + projectName + "\""); } project.setIndexed(false); List<RepositoryInfo> repos = env.getProjectRepositoriesMap().get(project); logger.log(Level.INFO, "deleting data for project {0}", projectName); for (String dirName: new String[]{IndexDatabase.INDEX_DIR, IndexDatabase.XREF_DIR}) { java.nio.file.Path path = Paths.get(env.getDataRootPath(), dirName, projectName); try { IOUtils.removeRecursive(path); } catch (IOException e) { logger.log(Level.WARNING, "Could not delete {0}", path.toString()); } } HistoryGuru guru = HistoryGuru.getInstance(); guru.removeCache(repos.stream(). map(x -> { try { return env.getPathRelativeToSourceRoot(new File((x).getDirectoryName())); } catch (ForbiddenSymlinkException e) { logger.log(Level.FINER, e.getMessage()); return ""; } catch (IOException e) { logger.log(Level.INFO, "cannot remove files for repository {0}", x.getDirectoryName()); return ""; } }).collect(Collectors.toSet())); suggester.delete(projectName); }

Target:
public void deleteProjectData(@PathParam("project") String projectName) throws HistoryException { Project project = disableProject(projectName); logger.log(Level.INFO, "deleting data for project {0}", projectName); List<RepositoryInfo> repos = env.getProjectRepositoriesMap().get(project); for (String dirName: new String[]{IndexDatabase.INDEX_DIR, IndexDatabase.XREF_DIR}) { java.nio.file.Path path = Paths.get(env.getDataRootPath(), dirName, projectName); try { IOUtils.removeRecursive(path); } catch (IOException e) { logger.log(Level.WARNING, "Could not delete {0}", path.toString()); } } deleteHistoryCache(projectName); suggester.delete(projectName); }
Source:
private void isAreaLoadedInject(int xStart, int yStart, int zStart, int xEnd, int yEnd, int zEnd, boolean allowEmpty, @Nonnull CallbackInfoReturnable<Boolean> cbi) { if (!this.isCubicWorld()) { return; } boolean ret = (this.isRemote() && allowEmpty) || this.testForCubes( xStart, yStart, zStart, xEnd, yEnd, zEnd, this::testNotNull); cbi.cancel(); cbi.setReturnValue(ret); }

Target:
private void isAreaLoadedInject(int xStart, int yStart, int zStart, int xEnd, int yEnd, int zEnd, boolean allowEmpty, @Nonnull CallbackInfoReturnable<Boolean> cbi) { if (!this.isCubicWorld()) { return; } boolean ret = (this.isRemote() && allowEmpty) || this.testForCubes( xStart, yStart, zStart, xEnd, yEnd, zEnd, Objects::nonNull); cbi.cancel(); cbi.setReturnValue(ret); }
Source:
public QuectelBG96(ModemDevice device, String platform, ConnectionFactory connectionFactory) { super(device, platform, connectionFactory); try { String atPort = getAtPort(); String gpsPort = getGpsPort(); if (atPort != null) { if (atPort.equals(getDataPort()) || atPort.equals(gpsPort)) { this.serialNumber = getSerialNumber(); this.imsi = getMobileSubscriberIdentity(); this.iccid = getIntegratedCirquitCardId(); this.model = getModel(); this.manufacturer = getManufacturer(); this.revisionId = getRevisionID(); this.gpsSupported = isGpsSupported(); this.rssi = getSignalStrength(); s_logger.trace("{} :: Serial Number={}", getClass().getName(), this.serialNumber); s_logger.trace("{} :: IMSI={}", getClass().getName(), this.imsi); s_logger.trace("{} :: ICCID={}", getClass().getName(), this.iccid); s_logger.trace("{} :: Model={}", getClass().getName(), this.model); s_logger.trace("{} :: Manufacturer={}", getClass().getName(), this.manufacturer); s_logger.trace("{} :: Revision ID={}", getClass().getName(), this.revisionId); s_logger.trace("{} :: GPS Supported={}", getClass().getName(), this.gpsSupported); s_logger.trace("{} :: RSSI={}", getClass().getName(), this.rssi); } } } catch (KuraException e) { e.printStackTrace(); } }

Target:
public QuectelBG96(ModemDevice device, String platform, ConnectionFactory connectionFactory) { super(device, platform, connectionFactory); try { String atPort = getAtPort(); String gpsPort = getGpsPort(); if (atPort != null) { if (atPort.equals(getDataPort()) || atPort.equals(gpsPort)) { this.serialNumber = getSerialNumber(); this.imsi = getMobileSubscriberIdentity(); this.iccid = getIntegratedCirquitCardId(); this.model = getModel(); this.manufacturer = getManufacturer(); this.revisionId = getRevisionID(); this.gpsSupported = isGpsSupported(); this.rssi = getSignalStrength(); logger.trace("{} :: Serial Number={}", getClass().getName(), this.serialNumber); logger.trace("{} :: IMSI={}", getClass().getName(), this.imsi); logger.trace("{} :: ICCID={}", getClass().getName(), this.iccid); logger.trace("{} :: Model={}", getClass().getName(), this.model); logger.trace("{} :: Manufacturer={}", getClass().getName(), this.manufacturer); logger.trace("{} :: Revision ID={}", getClass().getName(), this.revisionId); logger.trace("{} :: GPS Supported={}", getClass().getName(), this.gpsSupported); logger.trace("{} :: RSSI={}", getClass().getName(), this.rssi); } } } catch (KuraException e) { e.printStackTrace(); } }
Source:
public void earlyStartup() { try { new UsageReport().report(); } catch (Exception e) { new UsagePluginLogger(JBossToolsUsageActivator.getDefault()).error("could not start usage reporting"); } }

Target:
public void earlyStartup() { Display.getDefault().asyncExec(new Runnable() { public void run() { new UsageReport().report(); } }); }
Source:
public void safeExecute(Shell shell) { MultipleConfigsSelectionDialog dialog = new MultipleConfigsSelectionDialog(shell, "Delete Configurations", SERVER.configsInfo().getValue(), false, false); if (dialog.open() == Window.OK) { Map<String, Boolean> configNamesWithFlags = SERVER.configNamesWithFlags(); configService.uncheckedWrite((dialog.selectedConfigs())); boolean noError = true; try { if (!ManagerModeModel.getInstance().isInManagerMode()) { for (String item: dialog.selectedConfigs()) { if (configNamesWithFlags.get(item)) { noError = false; displayErrorDialog(shell); break; } } } if (noError) { for (String item : dialog.selectedConfigs()) { Configurations.getInstance().removeNameFromRecentlyLoadedConfigList(item); } } } catch (ManagerModePvNotConnectedException e) { MessageDialog error = new MessageDialog(shell, "Error", null, e.getMessage(), MessageDialog.ERROR, new String[] {"OK"},0); error.open(); } } }

Target:
public void safeExecute(Shell shell) { Map<String, Boolean> configNamesWithFlags = SERVER.configNamesWithFlags(); MultipleConfigsSelectionDialog dialog = new MultipleConfigsSelectionDialog(shell, "Delete Configurations", SERVER.configsInfo().getValue(), configNamesWithFlags, false, false); if (dialog.open() == Window.OK) { try { configService.write(dialog.selectedConfigs()); boolean noError = true; if (!ManagerModeModel.getInstance().isInManagerMode()) { for (String item: dialog.selectedConfigs()) { if (configNamesWithFlags.get(item)) { noError = false; displayErrorDialog(shell); break; } } } if (noError) { for (String item : dialog.selectedConfigs()) { Configurations.getInstance().removeNameFromRecentlyLoadedConfigList(item); } } } catch (ManagerModePvNotConnectedException|IOException e) { MessageDialog error = new MessageDialog(shell, "Error", null, e.getMessage(), MessageDialog.ERROR, new String[] {"OK"}, 0); error.open(); } } }
Source:
protected void actionPerformed(GuiButton button) { switch (button.id) { case 1: try { Desktop.getDesktop().browse(new java.net.URI("<LINK_0>")); } catch (Exception e) { System.err.print(e); } break; case 2: try { Desktop.getDesktop().browse(new java.net.URI("<LINK_1>")); } catch (Exception e) { System.err.print(e); } break; } }

Target:
protected void actionPerformed(GuiButton button) { switch (button.id) { case 1: this.mc.displayGuiScreen(new GuiConfirmOpenLink(this, "<LINK_0>", 1, false)); break; case 2: this.mc.displayGuiScreen(new GuiConfirmOpenLink(this, "<LINK_1>", 2, false)); break; } }
Source:
public PageHeaderWithOffset(PageHeader pageHeader, long offset) { this.pageHeader = pageHeader; this.offset = offset; this.headerByteSize = -1; }

Target:
public PageHeaderWithOffset(PageHeader pageHeader, long offset) { this.pageHeader = pageHeader; this.offset = offset; }
Source:
public SearchStudentsTable(String courseId, List<StudentListSectionData> sections) { this.courseId = courseId; this.sections = sections; if (sections.size() == 1) { StudentListSectionData section = sections.get(0); if (section.getSectionName().equals("None")) { this.hasSection = false; } else { this.hasSection = true; } } else { this.hasSection = true; } }

Target:
public SearchStudentsTable(String courseId, List<StudentListSectionData> sections) { this.courseId = courseId; this.sections = sections; if (sections.size() == 1) { StudentListSectionData section = sections.get(0); this.hasSection = !section.getSectionName().equals("None"); } else { this.hasSection = true; } }
Source:
private LoadHolder isCurrentServerMostLoaded(ServerLocation currentServer, Map<ServerLocationAndMemberId, LoadHolder> groupServers) { LoadHolder currentLH = null; for (ServerLocationAndMemberId locationAndMemberId : groupServers.keySet()) { if (currentServer.equals(locationAndMemberId.getServerLocation())) { currentLH = groupServers.get(locationAndMemberId); break; } } if (currentLH == null) return null; final float currentLoad = currentLH.getLoad(); for (Map.Entry<ServerLocationAndMemberId, LoadHolder> loadEntry : groupServers.entrySet()) { ServerLocation location = loadEntry.getKey().getServerLocation(); if (location.equals(currentServer)) { continue; } LoadHolder nextLoadReference = loadEntry.getValue(); float nextLoad = nextLoadReference.getLoad(); if (nextLoad > currentLoad) { return null; } } return currentLH; }

Target:
LoadHolder isCurrentServerMostLoaded(ServerLocation currentServer, Map<ServerLocationAndMemberId, LoadHolder> groupServers) { LoadHolder currentLH = null; for (ServerLocationAndMemberId locationAndMemberId : groupServers.keySet()) { if (currentServer.equals(locationAndMemberId.getServerLocation())) { currentLH = groupServers.get(locationAndMemberId); break; } } if (currentLH == null) return null; final float currentLoad = currentLH.getLoad(); for (Map.Entry<ServerLocationAndMemberId, LoadHolder> loadEntry : groupServers.entrySet()) { ServerLocation location = loadEntry.getKey().getServerLocation(); if (location.equals(currentServer)) { continue; } LoadHolder nextLoadReference = loadEntry.getValue(); float nextLoad = nextLoadReference.getLoad(); if (nextLoad > currentLoad) { return null; } } return currentLH; }
Source:
public void start(String serverRepositoryDir, String runtimeRepositoryDir) throws DeploymentEngineException { serverRepositoryDirectory = new File(serverRepositoryDir); runtimeRepositoryDirectory = new File(runtimeRepositoryDir); if (!serverRepositoryDirectory.exists()) { throw new DeploymentEngineException("Cannot find repository : " + serverRepositoryDirectory); } if (!runtimeRepositoryDirectory.exists()) { throw new DeploymentEngineException("Cannot find repository : " + runtimeRepositoryDirectory); } logger.debug("Starting carbon deployment engine for repository : " + serverRepositoryDir); repositoryScanner.scan(); startScheduler(); }

Target:
public void start(String serverRepositoryDir, String runtimeRepositoryDir) throws DeploymentEngineException { serverRepositoryDirectory = new File(serverRepositoryDir); runtimeRepositoryDirectory = new File(runtimeRepositoryDir); if (!serverRepositoryDirectory.exists()) { throw new DeploymentEngineException("Cannot find repository : " + serverRepositoryDirectory); } if (!runtimeRepositoryDirectory.exists()) { throw new DeploymentEngineException("Cannot find repository : " + runtimeRepositoryDirectory); } if (logger.isDebugEnabled()) { logger.debug("Starting carbon deployment engine for repository : " + serverRepositoryDir); } repositoryScanner.scan(); startScheduler(); }
Source:
public static <A> Equal<A> anyEqual() { return new Equal<A>(a1 -> a2 -> a1.equals(a2)); }

Target:
public static <A> Equal<A> anyEqual() { return equal(a1 -> a2 -> a1.equals(a2)); }
Source:
public ArticleComment waitForVideo() { driver.switchTo().frame(1); wait.forElementVisible(By.cssSelector("img")); return this; }

Target:
public ArticleComment waitForVideo() { driver.switchTo().frame(commentIFrame); wait.forElementVisible(By.cssSelector("img")); return this; }
Source:
public void setClientPortListenBacklog(int backlog) { LOG.info("clientPortListenBacklog set to " + backlog); this.listenBacklog = backlog; }

Target:
public void setClientPortListenBacklog(int backlog) { this.listenBacklog = backlog; LOG.info("clientPortListenBacklog set to " + backlog); }
Source:
public static boolean matchesPartially(final MbusChannelElementsDto mbusChannelElements, final ChannelElementValuesDto channelElementValues) { final boolean validateMbusDeviceInfoMatch = !(failPartialMatchOnMbusIdentificationNumber(mbusChannelElements, channelElementValues) || failPartialMatchOnMbusManufacturerIdentification(mbusChannelElements, channelElementValues) || failPartialMatchOnMbusVersion(mbusChannelElements, channelElementValues) || failPartialMatchOnMbusDeviceTypeIdentification(mbusChannelElements, channelElementValues)); return channelElementValues.isMbusSlaveDeviceConfigured() && validateMbusDeviceInfoMatch; }

Target:
public static boolean matchesPartially(final MbusChannelElementsDto mbusChannelElements, final ChannelElementValuesDto channelElementValues) { return channelElementValues.isMbusSlaveDeviceConfigured() && validateMbusDeviceInfoPartialMatch(mbusChannelElements, channelElementValues); }
Source:
public static void afterClass() throws CommandFailedException, IOException, TimeoutException, InterruptedException { try { administration.reloadIfRequired(); administration.restartIfRequired(); } finally { client.close(); } }

Target:
public static void afterClass() throws CommandFailedException, IOException, TimeoutException, InterruptedException { try { administration.reloadIfRequired(); } finally { client.close(); } }
Source:
public String getId() { return email + "::" + course; }

Target:
public String getId() { return email + "%" + course; }
Source:
private static void executeDiffTask(DiffStrategy strategy, TableReference plusTable, TableReference minusTable, DiffStats stats, DiffTask task, MutableRange range) throws InterruptedException { final RangeRequest request = range.getRangeRequest(); long startTime = System.currentTimeMillis(); PartialDiffStats partialStats = task.call(request, range, strategy); stats.rowsOnlyInSource.addAndGet(partialStats.rowsOnlyInSource); stats.rowsPartiallyInCommon.addAndGet(partialStats.rowsPartiallyInCommon); stats.rowsCompletelyInCommon.addAndGet(partialStats.rowsCompletelyInCommon); stats.rowsVisited.addAndGet(partialStats.rowsVisited); stats.cellsOnlyInSource.addAndGet(partialStats.cellsOnlyInSource); stats.cellsInCommon.addAndGet(partialStats.cellsInCommon); if (log.isInfoEnabled()) { log.info("Processed diff of " + "{} rows " + "{} rows only in source " + "{} rows partially in common " + "{} rows completely in common " + "{} cells only in source " + "{} cells in common " + "between and in ms.", partialStats.rowsVisited, partialStats.rowsOnlyInSource, partialStats.rowsPartiallyInCommon, partialStats.rowsCompletelyInCommon, partialStats.cellsOnlyInSource, partialStats.cellsInCommon, plusTable, minusTable, System.currentTimeMillis() - startTime); } }

Target:
private static void executeDiffTask(DiffStrategy strategy, TableReference plusTable, TableReference minusTable, DiffStats stats, DiffTask task, MutableRange range) throws InterruptedException { final RangeRequest request = range.getRangeRequest(); long startTime = System.currentTimeMillis(); PartialDiffStats partialStats = task.call(request, range, strategy); stats.rowsOnlyInSource.addAndGet(partialStats.rowsOnlyInSource); stats.rowsPartiallyInCommon.addAndGet(partialStats.rowsPartiallyInCommon); stats.rowsCompletelyInCommon.addAndGet(partialStats.rowsCompletelyInCommon); stats.rowsVisited.addAndGet(partialStats.rowsVisited); stats.cellsOnlyInSource.addAndGet(partialStats.cellsOnlyInSource); stats.cellsInCommon.addAndGet(partialStats.cellsInCommon); if (log.isInfoEnabled()) { log.info("Processed diff of " + "{} rows " + "{} rows only in source " + "{} rows partially in common " + "{} rows completely in common " + "{} cells only in source " + "{} cells in common " + "between and in ms.", SafeArg.of("rowsVisited", partialStats.rowsVisited), SafeArg.of("rowsOnlyInSource", partialStats.rowsOnlyInSource), SafeArg.of("rowsPartiallyInCommon", partialStats.rowsPartiallyInCommon), SafeArg.of("rowsCompletelyInCommon", partialStats.rowsCompletelyInCommon), SafeArg.of("cellsOnlyInSource", partialStats.cellsOnlyInSource), SafeArg.of("cellsInCommon", partialStats.cellsInCommon), LoggingArgs.tableRef("plusTable", plusTable), LoggingArgs.tableRef("minusTable", minusTable), SafeArg.of("timeTaken", System.currentTimeMillis() - startTime)); } }
Source:
protected boolean isRegisteredStudent(){ return (account.googleId != null) && (!account.googleId.isEmpty()); }

Target:
protected boolean isRegisteredStudent(){ return account.isUserRegistered(); }
Source:
private String displayAllTasks() { String nl = System.lineSeparator(); StringBuilder answer = new StringBuilder("Tasks = {" + nl); for (String tid : tasks.keySet()) { answer.append(LogFormatter.addIndent(tasks.get(tid).display())).append(nl).append(nl); } answer.append("}"); return answer.toString(); }

Target:
private String displayAllTasks() { String nl = System.lineSeparator(); StringBuilder answer = new StringBuilder("Tasks = {"); answer.append(nl); for (String tid : tasks.keySet()) { answer.append(LogFormatter.addIndent(tasks.get(tid).display())).append(nl).append(nl); } answer.append("}"); return answer.toString(); }
Source:
private String composeExistingVmsWarningMessage(List<T> existingVms) { final StringBuffer s = new StringBuffer(); for (T t : existingVms) { if(s.length() > 0) { s.append(", "); } s.append(extractNameFromEntity(t)); } return s.toString(); }

Target:
private String composeExistingVmsWarningMessage(List<T> existingVms) { final List<String> list = new ArrayList<String>(); for (T t : existingVms) { list.add(extractNameFromEntity(t)); } return StringUtils.join(list, ", "); }
Source:
public MatrixLib sample_value() { checkHasParams(); int[] result = new int[k]; for (int i = 0; i < k; i++) { result[i] = 0; } for (int trial = 0; trial < n; trial++) { double val = Util.random(); int bucket; for (bucket = 0; bucket < k; bucket++) { if (val <= pCDF[bucket]) { break; } } result[bucket] += 1; } double[][] doubleResult = new double[1][n]; for (int i = 0; i < n; i++) { doubleResult[0][i] = result[i]; } return MatrixFactory.fromArray(doubleResult); }

Target:
public MatrixLib sample_value() { checkHasParams(); double[] result = new double[k]; for (int i = 0; i < k; i++) { result[i] = 0; } for (int trial = 0; trial < n; trial++) { double val = Util.random(); int bucket; for (bucket = 0; bucket < k; bucket++) { if (val <= pCDF[bucket]) { break; } } result[bucket] += 1; } return MatrixFactory.createRowVector(result); }
Source:
static void startLocalBookiesInternal(ServerConfiguration conf, String zkHost, int zkPort, int numBookies, boolean shouldStartZK, int initialBookiePort, boolean stopOnExit, String dirSuffix, String zkDataDir) throws Exception { LocalBookKeeper lb = new LocalBookKeeper(numBookies, initialBookiePort); ZooKeeperServerShim zks = null; File zkTmpDir = null; List<File> bkTmpDirs = null; try { if (shouldStartZK) { if (null == zkDataDir) { zkTmpDir = IOUtils.createTempDir("zookeeper", dirSuffix); } else { zkTmpDir = Files.createTempDirectory( Paths.get(zkDataDir), "zookeeper_localbookkeeper", new FileAttribute[0]).toFile(); } zkTmpDir.deleteOnExit(); zks = LocalBookKeeper.runZookeeper(1000, zkPort, zkTmpDir); } lb.initializeZookeeper(conf, zkHost, zkPort); conf.setZkServers(zkHost + ":" + zkPort); bkTmpDirs = lb.runBookies(conf, dirSuffix); try { while (true) { Thread.sleep(5000); } } catch (InterruptedException ie) { if (stopOnExit) { lb.shutdownBookies(); if (null != zks) { zks.stop(); } } throw ie; } } catch (Exception e) { LOG.error("Failed to run bookies : zk ensemble = '{}:{}'", numBookies, zkHost, zkPort, e); throw e; } finally { if (stopOnExit) { cleanupDirectories(bkTmpDirs); if (null != zkTmpDir) { FileUtils.deleteDirectory(zkTmpDir); } } } }

Target:
static void startLocalBookiesInternal(ServerConfiguration conf, String zkHost, int zkPort, int numBookies, boolean shouldStartZK, int initialBookiePort, boolean stopOnExit, String dirSuffix, String zkDataDir) throws Exception { LocalBookKeeper lb = new LocalBookKeeper(numBookies, initialBookiePort); ZooKeeperServerShim zks = null; File zkTmpDir = null; List<File> bkTmpDirs = null; try { if (shouldStartZK) { File zkDataDirFile = null; if (zkDataDir != null) { zkDataDirFile = new File(zkDataDir); } zkTmpDir = IOUtils.createTempDir("zookeeper", dirSuffix, zkDataDirFile); zkTmpDir.deleteOnExit(); zks = LocalBookKeeper.runZookeeper(1000, zkPort, zkTmpDir); } lb.initializeZookeeper(conf, zkHost, zkPort); conf.setZkServers(zkHost + ":" + zkPort); bkTmpDirs = lb.runBookies(conf, dirSuffix); try { while (true) { Thread.sleep(5000); } } catch (InterruptedException ie) { if (stopOnExit) { lb.shutdownBookies(); if (null != zks) { zks.stop(); } } throw ie; } } catch (Exception e) { LOG.error("Failed to run bookies : zk ensemble = '{}:{}'", numBookies, zkHost, zkPort, e); throw e; } finally { if (stopOnExit) { cleanupDirectories(bkTmpDirs); if (null != zkTmpDir) { FileUtils.deleteDirectory(zkTmpDir); } } } }
Source:
private Mono<Void> sendInternalTracingEnabled(Flux<EventData> events, String partitionKey) { return sendLinkMono.flatMap(link -> { final AtomicReference<Context> sendSpanContext = new AtomicReference<>(Context.NONE); return link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final BatchOptions batchOptions = new BatchOptions() .setPartitionKey(partitionKey) .setMaximumSizeInBytes(batchSize); final AtomicReference<Boolean> isFirst = new AtomicReference<>(true); return events.map(eventData -> { Context parentContext = eventData.getContext(); if (isFirst.get()) { Context entityContext = parentContext.addData(ENTITY_PATH, link.getEntityPath()); sendSpanContext.set(tracerProvider .startSpan(entityContext.addData(HOST_NAME, link.getHostname()), ProcessKind.SEND)); } isFirst.set(false); return setSpanContext(eventData, parentContext); }).collect(new EventDataCollector(batchOptions, 1, link::getErrorContext)); }) .flatMap(list -> sendInternal(Flux.fromIterable(list))) .doOnEach(signal -> { tracerProvider.endSpan(sendSpanContext.get(), signal); }); }); }

Target:
private Mono<Void> sendInternalTracingEnabled(Flux<EventData> events, String partitionKey) { return sendLinkMono.flatMap(link -> { final AtomicReference<Context> sendSpanContext = new AtomicReference<>(Context.NONE); return link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final BatchOptions batchOptions = new BatchOptions() .setPartitionKey(partitionKey) .setMaximumSizeInBytes(batchSize); final AtomicReference<Boolean> isFirst = new AtomicReference<>(true); return events.map(eventData -> { Context parentContext = eventData.getContext(); if (isFirst.getAndSet(false)) { Context entityContext = parentContext.addData(ENTITY_PATH, link.getEntityPath()); sendSpanContext.set(tracerProvider.startSpan( entityContext.addData(HOST_NAME, link.getHostname()), ProcessKind.SEND)); } return setSpanContext(eventData, parentContext); }).collect(new EventDataCollector(batchOptions, 1, link::getErrorContext)); }) .flatMap(list -> sendInternal(Flux.fromIterable(list))) .doOnEach(signal -> { tracerProvider.endSpan(sendSpanContext.get(), signal); }); }); }
Source:
public static String commaSeparateStrings( final ImmutableList<String> strings, final int indent) { if (isEmpty(strings)) { return ""; } return strings .stream() .map(i -> i) .collect(Collectors.joining(",\n" + indent(indent))); }

Target:
public static String commaSeparateStrings( final ImmutableList<String> strings, final int indent) { if (isEmpty(strings)) { return ""; } return strings .stream() .collect(Collectors.joining(",\n" + indent(indent))); }
Source:
protected void modified(ComponentContext context) { if (context != null) { Object value = context.getProperties().get("autoLinks"); if (value != null && value.toString().equals("false")) { autoLinks = false; } } }

Target:
protected void modified(ComponentContext context) { if (context != null) { Object value = context.getProperties().get("autoLinks"); autoLinks = value == null || !value.toString().equals("false"); } }
Source:
private FileInfo getOrCreateFlagImageFileInfo(final Map<URI, FileInfo> fileInfos, final URI file, final URI relpath) { assert file.getFragment() == null; final URI f = file.normalize(); FileInfo.Builder b; if (fileInfos.containsKey(f)) { b = new FileInfo.Builder(fileInfos.get(f)); } else { b = new FileInfo.Builder().src(file); } b = b.uri(tempFileNameScheme.generateTempFileName(baseInputDir.resolve(relpath))); final FileInfo i = b.build(); fileInfos.put(i.src, i); return i; }

Target:
private FileInfo getOrCreateFlagImageFileInfo(final Map<URI, FileInfo> fileInfos, final URI file, final URI relpath) { assert file.getFragment() == null; final URI f = file.normalize(); FileInfo.Builder b; if (fileInfos.containsKey(f)) { b = new FileInfo.Builder(fileInfos.get(f)); } else { b = new FileInfo.Builder().src(file); } b = b.uri(tempFileNameScheme.generateTempFileName(rootFile.resolve(relpath))); final FileInfo i = b.build(); fileInfos.put(i.src, i); return i; }
Source:
protected Scope visitCreateSchema(CreateSchema node, Optional<Scope> scope) { process(node.getProperties(), scope); return createAndAssignScope(node, scope); }

Target:
protected Scope visitCreateSchema(CreateSchema node, Optional<Scope> scope) { validateProperties(node.getProperties(), scope); return createAndAssignScope(node, scope); }
Source:
public CacheQuery<E> sort(Sort sort) { this.sort = sort; this.queryDefinition.setSort(sort); return super.sort(sort); }

Target:
public CacheQuery<E> sort(Sort sort) { this.queryDefinition.setSort(sort); return super.sort(sort); }
Source:
private static int getMaskSizeInBytes(int baseSeqNum, List<Integer> sortedProtectedSeqNums) { int largestSeqNum = sortedProtectedSeqNums.get(sortedProtectedSeqNums.size() - 1); int largestDelta = largestSeqNum - baseSeqNum; if (largestDelta <= 14) { return MASK_SIZE_SMALL; } else if (largestDelta <= 45) { return MASK_SIZE_MED; } return MASK_SIZE_LARGE; }

Target:
private static int getMaskSizeInBytes(int baseSeqNum, List<Integer> sortedProtectedSeqNums) throws MalformedMaskException { int largestDelta = -1; for (Integer protectedSeqNum : sortedProtectedSeqNums) { int delta = RTPUtils.getSequenceNumberDelta(protectedSeqNum, baseSeqNum); if (delta > largestDelta) { largestDelta = delta; } } if (largestDelta > 108) { throw new MalformedMaskException(); } if (largestDelta <= 14) { return MASK_SIZE_SMALL; } else if (largestDelta <= 45) { return MASK_SIZE_MED; } return MASK_SIZE_LARGE; }
Source:
public void reinit(TpeImageWidget iw, TpeImageInfo tii) { super.reinit(iw, tii); final TpeContext ctx = iw.getContext(); if (ctx.instrument().isEmpty()) return; final SPInstObsComp inst = ctx.instrument().get(); _feat = null; if (inst instanceof InstNIRI) { if (_niriFeat == null) _niriFeat = new NIRI_OIWFS_Feature(); _feat = _niriFeat; } else if (inst instanceof InstGmosNorth) { if (_gmosNFeat == null) _gmosNFeat = GmosNorthOIWFSFeature$.MODULE$; _feat = _gmosNFeat; } else if (inst instanceof InstGmosSouth || inst instanceof InstBHROS) { if (_gmosSFeat == null) _gmosSFeat = GmosSouthOIWFSFeature$.MODULE$; _feat = _gmosSFeat; } else if (inst instanceof InstGNIRS) { if (_gnirsFeat == null) _gnirsFeat = new GNIRS_OIWFS_Feature(); _feat = _gnirsFeat; } else if (inst instanceof InstNIFS) { if (_nifsFeat == null) _nifsFeat = new NIFS_OIWFS_Feature(); _feat = _nifsFeat; } else if (inst instanceof Flamingos2) { if (_flamingos2Feat == null) _flamingos2Feat = Flamingos2OIWFSFeature$.MODULE$; _feat = _flamingos2Feat; } if (_feat != null) { _feat.reinit(iw, tii); } }

Target:
public void reinit(TpeImageWidget iw, TpeImageInfo tii) { super.reinit(iw, tii); final TpeContext ctx = iw.getContext(); if (ctx.instrument().isEmpty()) return; final SPInstObsComp inst = ctx.instrument().get(); _feat = null; if (inst instanceof InstNIRI) { if (_niriFeat == null) _niriFeat = new NIRI_OIWFS_Feature(); _feat = _niriFeat; } else if (inst instanceof InstGmosNorth) _feat = GmosNorthOIWFSFeature.instance(); else if (inst instanceof InstGmosSouth || inst instanceof InstBHROS) _feat = GmosSouthOIWFSFeature.instance(); else if (inst instanceof InstGNIRS) { if (_gnirsFeat == null) _gnirsFeat = new GNIRS_OIWFS_Feature(); _feat = _gnirsFeat; } else if (inst instanceof InstNIFS) { if (_nifsFeat == null) _nifsFeat = new NIFS_OIWFS_Feature(); _feat = _nifsFeat; } else if (inst instanceof Flamingos2) _feat = Flamingos2OIWFSFeature.instance(); if (_feat != null) _feat.reinit(iw, tii); }
Source:
public static String encryptOrder(LgoKey lgoKey, LgoPlaceOrder lgoPlaceOrder) { try { String pub = lgoKey.getValue(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] keyBytes = Base64.getDecoder().decode(pub.getBytes(StandardCharsets.UTF_8)); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(spec); Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] cipherData = cipher.doFinal(lgoPlaceOrder.toPayload().getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(cipherData); } catch (Exception e) { throw new ExchangeException("Error encrypting order", e); } }

Target:
public static String encryptOrder(LgoKey lgoKey, LgoPlaceOrder lgoPlaceOrder) { try { String pub = lgoKey.getValue(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); byte[] keyBytes = Base64.getDecoder().decode(pub.getBytes(StandardCharsets.UTF_8)); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(spec); Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] cipherData = cipher.doFinal(lgoPlaceOrder.toPayload().getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(cipherData); } catch (NoSuchAlgorithmException e) { throw new ExchangeException("Error encrypting order: algorithm instance not available", e); } catch (NoSuchPaddingException e) { throw new ExchangeException("Error encrypting order: padding instance not available", e); } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeySpecException | InvalidKeyException e) { throw new ExchangeException("Error encrypting order: provided data invalid", e); } }
Source:
public void setEnableSmallFileFeatures(final boolean on) { enableSmallFileFeatures = on; if (enableSmallFileFeatures) { syntaxHighlighting.setValue(getValue().isSyntaxHighlighting()); } else { syntaxHighlighting.setValue(false); } NodeList<OptionElement> options = context.getElement().<SelectElement>cast().getOptions(); for (int i = 0; i < options.getLength(); i++) { OptionElement currOption = options.getItem(i); if (Short.parseShort(currOption.getValue()) == AccountDiffPreference.WHOLE_FILE_CONTEXT) { if (enableSmallFileFeatures) { currOption.setDisabled(false); } else { currOption.setDisabled(true); if (context.getSelectedIndex() > -1 && AccountDiffPreference.CONTEXT_CHOICES[context.getSelectedIndex()] == AccountDiffPreference.WHOLE_FILE_CONTEXT) { for (int j = 0; i < AccountDiffPreference.CONTEXT_CHOICES.length; j++) { if (AccountDiffPreference.CONTEXT_CHOICES[j] == PatchScreen.LARGE_FILE_CONTEXT) { context.setSelectedIndex(j); break; } } } } break; } } toggleEnabledStatus(save.isEnabled()); }

Target:
public void setEnableSmallFileFeatures(final boolean on) { enableSmallFileFeatures = on; if (enableSmallFileFeatures) { syntaxHighlighting.setValue(getValue().isSyntaxHighlighting()); } else { syntaxHighlighting.setValue(false); } NodeList<OptionElement> options = context.getElement().<SelectElement>cast().getOptions(); int lastIndex = options.getLength() - 1; OptionElement currOption = options.getItem(lastIndex); if (enableSmallFileFeatures) { currOption.setDisabled(false); } else { currOption.setDisabled(true); if (context.getSelectedIndex() == lastIndex) { context.setSelectedIndex(lastIndex - 1); } } toggleEnabledStatus(save.isEnabled()); }
Source:
public ChainrBuilder loader( ChainrInstantiator loader ) { this.chainrInstantiator = loader; return this; }

Target:
public ChainrBuilder loader( ChainrInstantiator loader ) { if ( loader == null ) { throw new RuntimeException( "ChainrBuilder requires a non-null laoder." ); } this.chainrInstantiator = loader; return this; }
Source:
public boolean setText (String html, boolean trusted) { byte[] bytes = (html + '\0').getBytes (StandardCharsets.UTF_8); boolean blankLoading = htmlBytes != null; htmlBytes = bytes; untrustedText = !trusted; if (WEBKIT2) { byte[] uriBytes; if (url != null) { uriBytes = Converter.wcsToMbcs (url, true); } else if (untrustedText) { uriBytes = Converter.wcsToMbcs (ABOUT_BLANK, true); } else { uriBytes = Converter.wcsToMbcs (URI_FILEROOT, true); } WebKitGTK.webkit_web_view_load_html (webView, htmlBytes, uriBytes); } else { if (blankLoading) return true; byte[] uriBytes = Converter.wcsToMbcs (ABOUT_BLANK, true); WebKitGTK.webkit_web_view_load_uri (webView, uriBytes); } return true; }

Target:
public boolean setText (String html, boolean trusted) { byte[] bytes = (html + '\0').getBytes (StandardCharsets.UTF_8); boolean blankLoading = htmlBytes != null; htmlBytes = bytes; untrustedText = !trusted; if (WEBKIT2) { byte[] uriBytes; if (untrustedText) { uriBytes = Converter.wcsToMbcs (ABOUT_BLANK, true); } else { uriBytes = Converter.wcsToMbcs (URI_FILEROOT, true); } WebKitGTK.webkit_web_view_load_html (webView, htmlBytes, uriBytes); } else { if (blankLoading) return true; byte[] uriBytes = Converter.wcsToMbcs (ABOUT_BLANK, true); WebKitGTK.webkit_web_view_load_uri (webView, uriBytes); } return true; }
Source:
private void processFeatures() { for (Feature feature : features) { List<ScenarioTag> scenarioList = new ArrayList<>(); Element[] scenarios = feature.getElements(); numberOfScenarios = getNumberOfScenarios(scenarios); int count = 1; if (featureNamesCount.containsKey(feature.getFileName())) { count = featureNamesCount.get(feature.getFileName()); count++; } featureNamesCount.put(feature.getFileName(),count); feature.setFileName(count); if (feature.hasTags()) { for (Element e : feature.getElements()) { if (!e.isBackground()) { scenarioList.add(new ScenarioTag(e, feature.getFileName())); } } addToTagMapByFeature(feature.getTags(), scenarioList); } for (Element scenario : scenarios) { if (!scenario.isBackground()) { totalBackgroundSteps.incrementFor(scenario.getStatus()); } else { setBackgroundInfo(scenario); } if (scenario.hasTags()) { addScenarioUnlessExists(scenarioList, new ScenarioTag(scenario, feature.getFileName())); addToTagMap(scenario.getTags(), scenarioList); } adjustStepsForScenario(scenario); } } }

Target:
private void processFeatures() { for (Feature feature : features) { List<ScenarioTag> scenarioList = new ArrayList<>(); Element[] scenarios = feature.getElements(); numberOfScenarios = getNumberOfScenarios(scenarios); int count = 1; if (featureIdsCount.containsKey(feature.getId())) { count = featureIdsCount.get(feature.getId()); count++; } featureIdsCount.put(feature.getId(), count); feature.setFileName(count); if (feature.hasTags()) { for (Element e : feature.getElements()) { if (!e.isBackground()) { scenarioList.add(new ScenarioTag(e, feature.getFileName())); } } addToTagMapByFeature(feature.getTags(), scenarioList); } for (Element scenario : scenarios) { if (!scenario.isBackground()) { totalBackgroundSteps.incrementFor(scenario.getStatus()); } else { setBackgroundInfo(scenario); } if (scenario.hasTags()) { addScenarioUnlessExists(scenarioList, new ScenarioTag(scenario, feature.getFileName())); addToTagMap(scenario.getTags(), scenarioList); } adjustStepsForScenario(scenario); } } }
Source:
public void execute() throws Exception { VirtualObject file = process.require(fileParameter); try (InputStream in = storage.getData(file)) { if (!canHandleFileExtension(file.getFileExtension()) && "zip".equalsIgnoreCase(file.getFileExtension())) { executeForZippedFile(in); return; } if (!canHandleFileExtension(file.getFileExtension())) { throw Exceptions.createHandled().withNLSKey("FileImportJob.fileNotSupported").handle(); } executeForStream(file.getFilename(), in); } }

Target:
public void execute() throws Exception { VirtualObject file = process.require(fileParameter); if (!canHandleFileExtension(file.getFileExtension())) { if ("zip".equalsIgnoreCase(file.getFileExtension())) { try (InputStream in = storage.getData(file)) { executeForZippedFile(in); } return; } throw Exceptions.createHandled().withNLSKey("FileImportJob.fileNotSupported").handle(); } try (InputStream in = storage.getData(file)) { executeForStream(file.getFilename(), in); } }
Source:
public void testColumnScannerStream() { Set<ColumnValue> colsVal = new HashSet<>(); Set<ColumnValue> empty = new HashSet<>(); Bytes row = Bytes.of("123"); colsVal.add(new ColumnValue(new Column("f1", "q1"), Bytes.of("v1"))); colsVal.add(new ColumnValue(new Column("f2", "q3"), Bytes.of("v2"))); colsVal.add(new ColumnValue(new Column("f1", "q1"), Bytes.of("v3"))); colsVal.add(new ColumnValue(new Column("f1", "q2"), Bytes.of("v4"))); colsVal.add(new ColumnValue(new Column("f2", "q5"), Bytes.of("v5"))); ColumnScanner colScanStream = new ColumnScannerImpl(row, colsVal); colsVal.stream().filter(cv -> cv.getColumn().getsFamily().equals("f2")) .collect(Collectors.toSet()); colScanStream.stream().filter(cv -> cv.getColumn().getsFamily().equals("f2")) .collect(Collectors.toSet()); Assert.assertNotEquals(empty, colScanStream.stream().collect(Collectors.toSet())); Assert.assertEquals(colsVal, colScanStream.stream().collect(Collectors.toSet())); Assert.assertEquals(colsVal.size(), colScanStream.stream().count()); }

Target:
public void testColumnScannerStream() { Set<ColumnValue> colsVal = new HashSet<>(); Set<ColumnValue> empty = new HashSet<>(); Bytes row = Bytes.of("123"); colsVal.add(new ColumnValue(new Column("f1", "q1"), Bytes.of("v1"))); colsVal.add(new ColumnValue(new Column("f2", "q3"), Bytes.of("v2"))); colsVal.add(new ColumnValue(new Column("f1", "q1"), Bytes.of("v3"))); colsVal.add(new ColumnValue(new Column("f1", "q2"), Bytes.of("v4"))); colsVal.add(new ColumnValue(new Column("f2", "q5"), Bytes.of("v5"))); ColumnScanner colScanner = new ColumnScannerImpl(row, colsVal); Set<ColumnValue> expected = colsVal.stream().filter(cv -> cv.getColumn().getsFamily().equals("f2")) .collect(Collectors.toSet()); Set<ColumnValue> colSubSet = colScanner.stream().filter(cv -> cv.getColumn().getsFamily().equals("f2")) .collect(Collectors.toSet()); Assert.assertNotEquals(empty, colSubSet); Assert.assertNotEquals(empty, colScanner.stream().collect(Collectors.toSet())); Assert.assertEquals(colsVal, colScanner.stream().collect(Collectors.toSet())); Assert.assertEquals(expected, colSubSet); }
Source:
public static Intent createChooserIntent(Intent targetIntent, CharSequence chooserTitle, Context context, String packageNameBlacklistRegex) { List<LabeledIntent> intents = queryIntents(context, targetIntent, packageNameBlacklistRegex); if (intents.isEmpty()) { return null; } Intent bestIntent = intents.remove(0); return Intent.createChooser(targetIntent, chooserTitle) .putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray()); }

Target:
public static Intent createChooserIntent(Intent targetIntent, CharSequence chooserTitle, Context context, String packageNameBlacklistRegex) { List<LabeledIntent> intents = queryIntents(context, targetIntent, packageNameBlacklistRegex); if (intents.isEmpty()) { return null; } Intent bestIntent = intents.remove(0); return Intent.createChooser(bestIntent, chooserTitle) .putExtra(Intent.EXTRA_INITIAL_INTENTS, intents.toArray(new Parcelable[0])); }
Source:
private void averageWaitingTime() { fWriter.println("----- Average waiting time with 3 requests -----"); for (int i = 0; i < NUM_LOOPS; i++) { ForegroundRequest foreground1 = new ForegroundRequest(TmfTimeRange.ETERNITY); ForegroundRequest foreground2 = new ForegroundRequest(TmfTimeRange.ETERNITY); BackgroundRequest background1 = new BackgroundRequest(TmfTimeRange.ETERNITY); fTrace.sendRequest(background1); fTrace.sendRequest(foreground1); fTrace.sendRequest(foreground2); try { foreground1.waitForCompletion(); foreground2.waitForCompletion(); background1.waitForCompletion(); } catch (InterruptedException e) { e.printStackTrace(); } averageWaitingBackground += background1.getAverageWaitingTime(); averageWaitingForeground1 += foreground1.getAverageWaitingTime(); averageWaitingForeground2 += foreground2.getAverageWaitingTime(); } fWriter.println("-- Background --"); fWriter.println((averageWaitingBackground / NUM_LOOPS) / 1000000 + " ms"); fWriter.println("-- First foreground --"); fWriter.println((averageWaitingForeground1 / NUM_LOOPS) / 1000000 + " ms"); fWriter.println("-- Second foreground --"); fWriter.println((averageWaitingForeground2 / NUM_LOOPS) / 1000000 + " ms"); }

Target:
private void averageWaitingTime() { System.out.println("----- Average waiting time with 3 requests -----"); for (int i = 0; i < NUM_LOOPS; i++) { ForegroundRequest foreground1 = new ForegroundRequest(TmfTimeRange.ETERNITY); ForegroundRequest foreground2 = new ForegroundRequest(TmfTimeRange.ETERNITY); BackgroundRequest background1 = new BackgroundRequest(TmfTimeRange.ETERNITY); fTrace.sendRequest(background1); fTrace.sendRequest(foreground1); fTrace.sendRequest(foreground2); try { foreground1.waitForCompletion(); foreground2.waitForCompletion(); background1.waitForCompletion(); } catch (InterruptedException e) { e.printStackTrace(); } averageWaitingBackground += background1.getAverageWaitingTime(); averageWaitingForeground1 += foreground1.getAverageWaitingTime(); averageWaitingForeground2 += foreground2.getAverageWaitingTime(); } System.out.println("-- Background --"); System.out.println((averageWaitingBackground / NUM_LOOPS) / NANOSECONDS_IN_MILLISECONDS + " ms"); System.out.println("-- First foreground --"); System.out.println((averageWaitingForeground1 / NUM_LOOPS) / NANOSECONDS_IN_MILLISECONDS + " ms"); System.out.println("-- Second foreground --"); System.out.println((averageWaitingForeground2 / NUM_LOOPS) / NANOSECONDS_IN_MILLISECONDS + " ms"); }