auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Result apply(AggregationNode aggregationNode, Captures captures, Context context) { boolean anyRewritten = false; ImmutableMap.Builder<Symbol, Aggregation> aggregations = ImmutableMap.builder(); for (Map.Entry<Symbol, Aggregation> entry : aggregationNode.getAggregations().entrySet()) { Aggregation aggregation = entry.getValue(); FunctionCall call = new FunctionCall( aggregation.getCall().getName(), Optional.empty(), aggregation.getFilter().map(a -> rewriter.rewrite(a, context)), aggregation.getCall().getOrderBy(), aggregation.isDistinct(), aggregation.getArguments().stream().map(a -> rewriter.rewrite(a, context)).collect(toImmutableList())); aggregations.put( entry.getKey(), new Aggregation(call, aggregation.getFunctionHandle(), aggregation.getMask())); if (!aggregation.getCall().equals(call)) { anyRewritten = true; } } if (anyRewritten) { return Result.ofPlanNode(new AggregationNode( aggregationNode.getId(), aggregationNode.getSource(), aggregations.build(), aggregationNode.getGroupingSets(), aggregationNode.getPreGroupedSymbols(), aggregationNode.getStep(), aggregationNode.getHashSymbol(), aggregationNode.getGroupIdSymbol())); } return Result.empty(); }

Target:
public Result apply(AggregationNode aggregationNode, Captures captures, Context context) { boolean anyRewritten = false; ImmutableMap.Builder<VariableReferenceExpression, Aggregation> aggregations = ImmutableMap.builder(); for (Map.Entry<VariableReferenceExpression, Aggregation> entry : aggregationNode.getAggregations().entrySet()) { Aggregation aggregation = entry.getValue(); Aggregation rewritten = new Aggregation( new CallExpression(aggregation.getCall().getDisplayName(), aggregation.getCall().getFunctionHandle(), aggregation.getCall().getType(), aggregation.getCall().getArguments() .stream() .map(argument -> castToRowExpression(rewriter.rewrite(castToExpression(argument), context))) .collect(toImmutableList())), aggregation.getFilter() .map(filter -> castToRowExpression(rewriter.rewrite(castToExpression(filter), context))), aggregation.getOrderBy(), aggregation.isDistinct(), aggregation.getMask()); aggregations.put(entry.getKey(), rewritten); if (!aggregation.equals(rewritten)) { anyRewritten = true; } } if (anyRewritten) { return Result.ofPlanNode(new AggregationNode( aggregationNode.getId(), aggregationNode.getSource(), aggregations.build(), aggregationNode.getGroupingSets(), aggregationNode.getPreGroupedVariables(), aggregationNode.getStep(), aggregationNode.getHashVariable(), aggregationNode.getGroupIdVariable())); } return Result.empty(); }
Source:
protected void requestDatacentersToCreateWaitingCloudlets() { final List<Cloudlet> successfullySubmitted = new ArrayList<>(); for (final Cloudlet cloudlet : getCloudletWaitingList()) { if (cloudletCreationRequestsMap.containsKey(cloudlet)) { continue; } lastSelectedVm = vmMapper.apply(cloudlet); if (lastSelectedVm == Vm.NULL) { println(String.format( "%.2f: %s: : Postponing execution of cloudlet %d: bind VM not available.", getSimulation().clock(), getName(), cloudlet.getId())); continue; } println(String.format( "%.2f: %s: Sending %s %d to %s in %s.", getSimulation().clock(), getName(), cloudlet.getClass().getSimpleName(), cloudlet.getId(), lastSelectedVm, lastSelectedVm.getHost())); cloudlet.setVm(lastSelectedVm); send(getVmDatacenter(lastSelectedVm).getId(), cloudlet.getSubmissionDelay(), CloudSimTags.CLOUDLET_SUBMIT, cloudlet); cloudletCreationRequestsMap.put(cloudlet, getVmDatacenter(lastSelectedVm)); cloudletsCreated++; successfullySubmitted.add(cloudlet); } cloudletWaitingList.removeAll(successfullySubmitted); }

Target:
protected void requestDatacentersToCreateWaitingCloudlets() { final List<Cloudlet> successfullySubmitted = new ArrayList<>(); for (final Cloudlet cloudlet : cloudletWaitingList) { if (cloudletCreationRequestsMap.containsKey(cloudlet)) { continue; } lastSelectedVm = vmMapper.apply(cloudlet); if (lastSelectedVm == Vm.NULL) { println(String.format( "%.2f: %s: : Postponing execution of cloudlet %d: bind VM not available.", getSimulation().clock(), getName(), cloudlet.getId())); continue; } println(String.format( "%.2f: %s: Sending %s %d to %s in %s.", getSimulation().clock(), getName(), cloudlet.getClass().getSimpleName(), cloudlet.getId(), lastSelectedVm, lastSelectedVm.getHost())); cloudlet.setVm(lastSelectedVm); send(getVmDatacenter(lastSelectedVm).getId(), cloudlet.getSubmissionDelay(), CloudSimTags.CLOUDLET_SUBMIT, cloudlet); cloudletCreationRequestsMap.put(cloudlet, getVmDatacenter(lastSelectedVm)); cloudletsCreated++; successfullySubmitted.add(cloudlet); } cloudletWaitingList.removeAll(successfullySubmitted); }
Source:
public @Nullable IntervalField getEndField() { return endField; }

Target:
public IntervalField getEndField() { return endField; }
Source:
private boolean connectorSupportsTest(TypeElement connector, Class<?> test) { Set<ConnectorFeature> supportedFeatures = supportedFeatures(connector); Set<ConnectorFeature> requiredFeatures = requiredFeatures(test); return supportedFeatures.containsAll(requiredFeatures); }

Target:
private static boolean connectorSupportsTest(TypeElement connector, Class<?> test) { Set<ConnectorFeature> supportedFeatures = supportedFeatures(connector); Set<ConnectorFeature> requiredFeatures = requiredFeatures(test); return supportedFeatures.containsAll(requiredFeatures); }
Source:
private void printPlugins() { final List<String> installedPlugins = getInstalledPlugins(); if (installedPlugins != null) { System.out.println("The following DITA-OT plugins are installed:"); for (final String plugin : installedPlugins) { System.out.println(" " + plugin); } } else { System.out.println("No DITA-OT plugins are installed."); } }

Target:
private void printPlugins() { final List<String> installedPlugins = getInstalledPlugins(); for (final String plugin : installedPlugins) { System.out.println(plugin); } }
Source:
public List<Facility> getAllowedFacilities(PerunSession sess, Member member) throws InternalErrorException { return getFacilitiesManagerImpl().getAllowedFacilities(sess, member); }

Target:
public List<Facility> getAllowedFacilities(PerunSession sess, Member member) { return getFacilitiesManagerImpl().getAllowedFacilities(sess, member); }
Source:
EmbeddedPostgres(File parentDirectory, File dataDirectory, boolean cleanDataDirectory, Map<String, String> postgresConfig, Map<String, String> localeConfig, int port, Map<String, String> connectConfig, PgDirectoryResolver pgDirectoryResolver, ProcessBuilder.Redirect errorRedirector, ProcessBuilder.Redirect outputRedirector, Duration pgStartupWait, Optional<File> overrideWorkingDirectory) throws IOException { this.cleanDataDirectory = cleanDataDirectory; this.postgresConfig = new HashMap<>(postgresConfig); this.localeConfig = new HashMap<>(localeConfig); this.port = port; this.pgDir = pgDirectoryResolver.getDirectory(overrideWorkingDirectory); this.errorRedirector = errorRedirector; this.outputRedirector = outputRedirector; this.pgStartupWait = Objects.requireNonNull(pgStartupWait, "Wait time cannot be null"); if (parentDirectory != null) { mkdirs(parentDirectory); cleanOldDataDirectories(parentDirectory); if (dataDirectory != null) { this.dataDirectory = dataDirectory; } else { this.dataDirectory = new File(parentDirectory, instanceId.toString()); } } else { this.dataDirectory = dataDirectory; } if (this.dataDirectory == null) { throw new IllegalArgumentException("no data directory"); } LOG.info("{} postgres: data directory is {}, postgres directory is {}", instanceId, this.dataDirectory, this.pgDir); mkdirs(this.dataDirectory); lockFile = new File(this.dataDirectory, LOCK_FILE_NAME); if (cleanDataDirectory || !new File(dataDirectory, "postgresql.conf").exists()) { initdb(); } lock(); startPostmaster(connectConfig); }

Target:
EmbeddedPostgres(File parentDirectory, File dataDirectory, boolean cleanDataDirectory, Map<String, String> postgresConfig, Map<String, String> localeConfig, int port, Map<String, String> connectConfig, PgDirectoryResolver pgDirectoryResolver, ProcessBuilder.Redirect errorRedirector, ProcessBuilder.Redirect outputRedirector, Duration pgStartupWait, Optional<File> overrideWorkingDirectory) throws IOException { this.cleanDataDirectory = cleanDataDirectory; this.postgresConfig = new HashMap<>(postgresConfig); this.localeConfig = new HashMap<>(localeConfig); this.port = port; this.pgDir = pgDirectoryResolver.getDirectory(overrideWorkingDirectory); this.errorRedirector = errorRedirector; this.outputRedirector = outputRedirector; this.pgStartupWait = Objects.requireNonNull(pgStartupWait, "Wait time cannot be null"); if (parentDirectory != null) { mkdirs(parentDirectory); cleanOldDataDirectories(parentDirectory); if (dataDirectory != null) { this.dataDirectory = dataDirectory; } else { this.dataDirectory = new File(parentDirectory, instanceId.toString()); } } else { this.dataDirectory = dataDirectory; } if (this.dataDirectory == null) { throw new IllegalArgumentException("no data directory"); } LOG.debug("{} postgres: data directory is {}, postgres directory is {}", instanceId, this.dataDirectory, this.pgDir); mkdirs(this.dataDirectory); lockFile = new File(this.dataDirectory, LOCK_FILE_NAME); if (cleanDataDirectory || !new File(dataDirectory, "postgresql.conf").exists()) { initdb(); } lock(); startPostmaster(connectConfig); }
Source:
public byte[] call(final byte[] bytes) throws Exception { CatchableExecutors.newSingleThreadExecutor().submit(() -> { for (int i = 1; i <= 100; i++) { LOG.log(Level.INFO, "Test print : [{0} / 200]", i); } final int errorNumber = 1 / 0; for (int i = 101; i <= 200; i++) { LOG.log(Level.INFO, "Test print : [{0} / 200]", i); } }); Thread.sleep(5000); return null; }

Target:
public byte[] call(final byte[] bytes) throws Exception { CatchableExecutors.newSingleThreadExecutor().submit(() -> { LOG.log(Level.INFO, "Before error"); final int errorNumber = 1 / 0; LOG.log(Level.INFO, "After error"); }); Thread.sleep(5000); return null; }
Source:
public void stop() { LOG.info("Oracle TriggerBased connector stop requested."); try { _daemonThreadExecutorService.shutdown(); if (!_daemonThreadExecutorService.awaitTermination(5, TimeUnit.SECONDS)) { LOG.warn("Timeout waiting for daemon thread to stop! Continue to shutdown all task handlers."); } } catch (InterruptedException e) { LOG.error("Interrupted when waiting for daemon thread to stop! Continue to shutdown all task handlers.", e); } _daemonThreadExecutorService = null; if (_namedTaskHandlers != null) { LOG.info(String.format("attempting to shutdown %s connector ...", CONNECTOR_TYPE)); synchronized (this) { _namedTaskHandlers.values().forEach(OracleTaskHandler::stop); } ThreadUtils.shutdownExecutor(_executorService, SHUTDOWN_TIMEOUT, LOG); } LOG.info(String.format("%s connector has successfully stopped", CONNECTOR_TYPE)); }

Target:
public void stop() { LOG.info(String.format("attempting to shutdown %s connector ...", CONNECTOR_TYPE)); _namedTaskHandlers.values().forEach(OracleTaskHandler::stop); if (!ThreadUtils.shutdownExecutor(_executorService, SHUTDOWN_TIMEOUT, LOG)) { LOG.warn("Failed to shut down OracleTaskHandler Executor Service cleanly"); } if (!ThreadUtils.shutdownExecutor(_daemonThreadExecutorService, SHUTDOWN_TIMEOUT, LOG)) { LOG.warn("Failed to shut down daemon Thread Executor Service cleanly"); } _daemonThreadExecutorService = null; _namedTaskHandlers.clear(); LOG.info(String.format("%s connector has successfully stopped", CONNECTOR_TYPE)); }
Source:
protected Iterable<IAnalysisModule> getDependentAnalyses() { ITmfTrace trace = getTrace(); if (trace != null) { ISegmentStoreProvider provider = findSegmentProviderAnalysis(trace); if (provider != null && provider instanceof IAnalysisModule) { fSegmentStoreProviderModule = (IAnalysisModule) provider; return ImmutableList.of((IAnalysisModule) provider); } } return super.getDependentAnalyses(); }

Target:
protected Iterable<IAnalysisModule> getDependentAnalyses() { ITmfTrace trace = getTrace(); if (trace != null) { ISegmentStoreProvider provider = getSegmentProviderAnalysis(trace); if (provider instanceof IAnalysisModule) { fSegmentStoreProviderModule = (IAnalysisModule) provider; return ImmutableList.of((IAnalysisModule) provider); } } return super.getDependentAnalyses(); }
Source:
public void onEvent(PersistenceProcessorImpl.PersistBatchEvent batchEvent) throws Exception { int commitEventsToFlush = 0; Batch batch = batchEvent.getBatch(); int numOfBatchedEvents = batch.getNumEvents(); batchSizeHistogram.update(numOfBatchedEvents); for (int i=0; i < numOfBatchedEvents; ++i) { PersistEvent event = batch.get(i); switch (event.getType()) { case COMMIT: event.getMonCtx().timerStart("commitPersistProcessor"); writer.addCommittedTransaction(event.getStartTimestamp(), event.getCommitTimestamp()); commitEventsToFlush++; break; case ABORT: break; case TIMESTAMP: event.getMonCtx().timerStart("timestampPersistProcessor"); break; } } if(commitEventsToFlush > 0) { flush(commitEventsToFlush); } filterClientRetriesAndSendBatchToReplyProcessor(batch, batchEvent.getBatchSequence()); }

Target:
public void onEvent(PersistenceProcessorImpl.PersistBatchEvent batchEvent) throws Exception { int commitEventsToFlush = 0; Batch batch = batchEvent.getBatch(); int numOfBatchedEvents = batch.getNumEvents(); batchSizeHistogram.update(numOfBatchedEvents); for (int i=0; i < numOfBatchedEvents; ++i) { PersistEvent event = batch.get(i); switch (event.getType()) { case COMMIT: event.getMonCtx().timerStart("commitPersistProcessor"); writer.addCommittedTransaction(event.getStartTimestamp(), event.getCommitTimestamp()); commitEventsToFlush++; break; case ABORT: break; case TIMESTAMP: event.getMonCtx().timerStart("timestampPersistProcessor"); break; } } flush(commitEventsToFlush); filterAndDissambiguateClientRetries(batch); replyProcessor.manageResponsesBatch(batchEvent.getBatchSequence(), batch); }
Source:
MetricsInterceptor( Provider<Registry> registry, OkHttpMetricsInterceptorProperties okHttpMetricsInterceptorProperties) { this.registry = registry; this.okHttpMetricsInterceptorProperties = okHttpMetricsInterceptorProperties; this.headerCheckPattern = okHttpMetricsInterceptorProperties.getHeaderCheckRegExPattern(); this.log = LoggerFactory.getLogger(getClass()); }

Target:
MetricsInterceptor( Provider<Registry> registry, OkHttpMetricsInterceptorProperties okHttpMetricsInterceptorProperties) { this.registry = registry; this.okHttpMetricsInterceptorProperties = okHttpMetricsInterceptorProperties; this.log = LoggerFactory.getLogger(getClass()); }
Source:
public boolean exists(K key) throws GoraException { try { ColumnSchema column = table.getSchema().getColumn(kuduMapping.getPrimaryKey().get(0).getName()); KuduScanner.KuduScannerBuilder scannerBuilder = client.newScannerBuilder(table); scannerBuilder.limit(1); scannerBuilder.setProjectedColumnIndexes(new ArrayList<>()); scannerBuilder.addPredicate(KuduClientUtils.createEqualPredicate(column, key)); KuduScanner build = scannerBuilder.build(); RowResult waitFirstResult = KuduClientUtils.waitFirstResult(build); build.close(); return waitFirstResult != null; } catch (Exception e) { throw new GoraException(e); } }

Target:
public boolean exists(K key) throws GoraException { try { ColumnSchema column = table.getSchema().getColumn(kuduMapping.getPrimaryKey().get(0).getName()); ArrayList<KuduPredicate> equalPredicate = new ArrayList<>(); equalPredicate.add(KuduClientUtils.createEqualPredicate(column, key)); KuduScanner build = createScanner(equalPredicate, new ArrayList<>(), 1); RowResult waitFirstResult = KuduClientUtils.waitFirstResult(build); build.close(); return waitFirstResult != null; } catch (Exception e) { throw new GoraException(e); } }
Source:
private void writeSubscribeCommands( String repoName, List<SubscribeCommand> commands) throws IOException { write("repository " + repoName); for (SubscribeCommand cmd : commands) { switch (cmd.getCommand()) { case SUBSCRIBE: write("want " + cmd.getSpec()); break; case UNSUBSCRIBE: write("stop " + cmd.getSpec()); break; } } }

Target:
private void writeSubscribeCommands( String repoName, List<SubscribeCommand> commands) throws IOException { write("repository " + repoName); for (SubscribeCommand cmd : commands) { switch (cmd.getCommand()) { case SUBSCRIBE: write("want " + cmd.getSpec()); break; case UNSUBSCRIBE: write("stop " + cmd.getSpec()); break; default: throw new IllegalArgumentException(); } } }
Source:
private static void refreshBorderFigure(final BorderedStyle borderedStyle, final StyledFigure styledFigure) { LineBorder lineBorder = null; if (styledFigure.getBorder() instanceof LineBorder) { lineBorder = (LineBorder) styledFigure.getBorder(); } else { lineBorder = new LineBorder(); if (styledFigure instanceof Shape) { styledFigure.setBorder(null); } else { styledFigure.setBorder(lineBorder); } } int borderSize = 0; if (borderedStyle.getBorderSize() != null) { borderSize = borderedStyle.getBorderSize().intValue(); } lineBorder.setWidth(borderSize); final RGBValues borderColor = borderedStyle.getBorderColor(); if (borderColor != null) { lineBorder.setColor(VisualBindingManager.getDefault().getColorFromRGBValues(borderColor)); } if (borderedStyle.getBorderSize() == null || borderSize == 0) { if (!(styledFigure instanceof NoteFigure)) { styledFigure.setBorder(null); } } }

Target:
private static void refreshBorderFigure(final BorderedStyle borderedStyle, final StyledFigure styledFigure) { LineBorder lineBorder = null; if (styledFigure.getBorder() instanceof LineBorder) { lineBorder = (LineBorder) styledFigure.getBorder(); } else { lineBorder = new LineBorder(); if (styledFigure instanceof Shape) { styledFigure.setBorder(null); } else { styledFigure.setBorder(lineBorder); } } int borderSize = 0; if (borderedStyle.getBorderSize() != null) { borderSize = borderedStyle.getBorderSize().intValue(); } lineBorder.setWidth(borderSize); final RGBValues borderColor = borderedStyle.getBorderColor(); if (borderColor != null) { lineBorder.setColor(VisualBindingManager.getDefault().getColorFromRGBValues(borderColor)); } if (borderSize == 0) { if (!(styledFigure instanceof NoteFigure)) { styledFigure.setBorder(null); } } }
Source:
public static void respond(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { if (CORS_ENABLED) { res.headers().add("Access-Control-Allow-Origin", CORS_ALLOWED_ORIGINS); } if (res.content() != null) { HttpUtil.setContentLength(res, res.content().readableBytes()); } boolean isKeepAlive = HttpUtil.isKeepAlive(req); if (isKeepAlive) { res.headers().add(CONNECTION, KEEP_ALIVE); } ctx.channel().write(res); if (req == null || !isKeepAlive) { log.debug("Closing channel. isKeepAlive:" + isKeepAlive); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } }

Target:
public static void respond(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { if (CORS_ENABLED) { res.headers().add("Access-Control-Allow-Origin", CORS_ALLOWED_ORIGINS); } if (res.content() != null) { setContentLength(res, res.content().readableBytes()); } boolean isKeepAlive = isKeepAlive(req); if (isKeepAlive) { res.headers().add(CONNECTION, KEEP_ALIVE); } ctx.channel().write(res); if (req == null || !isKeepAlive) { log.debug("Closing channel. isKeepAlive:" + isKeepAlive + " on channel: " + ctx.channel().toString()); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } }
Source:
public boolean isTaskHandled(Task task) { boolean handled = false; if(this.handledTasksId == null) { this.handledTasksId = new ArrayList<>(); } for (Long handledTaskId : this.handledTasksId) { if (handledTaskId.equals(task.getId())) { handled = true; break; } } return handled; }

Target:
private boolean isTaskHandled(Task task) { boolean handled = false; if (this.handledTasksId.contains(task.getId())) { handled = true; } return handled; }
Source:
public void getTableMetaDataViewThrowsExceptionWhenGetConnectionHasSqlException() throws SQLException { when(dataSource.getConnection()).thenThrow(SQLException.class); Throwable throwable = catchThrowable(() -> service.getTableMetaDataView(mapping)); assertThat(throwable).isInstanceOf(JdbcConnectorException.class).hasMessageContaining( "Exception thrown while connecting to datasource \"dataSource\": null"); verify(connection, never()).close(); }

Target:
public void getTableMetaDataViewThrowsExceptionWhenGetConnectionHasSqlException() throws SQLException { String reason = "connection failed"; when(dataSource.getConnection()).thenThrow(new SQLException(reason)); Throwable throwable = catchThrowable(() -> service.getTableMetaDataView(mapping)); assertThat(throwable).isInstanceOf(JdbcConnectorException.class).hasMessageContaining( String.format("Exception thrown while connecting to datasource \"dataSource\": %s", reason)); verify(connection, never()).close(); }
Source:
private void doInitialize(RequestMonitor requestMonitor) { fSessionInitializationComplete = false; fCommandControl = getServicesTracker().getService(IGDBControl.class); fCommandFactory = getServicesTracker().getService(IMICommandControl.class).getCommandFactory(); fBackend = getServicesTracker().getService(IGDBBackend.class); fFetchCPUInfoCache = new CommandCache(getSession(), new CPUInfoManager()); fFetchCPUInfoCache.setContextAvailable(fCommandControl.getContext(), true); fLoadInfoRequestCache = new ArrayList<LoadInfoRequest>(); getSession().addServiceEventListener(this, null); register(new String[] { IGDBHardwareAndOS.class.getName(), GDBHardwareAndOS.class.getName() }, new Hashtable<String, String>()); requestMonitor.done(); }

Target:
private void doInitialize(RequestMonitor requestMonitor) { fSessionInitializationComplete = false; fCommandControl = getServicesTracker().getService(IGDBControl.class); fCommandFactory = getServicesTracker().getService(IMICommandControl.class).getCommandFactory(); fBackend = getServicesTracker().getService(IGDBBackend.class); fFetchCPUInfoCache = new CommandCache(getSession(), new CPUInfoManager()); fFetchCPUInfoCache.setContextAvailable(fCommandControl.getContext(), true); fLoadInfoRequestCache = new HashMap<IDMContext, DataRequestMonitor<ILoadInfo>>(); getSession().addServiceEventListener(this, null); register(new String[] { IGDBHardwareAndOS.class.getName(), IGDBHardwareAndOS2.class.getName(), GDBHardwareAndOS.class.getName() }, new Hashtable<String, String>()); requestMonitor.done(); }
Source:
public CategoryPage openCategoryPage(String name) { WebElement link = categoryList.findElement(By.cssSelector("a[title=\"" + name + "\"]")); PageObjectLogging.logInfo("Open category page named: " + name); wait.forElementClickable(link); link.click(); loading.handleAsyncPageReload(); Assertion.assertTrue(driver.getCurrentUrl().contains("/wiki/Category:"), "Url is different than /wiki/Category:"); PageObjectLogging.logInfo("You were redirected to /wiki/Category:"); return new CategoryPage(); }

Target:
public CategoryPage openCategoryPage(String name) { WebElement link = categoryList.findElement( By.cssSelector(String.format("a[title=\"%s\"]", name)) ); PageObjectLogging.logInfo(String.format("Open category page named: \"%s\".", name)); wait.forElementClickable(link); link.click(); loading.handleAsyncPageReload(); Assertion.assertTrue(driver.getCurrentUrl().contains("/wiki/Category:"), "Url is different than /wiki/Category:"); PageObjectLogging.logInfo("You were redirected to /wiki/Category:"); return new CategoryPage(); }
Source:
public PatientData<Map<String, String>> readJSON(JSONObject json) { Object testGeneJson = json.get(this.getJsonPropertyName()); if (testGeneJson == null) { return null; } try { JSONArray genesJson = json.getJSONArray(this.getJsonPropertyName()); List<Map<String, String>> allGenes = new LinkedList<Map<String, String>>(); for (Object geneJsonUncast : genesJson) { JSONObject geneJson = JSONObject.fromObject(geneJsonUncast); Map<String, String> singleGene = new LinkedHashMap<String, String>(); for (String property : getProperties()) { if (geneJson.has(property)) { String field = geneJson.getString(property); if (field != null) { singleGene.put(property, field); } } } allGenes.add(singleGene); } if (allGenes.isEmpty()) { return null; } else { return new IndexedPatientData<Map<String, String>>(getName(), allGenes); } } catch (Exception e) { this.logger.error("Could not load genes from JSON", e.getMessage()); } return null; }

Target:
public PatientData<Map<String, String>> readJSON(JSONObject json) { Object testGeneJson = json.get(this.getJsonPropertyName()); if (testGeneJson == null) { return null; } try { JSONArray genesJson = json.getJSONArray(this.getJsonPropertyName()); List<Map<String, String>> allGenes = new LinkedList<Map<String, String>>(); for (Object geneJsonUncast : genesJson) { JSONObject geneJson = JSONObject.fromObject(geneJsonUncast); Map<String, String> singleGene = new LinkedHashMap<String, String>(); for (String property : this.getProperties()) { if (geneJson.has(property)) { String field = geneJson.getString(property); if (field != null) { singleGene.put(property, field); } } } if (!singleGene.isEmpty()) { allGenes.add(singleGene); } } if (allGenes.isEmpty()) { return null; } else { return new IndexedPatientData<Map<String, String>>(getName(), allGenes); } } catch (Exception e) { this.logger.error("Could not load genes from JSON", e.getMessage()); } return null; }
Source:
public boolean delete(ResourcePath path) { final SearchResults results = searchFor(path, 0, true); if (results.isEmpty()) { return false; } for (final Result result : results) { for(String metricName: result.getMetrics()) { Metric metric = Metric.builder() .tag(CommonTagNames.resourceId, result.getResource().getId()) .tag(CommonTagNames.name, metricName) .tag(Metric.MandatoryTag.mtype.name(), Metric.Mtype.gauge.name()) .tag(Metric.MandatoryTag.unit.name(), CommonTagValues.unknown) .build(); try { storage.delete(metric); } catch (StorageException e) { LOG.error("Could not delete {}, will ignore problem and continue ", metric, e); } } } return true; }

Target:
public boolean delete(ResourcePath path) { final SearchResults results = searchFor(path, 0, true); if (results.isEmpty()) { return false; } for (final Result result : results) { for(String metricName: result.getMetrics()) { Metric metric = ImmutableMetric.builder() .intrinsicTag(CommonTagNames.resourceId, result.getResource().getId()) .intrinsicTag(CommonTagNames.name, metricName) .build(); try { storageManager.get().delete(metric); } catch (StorageException e) { LOG.error("Could not delete {}, will ignore problem and continue ", metric, e); } } } return true; }
Source:
private static File getFileFromClassLoader4Luna(String filename, ClassLoader classLoader) throws AssertionFailedError { String AssertionFailedErrorMessage = "no file found " + filename; try { Object classpathManager = MethodUtils.invokeExactMethod(classLoader, "getClasspathManager", null); if (classpathManager != null) { Object generation = MethodUtils.invokeExactMethod(classpathManager, "getGeneration", null); if (generation != null) { Object bundleFile = MethodUtils.invokeExactMethod(generation, "getBundleFile", null); if (bundleFile != null) { File file = (File) MethodUtils.invokeExactMethod(bundleFile, "getFile", new Object[] { filename, true }, new Class[] { String.class, boolean.class }); if (file != null) { return file; } } } } } catch (NoSuchMethodException e) { AssertionFailedErrorMessage = "got NoSuchMethodException " + e.getMessage(); } catch (IllegalAccessException e) { AssertionFailedErrorMessage = "got IllegalAccessException " + e.getMessage(); } catch (InvocationTargetException e) { AssertionFailedErrorMessage = "got InvocationTargetException " + e.getMessage(); } throw new AssertionFailedError(AssertionFailedErrorMessage); }

Target:
private static File getFileFromClassLoader4Luna(String filename, ClassLoader classLoader) throws Exception { Object classpathManager = MethodUtils.invokeExactMethod(classLoader, "getClasspathManager", null); Object generation = MethodUtils.invokeExactMethod(classpathManager, "getGeneration", null); Object bundleFile = MethodUtils.invokeExactMethod(generation, "getBundleFile", null); File file = (File) MethodUtils.invokeExactMethod(bundleFile, "getFile", new Object[] { filename, true }, new Class[] { String.class, boolean.class }); return file; }
Source:
public SolenoidSet(SolenoidSubsystem system, SolenoidState state) { this(system, state, () -> { return false; }); }

Target:
public SolenoidSet(SolenoidSubsystem system, SolenoidState state) { this("SolenoidSet", system, state); }
Source:
public void cloneSnapshot(String snapshotName, TableName tableName) throws IOException, TableExistsException, RestoreSnapshotException { BigtableInstanceName instanceName = options.getInstanceName(); BigtableClusterName clusterName = this.connection.getSession().getClusterName(); String btSnapshotName = clusterName.toSnapshotName(snapshotName); bigtableTableAdminClient.createTableFromSnapshot(CreateTableFromSnapshotRequest.newBuilder() .setParent(instanceName.toString()) .setTableId(tableName.getNameAsString()) .setSourceSnapshot(btSnapshotName) .build()); }

Target:
public void cloneSnapshot(String snapshotName, TableName tableName) throws IOException, TableExistsException, RestoreSnapshotException { CreateTableFromSnapshotRequest request = CreateTableFromSnapshotRequest.newBuilder() .setParent(options.getInstanceName().toString()) .setTableId(tableName.getNameAsString()) .setSourceSnapshot(getClusterName().toSnapshotName(snapshotName)) .build(); waitForOperation(bigtableTableAdminClient.createTableFromSnapshot(request)); }
Source:
void replace(final int word, final int oldTopicIdx, final int newTopicIdx, final int delta) { if (!changedTopicCounts.contains(word, oldTopicIdx)) { changedTopicCounts.put(word, oldTopicIdx, 0); } changedTopicCounts.put(word, oldTopicIdx, changedTopicCounts.get(word, oldTopicIdx) - delta); if (!changedTopicCounts.contains(word, newTopicIdx)) { changedTopicCounts.put(word, newTopicIdx, 0); } changedTopicCounts.put(word, newTopicIdx, changedTopicCounts.get(word, newTopicIdx) + delta); }

Target:
void replace(final int word, final int oldTopicIdx, final int newTopicIdx, final int delta) { final Integer countOldTopic = changedTopicCounts.get(word, oldTopicIdx); if (countOldTopic == null) { changedTopicCounts.put(word, oldTopicIdx, -delta); } else { changedTopicCounts.put(word, oldTopicIdx, countOldTopic - delta); } final Integer countNewTopic = changedTopicCounts.get(word, newTopicIdx); if (countNewTopic == null) { changedTopicCounts.put(word, newTopicIdx, delta); } else { changedTopicCounts.put(word, newTopicIdx, countNewTopic + delta); } }
Source:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addSlide(AppIntroFragment.newInstance("Welcome", "The global OpenMRS community works together to build the world's leading open source enterprise electronic medical record system platform.", R.drawable.openmrs_action_logo, Color.parseColor("#5B57A6"))); addSlide(AppIntroFragment.newInstance("Register Patients", "You can register your new patients to our server", R.drawable.ico_registry, Color.parseColor("#F26522"))); addSlide(AppIntroFragment.newInstance("Find Patients", "You can find and monitor those patients", R.drawable.ico_search, Color.parseColor("#009384"))); addSlide(AppIntroFragment.newInstance("Monitor Visits", "We help you monitor patient's visits too... Exciting ??? Lets get started", R.drawable.ico_visits, Color.parseColor("#F0A815"))); if(!mOpenMRS.getFirstTime()) { startActivity(new Intent(this, DashboardActivity.class)); finish(); } }

Target:
protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_welcome),"",getString(R.string.intro_welcome_desc),"", R.drawable.openmrs_logo, Color.parseColor("#ffffff"),Color.parseColor("#000000"),Color.parseColor("#000000"))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_register), getString(R.string.intro_register_desc), R.drawable.ico_registry, Color.parseColor("#000000"))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_find), getString(R.string.intro_find_desc), R.drawable.ico_search, Color.parseColor("#009384"))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_monitor), getString(R.string.intro_monitor_desc), R.drawable.ico_visits, Color.parseColor("#F0A815"))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_manage), getString(R.string.intro_manage_desc), R.drawable.ic_provider_big, Color.parseColor("#F26522"))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_location), getString(R.string.intro_location_desc), R.drawable.ic_location_big, Color.parseColor("#009384"))); addSlide(AppIntroFragment.newInstance(getString(R.string.intro_settings), getString(R.string.intro_settings_desc), R.drawable.ic_settings_big, Color.parseColor("#F0A815"))); if(!mOpenMRS.getFirstTime()) { startActivity(new Intent(this, DashboardActivity.class)); finish(); } }
Source:
public void shouldBypassWebsocketRequests() throws Exception{ HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain chain = mock(FilterChain.class); when(request.getHeader("Upgrade")).thenReturn("Websocket"); handler.setRequestingStaticFile(false); vRaptor.doFilter(request, response, chain); assertThat(handler.isDeferProcessingToContainerCalled(), is(false)); }

Target:
public void shouldBypassWebsocketRequests() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain chain = mock(FilterChain.class); when(request.getHeader("Upgrade")).thenReturn("Websocket"); vRaptor.doFilter(request, response, chain); verify(request).getHeader("Upgrade"); verify(chain).doFilter(request, response); verifyNoMoreInteractions(request, response); }
Source:
private void testButton(JoystickButtonManager manager, int i) { try { manager.getifAvailable(i); assertTrue(false); } catch (Exception e) { } }

Target:
private void testButton(JoystickButtonManager manager, int i) { try { manager.getifAvailable(i); fail(); } catch (Exception e) { } }
Source:
protected SortedProperties createUnsafeMapping() throws ProjectBuildingException, IOException, MojoExecutionException { String path = missingFile.getAbsolutePath().substring( getProject().getBasedir().getAbsolutePath().length() + 1 ); if ( isVerbose() ) { LOG.info( "Use missing file path: ", path ); } SortedProperties unsafeMappings = new SortedProperties( getEncoding() ); for ( Object o : reactorProjects ) { MavenProject p = (MavenProject) o; File file = new File( p.getBasedir(), path ); if ( file.exists() ) { SortedProperties tmp = getHelper().loadUnsafeMapping( licenseMap, file, null, projectDependencies ); unsafeMappings.putAll( tmp ); } SortedSet<MavenProject> unsafe = getHelper().getProjectsWithNoLicense( licenseMap ); if ( CollectionUtils.isEmpty( unsafe ) ) { break; } } return unsafeMappings; }

Target:
protected SortedProperties createUnsafeMapping() throws ProjectBuildingException, IOException, MojoExecutionException { String path = missingFile.getAbsolutePath().substring( getProject().getBasedir().getAbsolutePath().length() + 1 ); if ( isVerbose() ) { LOG.info( "Use missing file path: {}", path ); } SortedProperties unsafeMappings = new SortedProperties( getEncoding() ); for ( Object o : reactorProjects ) { MavenProject p = (MavenProject) o; File file = new File( p.getBasedir(), path ); if ( file.exists() ) { SortedProperties tmp = getHelper().loadUnsafeMapping( licenseMap, file, null, projectDependencies ); unsafeMappings.putAll( tmp ); } SortedSet<MavenProject> unsafe = getHelper().getProjectsWithNoLicense( licenseMap ); if ( CollectionUtils.isEmpty( unsafe ) ) { break; } } return unsafeMappings; }
Source:
public void close(long timeoutMS) { try { if (timeoutMS <= 0) { eventHubClient.closeSync(); } else { CompletableFuture<Void> future = eventHubClient.close(); future.get(timeoutMS, TimeUnit.MILLISECONDS); } } catch (Exception e) { LOG.error("Closing the event hub client failed ", e); } }

Target:
public void close(long timeoutMS) { try { if (timeoutMS == EventHubClientManager.BLOCK_UNTIL_CLOSE) { eventHubClient.closeSync(); } else { CompletableFuture<Void> future = eventHubClient.close(); future.get(timeoutMS, TimeUnit.MILLISECONDS); } } catch (Exception e) { LOG.error("Closing the EventHub client failed", e); } }
Source:
protected String validateConsistentTychoVersion(List<MavenProject> projects) throws MavenExecutionException { Map<String, Set<MavenProject>> versionToProjectsMap = new HashMap<String, Set<MavenProject>>(); for (MavenProject project : projects) { for (Plugin plugin : project.getBuild().getPlugins()) { if (TYCHO_GROUPID.equals(plugin.getGroupId()) && TYCHO_PLUGIN_IDS.contains(plugin.getArtifactId())) { String version = plugin.getVersion(); if (version == null) { continue; } log.debug(TYCHO_GROUPID + ":" + plugin.getArtifactId() + ":" + version + " configured in " + project); Set<MavenProject> projectSet = versionToProjectsMap.get(version); if (projectSet == null) { projectSet = new LinkedHashSet<MavenProject>(); versionToProjectsMap.put(version, projectSet); } projectSet.add(project); } } } if (versionToProjectsMap.size() > 1) { List<String> versions = new ArrayList<String>(versionToProjectsMap.keySet()); Collections.sort(versions); log.error("Several versions of tycho plugins are configured " + versions + ":"); for (String version : versions) { log.error(version + ":"); for (MavenProject project : versionToProjectsMap.get(version)) { log.error("\t" + project.toString()); } } throw new MavenExecutionException("All tycho plugins configured in one reactor must use the same version", projects.get(0).getFile()); } if (versionToProjectsMap.size() == 1) { return versionToProjectsMap.keySet().iterator().next(); } return UNKNOWN_VERSION; }

Target:
protected void validateConsistentTychoVersion(List<MavenProject> projects) throws MavenExecutionException { Map<String, Set<MavenProject>> versionToProjectsMap = new HashMap<String, Set<MavenProject>>(); for (MavenProject project : projects) { for (Plugin plugin : project.getBuild().getPlugins()) { if (TYCHO_GROUPID.equals(plugin.getGroupId()) && TYCHO_PLUGIN_IDS.contains(plugin.getArtifactId())) { String version = plugin.getVersion(); if (version == null) { continue; } log.debug(TYCHO_GROUPID + ":" + plugin.getArtifactId() + ":" + version + " configured in " + project); Set<MavenProject> projectSet = versionToProjectsMap.get(version); if (projectSet == null) { projectSet = new LinkedHashSet<MavenProject>(); versionToProjectsMap.put(version, projectSet); } projectSet.add(project); } } } if (versionToProjectsMap.size() > 1) { List<String> versions = new ArrayList<String>(versionToProjectsMap.keySet()); Collections.sort(versions); log.error("Several versions of tycho plugins are configured " + versions + ":"); for (String version : versions) { log.error(version + ":"); for (MavenProject project : versionToProjectsMap.get(version)) { log.error("\t" + project.toString()); } } throw new MavenExecutionException("All tycho plugins configured in one reactor must use the same version", projects.get(0).getFile()); } }
Source:
protected PoolTaskRest action(Context context, HttpServletRequest request, Integer id) throws SQLException, IOException, AuthorizeException { PoolTask task = null; try { task = poolTaskService.find(context, id); XmlWorkflowServiceFactory factory = (XmlWorkflowServiceFactory) XmlWorkflowServiceFactory.getInstance(); Workflow workflow = factory.getWorkflowFactory().getWorkflow(task.getWorkflowItem().getCollection()); Step step = workflow.getStep(task.getStepID()); WorkflowActionConfig currentActionConfig = step.getActionConfig(task.getActionID()); workflowService .doState(context, context.getCurrentUser(), request, task.getWorkflowItem().getID(), workflow, currentActionConfig); context.addEvent(new Event(Event.MODIFY, Constants.ITEM, task.getWorkflowItem().getItem().getID(), null, itemService.getIdentifiers(context, task.getWorkflowItem().getItem()))); } catch (WorkflowConfigurationException | MessagingException | WorkflowException e) { throw new RuntimeException(e.getMessage(), e); } return null; }

Target:
protected PoolTaskRest action(Context context, HttpServletRequest request, Integer id) throws SQLException, IOException { PoolTask task = null; try { task = poolTaskService.find(context, id); XmlWorkflowServiceFactory factory = (XmlWorkflowServiceFactory) XmlWorkflowServiceFactory.getInstance(); Workflow workflow = factory.getWorkflowFactory().getWorkflow(task.getWorkflowItem().getCollection()); Step step = workflow.getStep(task.getStepID()); WorkflowActionConfig currentActionConfig = step.getActionConfig(task.getActionID()); workflowService .doState(context, context.getCurrentUser(), request, task.getWorkflowItem().getID(), workflow, currentActionConfig); } catch (AuthorizeException e) { throw new RESTAuthorizationException(e); } catch (WorkflowConfigurationException | MessagingException | WorkflowException e) { throw new UnprocessableEntityException(e.getMessage(), e); } return null; }
Source:
public ListenableFuture<?> execute(TruncateTable statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters) { Session session = stateMachine.getSession(); QualifiedObjectName tableName = createQualifiedObjectName(session, statement, statement.getTableName()); Optional<TableHandle> tableHandle = metadata.getTableHandle(session, tableName); if (!tableHandle.isPresent()) { throw new SemanticException(MISSING_TABLE, statement, "Table '%s' does not exist", tableName); } accessControl.checkCanDropTable(session.getRequiredTransactionId(), session.getIdentity(), tableName); metadata.truncateTable(session, tableHandle.get()); return immediateFuture(null); }

Target:
public ListenableFuture<?> execute(TruncateTable statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters) { Session session = stateMachine.getSession(); QualifiedObjectName tableName = createQualifiedObjectName(session, statement, statement.getTableName()); Optional<TableHandle> tableHandle = metadata.getTableHandle(session, tableName); if (!tableHandle.isPresent()) { throw new SemanticException(MISSING_TABLE, statement, "Table '%s' does not exist", tableName); } accessControl.checkCanTruncateTable(session.getRequiredTransactionId(), session.getIdentity(), tableName); metadata.truncateTable(session, tableHandle.get()); return immediateFuture(null); }
Source:
public void testRemoveProject() throws Exception { String baseUrl = "<LINK_0>"; StringBuilder xmlContent = new StringBuilder(); Set<String> results = new HashSet<>(); xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<manifest>") .append("<remote name=\"remote1\" fetch=\".\" />") .append("<default revision=\"master\" remote=\"remote1\" />") .append("<project path=\"foo\" name=\"foo\" />") .append("<project path=\"bar\" name=\"bar\" />") .append("<remove-project name=\"foo\" />") .append("<project path=\"foo\" name=\"baz\" />") .append("</manifest>"); ManifestParser parser = new ManifestParser(null, null, "master", baseUrl, null, null); parser.read(new ByteArrayInputStream( xmlContent.toString().getBytes(CHARSET))); results.clear(); results.add("bar"); results.add("baz"); for (RepoProject proj : parser.getProjects()) { assertTrue("Unexpected project is included: " + proj.getName(), results.contains(proj.getName())); results.remove(proj.getName()); } assertTrue( "Expected projects are not included", results.isEmpty()); }

Target:
public void testRemoveProject() throws Exception { StringBuilder xmlContent = new StringBuilder(); xmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<manifest>") .append("<remote name=\"remote1\" fetch=\".\" />") .append("<default revision=\"master\" remote=\"remote1\" />") .append("<project path=\"foo\" name=\"foo\" />") .append("<project path=\"bar\" name=\"bar\" />") .append("<remove-project name=\"foo\" />") .append("<project path=\"foo\" name=\"baz\" />") .append("</manifest>"); ManifestParser parser = new ManifestParser(null, null, "master", "<LINK_0>", null, null); parser.read(new ByteArrayInputStream( xmlContent.toString().getBytes(CHARSET))); Set<String> results = new HashSet<>(); results.add("bar"); results.add("baz"); for (RepoProject proj : parser.getProjects()) { assertTrue("Unexpected project is included: " + proj.getName(), results.contains(proj.getName())); results.remove(proj.getName()); } assertTrue( "Expected projects are not included", results.isEmpty()); }
Source:
public static String path2uid(String path, String date) { return path.replace(File.separatorChar, '\u0000') + "\u0000" + date; }

Target:
public static String path2uid(String path, String date) { return path.replace('/', '\u0000') + "\u0000" + date; }
Source:
protected void validate(GetPresignedObjectUrlArgs args) { super.validate(args); validateMethod(args.method); validateExpiry(args.expiry); }

Target:
protected void validate(GetPresignedObjectUrlArgs args) { super.validate(args); validateMethod(args.method); }
Source:
private int computeHashCode() { int hash = getContig().hashCode(); hash = 31 * hash + getSource().hashCode(); hash = 31 * hash + getType().hashCode(); hash = 31 * hash + getStart(); hash = 31 * hash + getEnd(); hash = 31 * hash + Double.hashCode(getScore()); hash = 31 * hash + getPhase(); hash = 31 * hash + getStrand().hashCode(); hash = 31 * hash + getAttributes().hashCode(); if (getId() != null) { hash = 31 * hash + getId().hashCode(); } if (getName() != null) { hash = 31 * hash + getName().hashCode(); } for (final String alias : aliases) { hash = 31 * hash + alias.hashCode(); } return hash; }

Target:
private int computeHashCode() { int hash = getContig().hashCode(); hash = 31 * hash + getSource().hashCode(); hash = 31 * hash + getType().hashCode(); hash = 31 * hash + getStart(); hash = 31 * hash + getEnd(); hash = 31 * hash + Double.hashCode(getScore()); hash = 31 * hash + getPhase(); hash = 31 * hash + getStrand().hashCode(); hash = 31 * hash + getAttributes().hashCode(); if (getId() != null) { hash = 31 * hash + getId().hashCode(); } if (getName() != null) { hash = 31 * hash + getName().hashCode(); } hash = 31 * hash + aliases.hashCode(); return hash; }
Source:
public void before() { if (schema instanceof SessionKeySchema) { windows[0] = new SessionWindow(10L, 10L); windows[1] = new SessionWindow(500L, 1000L); windows[2] = new SessionWindow(1_000L, 1_500L); windows[3] = new SessionWindow(30_000L, 60_000L); nextSegmentWindow = new SessionWindow(segmentInterval + retention, segmentInterval + retention); } if (schema instanceof WindowKeySchema) { windows[0] = timeWindowForSize(10L, windowSizeForTimeWindow); windows[1] = timeWindowForSize(500L, windowSizeForTimeWindow); windows[2] = timeWindowForSize(1_000L, windowSizeForTimeWindow); windows[3] = timeWindowForSize(60_000L, windowSizeForTimeWindow); nextSegmentWindow = timeWindowForSize(segmentInterval + retention, windowSizeForTimeWindow); } bytesStore = getBytesStore(); stateDir = TestUtils.tempDirectory(); final StreamsMetricsImpl streamsMetrics = niceMock(StreamsMetricsImpl.class); replay(streamsMetrics); context = new InternalMockProcessorContext( stateDir, Serdes.String(), Serdes.Long(), new NoOpRecordCollector(), new ThreadCache(new LogContext("testCache "), 0, streamsMetrics ) ); bytesStore.init(context, bytesStore); }

Target:
public void before() { if (schema instanceof SessionKeySchema) { windows[0] = new SessionWindow(10L, 10L); windows[1] = new SessionWindow(500L, 1000L); windows[2] = new SessionWindow(1_000L, 1_500L); windows[3] = new SessionWindow(30_000L, 60_000L); nextSegmentWindow = new SessionWindow(segmentInterval + retention, segmentInterval + retention); } if (schema instanceof WindowKeySchema) { windows[0] = timeWindowForSize(10L, windowSizeForTimeWindow); windows[1] = timeWindowForSize(500L, windowSizeForTimeWindow); windows[2] = timeWindowForSize(1_000L, windowSizeForTimeWindow); windows[3] = timeWindowForSize(60_000L, windowSizeForTimeWindow); nextSegmentWindow = timeWindowForSize(segmentInterval + retention, windowSizeForTimeWindow); } bytesStore = getBytesStore(); stateDir = TestUtils.tempDirectory(); context = new InternalMockProcessorContext( stateDir, Serdes.String(), Serdes.Long(), new NoOpRecordCollector(), new ThreadCache( new LogContext("testCache "), 0, new StreamsMetricsImpl(new Metrics(), "test", StreamsConfig.METRICS_LATEST) ) ); bytesStore.init(context, bytesStore); }