auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void incrementProgressBy(final int increment) { if (isShowing()) { dialog.incrementProgressBy(increment); } this.progress += increment; }

Target:
public void incrementProgressBy(final int increment) { setProgress(progress + increment); }
Source:
public void setIdleStateRetentionTime(Time minTime, Time maxTime) { if (maxTime.toMilliseconds() - minTime.toMilliseconds() < 300000 && !(maxTime.toMilliseconds() == 0 && minTime.toMilliseconds() == 0)) { throw new IllegalArgumentException( "Difference between minTime: " + minTime.toString() + " and maxTime: " + maxTime.toString() + " should be at least 5 minutes."); } minIdleStateRetentionTime = minTime.toMilliseconds(); maxIdleStateRetentionTime = maxTime.toMilliseconds(); setIdleStateRetentionDuration(Duration.ofMillis(minIdleStateRetentionTime)); }

Target:
public void setIdleStateRetentionTime(Time minTime, Time maxTime) { if (maxTime.toMilliseconds() - minTime.toMilliseconds() < 300000 && !(maxTime.toMilliseconds() == 0 && minTime.toMilliseconds() == 0)) { throw new IllegalArgumentException( "Difference between minTime: " + minTime.toString() + " and maxTime: " + maxTime.toString() + " should be at least 5 minutes."); } setIdleStateRetention(Duration.ofMillis(minTime.toMilliseconds())); }
Source:
protected int checkAndGetUserInputQueryLimit( final Object userInputQueryLimit, final int reportQueryLimit ) { int systemQueryLimit = 0; final IPluginManager pm = PentahoSystem.get( IPluginManager.class ); if ( pm != null ) { systemQueryLimit = NumberUtils.toInt( (String) pm.getPluginSetting( "reporting", "settings/query-limit", "0" ), 0 ); } final int userQueryLimit = NumberUtils.toInt( (String) userInputQueryLimit, -1 ); if ( userQueryLimit > 0 ) { return systemQueryLimit > 0 ? Math.min( userQueryLimit, systemQueryLimit ) : userQueryLimit; } else { if ( systemQueryLimit > 0 ) { return reportQueryLimit > 0 ? Math.min( reportQueryLimit, systemQueryLimit ) : systemQueryLimit; } return -1; } }

Target:
int checkAndGetUserInputQueryLimit( final Object userInputQueryLimit, final int reportQueryLimit ) { int systemQueryLimit = 0; final IPluginManager pm = PentahoSystem.get( IPluginManager.class ); if ( pm != null ) { systemQueryLimit = NumberUtils.toInt( (String) pm.getPluginSetting( "reporting", "settings/query-limit", "0" ), 0 ); } if ( reportQueryLimit > 0 ) { if ( reportQueryLimit > 0 && systemQueryLimit > 0 ) { return Math.min( reportQueryLimit, systemQueryLimit ); } else { return reportQueryLimit; } } else { final int userLimit = NumberUtils.toInt( (String) userInputQueryLimit, -1 ); if ( userLimit > 0 && systemQueryLimit > 0 ) { return Math.min( userLimit, systemQueryLimit ); } else if ( systemQueryLimit > 0 ) { return systemQueryLimit; } else { return userLimit; } } }
Source:
Mono<Response<Boolean>> existsWithResponse(Context context) { return this.getPropertiesWithResponse(null, context) .map(cp -> (Response<Boolean>) new SimpleResponse<>(cp, true)) .onErrorResume(t -> (t instanceof ShareStorageException && ((ShareStorageException) t).getStatusCode() == 404) || (t instanceof HttpResponseException && ((HttpResponseException) t).getResponse().getStatusCode() == 404), t -> { HttpResponse response = t instanceof ShareStorageException ? ((ShareStorageException) t).getResponse() : ((HttpResponseException) t).getResponse(); return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false)); }); }

Target:
Mono<Response<Boolean>> existsWithResponse(Context context) { return this.getPropertiesWithResponse(null, context) .map(cp -> (Response<Boolean>) new SimpleResponse<>(cp, true)) .onErrorResume(this::checkDoesNotExistStatusCode, t -> { HttpResponse response = t instanceof ShareStorageException ? ((ShareStorageException) t).getResponse() : ((HttpResponseException) t).getResponse(); return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false)); }); }
Source:
public Boolean isImageOnPage(String fileName) { wait.forElementVisible(By.cssSelector(MW_CONTENT_TEXT_IMG)); for (int i = 0; i < 2; i++) { for (WebElement image : imagesNewFiles) { if (image.getAttribute("src").contains(fileName)) { return true; } } try { Thread.sleep(5000); } catch (InterruptedException e) { PageObjectLogging.logInfo("Sleep interrupted"); } driver.navigate().refresh(); } return false; }

Target:
public Boolean isImageOnPage(String fileName) { wait.forElementVisible(mwContentTextImgBy); for (int i = 0; i < 2; i++) { for (WebElement image : imagesNewFiles) { if (image.getAttribute("src").contains(fileName)) { return true; } } try { Thread.sleep(5000); } catch (InterruptedException e) { PageObjectLogging.logInfo("Sleep interrupted"); } driver.navigate().refresh(); } return false; }
Source:
public void technical_error_should_add_error_to_context() { thrown.expect(AnalysisException.class); JavaScriptCheck check = new ExceptionRaisingCheck(new NullPointerException("NPE forcibly raised by check class")); createSensor().analyseFiles(context, ImmutableList.of((TreeVisitor)check), ImmutableList.of(new CompatibleInputFile(inputFile("file.js"))), progressReport); assertThat(context.allAnalysisErrors()).hasSize(1); }

Target:
public void technical_error_should_add_error_to_context() { thrown.expect(AnalysisException.class); JavaScriptCheck check = new ExceptionRaisingCheck(new NullPointerException("NPE forcibly raised by check class")); createSensor().analyseFiles(context, ImmutableList.of((TreeVisitor)check), ImmutableList.of(inputFile("file.js")), progressReport); assertThat(context.allAnalysisErrors()).hasSize(1); }
Source:
public void deleteGallery(int index) { selectGallery(index); wait.forElementVisible(focusedHighlight); if ("CHROME".equalsIgnoreCase(Configuration.getBrowser())) { Actions actions2 = new Actions(driver); actions2.sendKeys(Keys.DELETE).build().perform(); } else { editArea.sendKeys(Keys.DELETE); } }

Target:
public void deleteGallery(int index) { selectGallery(index); wait.forElementVisible(focusedHighlight); if (Browser.CHROME.equalsIgnoreCase(Configuration.getBrowser())) { Actions actions2 = new Actions(driver); actions2.sendKeys(Keys.DELETE).build().perform(); } else { editArea.sendKeys(Keys.DELETE); } }
Source:
public boolean isBasedOn(final MixinDefinitionId mixinId) { for (SClass cls : getSuperclassAndMixins()) { if (cls.isBasedOn(mixinId)) { return true; } } return false; }

Target:
public boolean isBasedOn(final MixinDefinitionId mixinId) { VM.callerNeedsToBeOptimized("Result of isBasedOn should be cached"); for (SClass cls : getSuperclassAndMixins()) { if (cls.isBasedOn(mixinId)) { return true; } } return false; }
Source:
private List<Person> makeDirectors(Element cast) { List<Person> people = new ArrayList<>(); Elements directors = cast.getChildElements("actor"); for (int i = 0; i < directors.size(); i++) { Element director = directors.get(i); people.add(makeDirector(director)); } return people; }

Target:
private List<Person> makeDirectors(Element cast) { List<Person> people = Lists.newArrayList(); Elements directors = cast.getChildElements(ACTOR); for (int i = 0; i < directors.size(); i++) { Element director = directors.get(i); people.add(makeDirector(director)); } return people; }
Source:
public void start(FeaturesRunner runner) { try { RuntimeHarness harness = runner.getFeature(RuntimeFeature.class).getHarness(); storageConfiguration.init(); for (String bundle : storageConfiguration.getExternalBundles()) { harness.deployBundle(bundle); } URL blobContribUrl = storageConfiguration.getBlobManagerContrib(runner); harness.getContext().deploy(new URLStreamRef(blobContribUrl)); URL repoContribUrl = storageConfiguration.getRepositoryContrib(runner); harness.getContext().deploy(new URLStreamRef(repoContribUrl)); } catch (Exception e) { throw new NuxeoException(e); } }

Target:
public void start(FeaturesRunner runner) { try { RuntimeHarness harness = runner.getFeature(RuntimeFeature.class).getHarness(); storageConfiguration.init(); for (String bundle : storageConfiguration.getExternalBundles()) { try { harness.deployBundle(bundle); } catch (Exception e) { throw new NuxeoException(e); } } URL blobContribUrl = storageConfiguration.getBlobManagerContrib(runner); harness.getContext().deploy(new URLStreamRef(blobContribUrl)); URL repoContribUrl = storageConfiguration.getRepositoryContrib(runner); harness.getContext().deploy(new URLStreamRef(repoContribUrl)); } catch (IOException e) { throw new NuxeoException(e); } }
Source:
public void dateFormatFunctionExtension7() throws InterruptedException { log.info("DateFormatFunctionExtensionTestCaseFirstArgumentNul"); SiddhiManager siddhiManager = new SiddhiManager(); String inStreamDefinition = "define stream inputStream (symbol string," + "dateValue string,sourceFormat string,timestampInMilliseconds long,targetFormat string);"; String query = ("@info(name = 'query1') from inputStream select symbol , " + "time:dateFormat(dateValue,targetFormat,sourceFormat) as formattedDate," + "time:dateFormat(timestampInMilliseconds," + "targetFormat) as formattedUnixDate insert into outputStream;"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager .createExecutionPlanRuntime(inStreamDefinition + query); executionPlanRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); eventArrived = true; for(int cnt=0;cnt<inEvents.length;cnt++){ count++; log.info("Event : " + count + ",formattedDate : " + inEvents[cnt].getData(1) + "," + "formattedMillsDate : " + inEvents[cnt].getData(2)); } } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); executionPlanRuntime.start(); inputHandler.send(new Object[] { "IBM",null, "yyyy-MM-dd HH:mm:ss", 1415692424000L, "ss" }); Thread.sleep(100); Assert.assertEquals(1, count); Assert.assertTrue(eventArrived); executionPlanRuntime.shutdown(); }

Target:
public void dateFormatFunctionExtension7() throws InterruptedException { log.info("DateFormatFunctionExtensionTestCaseFirstArgumentNul"); SiddhiManager siddhiManager = new SiddhiManager(); String inStreamDefinition = "define stream inputStream (symbol string," + "dateValue string,sourceFormat string,timestampInMilliseconds long,targetFormat string);"; String query = ("@info(name = 'query1') from inputStream select symbol , " + "time:dateFormat(dateValue,targetFormat,sourceFormat) as formattedDate," + "time:dateFormat(timestampInMilliseconds," + "targetFormat) as formattedUnixDate insert into outputStream;"); ExecutionPlanRuntime executionPlanRuntime = siddhiManager .createExecutionPlanRuntime(inStreamDefinition + query); executionPlanRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); eventArrived = true; for (Event event : inEvents) { count++; if (count == 1) { Assert.assertEquals(null, event.getData(1)); Assert.assertEquals("2014-11-11", event.getData(2)); } if (count == 2) { Assert.assertEquals(null, event.getData(1)); Assert.assertEquals("44", event.getData(2)); } } } }); InputHandler inputHandler = executionPlanRuntime.getInputHandler("inputStream"); executionPlanRuntime.start(); inputHandler.send(new Object[]{"IBM", null, "yyyy-MM-dd HH:mm:ss", 1415692424000L, "yyyy-MM-dd"}); inputHandler.send(new Object[]{"IBM", null, "yyyy-MM-dd HH:mm:ss", 1415692424000L, "ss"}); Thread.sleep(100); Assert.assertEquals(2, count); Assert.assertTrue(eventArrived); executionPlanRuntime.shutdown(); }
Source:
public Boolean call() throws LauncherException, PackingException { SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime); TopologyAPI.Topology topology = Runtime.topology(runtime); String topologyName = Context.topologyName(config); PackingPlan packedPlan = LauncherUtils.getInstance().createPackingPlan(config, runtime); launcher.initialize(config, runtime); Boolean result; result = statemgr.setTopology(trimTopology(topology), topologyName); if (result == null || !result) { throw new LauncherException("Failed to set topology definition", topologyName); } result = statemgr.setPackingPlan(createPackingPlan(packedPlan), topologyName); if (result == null || !result) { statemgr.deleteTopology(topologyName); throw new LauncherException("Failed to set packing plan", topologyName); } ExecutionEnvironment.ExecutionState executionState = createExecutionState(); result = statemgr.setExecutionState(executionState, topologyName); if (result == null || !result) { statemgr.deletePackingPlan(topologyName); statemgr.deleteTopology(topologyName); throw new LauncherException("Failed to set execution state", topologyName); } if (!launcher.launch(packedPlan)) { statemgr.deleteExecutionState(topologyName); statemgr.deletePackingPlan(topologyName); statemgr.deleteTopology(topologyName); throw new LauncherException("Failed to launch topology", topologyName); } return true; }

Target:
public void call() throws LauncherException, PackingException { SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime); TopologyAPI.Topology topology = Runtime.topology(runtime); String topologyName = Context.topologyName(config); PackingPlan packedPlan = LauncherUtils.getInstance().createPackingPlan(config, runtime); launcher.initialize(config, runtime); Boolean result; result = statemgr.setTopology(trimTopology(topology), topologyName); if (result == null || !result) { throw new LauncherException(String.format( "Failed to set topology definition for topology '%s'", topologyName)); } result = statemgr.setPackingPlan(createPackingPlan(packedPlan), topologyName); if (result == null || !result) { statemgr.deleteTopology(topologyName); throw new LauncherException(String.format( "Failed to set packing plan for topology '%s'", topologyName)); } ExecutionEnvironment.ExecutionState executionState = createExecutionState(); result = statemgr.setExecutionState(executionState, topologyName); if (result == null || !result) { statemgr.deletePackingPlan(topologyName); statemgr.deleteTopology(topologyName); throw new LauncherException(String.format( "Failed to set execution state for topology '%s'", topologyName)); } if (!launcher.launch(packedPlan)) { statemgr.deleteExecutionState(topologyName); statemgr.deletePackingPlan(topologyName); statemgr.deleteTopology(topologyName); throw new LauncherException(String.format( "Failed to launch topology '%s'", topologyName)); } }
Source:
public static Map<String, String> getRESTAPIScopesFromConfig(JSONObject scopesConfig, JSONObject roleMappings) { Map<String, String> scopes = new HashMap<String, String>(); JSONArray scopesArray = (JSONArray) scopesConfig.get("Scope"); for (Object scopeObj : scopesArray) { JSONObject scope = (JSONObject) scopeObj; String scopeName = scope.get(APIConstants.REST_API_SCOPE_NAME).toString(); String scopeRoles = scope.get(APIConstants.REST_API_SCOPE_ROLE).toString(); if (roleMappings != null) { if (log.isDebugEnabled()) { log.debug("REST API scope role mappings exist. Hence proceeding to swap original scope roles " + "for mapped scope roles."); } List<String> originalRoles = Arrays.asList(scopeRoles.split("\\s*,\\s*")); List<String> mappedRoles = new ArrayList<String>(); for (String role : originalRoles) { String mappedRole = (String) roleMappings.get(role); if (mappedRole != null) { if (log.isDebugEnabled()) { log.debug(role + " was mapped to " + mappedRole); } mappedRoles.add(mappedRole); } else { mappedRoles.add(role); } } scopeRoles = mappedRoles.toString().replace("[", "").replace("]", "").replace(" ", ""); } scopes.put(scopeName, scopeRoles); } return scopes; }

Target:
public static Map<String, String> getRESTAPIScopesFromConfig(JSONObject scopesConfig, JSONObject roleMappings) { Map<String, String> scopes = new HashMap<String, String>(); JSONArray scopesArray = (JSONArray) scopesConfig.get("Scope"); for (Object scopeObj : scopesArray) { JSONObject scope = (JSONObject) scopeObj; String scopeName = scope.get(APIConstants.REST_API_SCOPE_NAME).toString(); String scopeRoles = scope.get(APIConstants.REST_API_SCOPE_ROLE).toString(); if (roleMappings != null) { if (log.isDebugEnabled()) { log.debug("REST API scope role mappings exist. Hence proceeding to swap original scope roles " + "for mapped scope roles."); } List<String> originalRoles = Arrays.asList(scopeRoles.split("\\s*,\\s*")); List<String> mappedRoles = new ArrayList<String>(); for (String role : originalRoles) { String mappedRole = (String) roleMappings.get(role); if (mappedRole != null) { if (log.isDebugEnabled()) { log.debug(role + " was mapped to " + mappedRole); } mappedRoles.add(mappedRole); } else { mappedRoles.add(role); } } scopeRoles = String.join(",", mappedRoles); } scopes.put(scopeName, scopeRoles); } return scopes; }
Source:
public IntervalList toIntervalList(final boolean includeFiltered) { return fromVcf(this, includeFiltered); }

Target:
public IntervalList toIntervalList(final boolean includeFiltered) { return toIntervalList(this, includeFiltered); }
Source:
public PortableInfoboxObject clickNextImageArrow(int childIndex) { wait.forElementClickable(By.cssSelector(".pi-image:nth-child(" + childIndex + ") .action-next")).click(); return this; }

Target:
public PortableInfoboxObject clickNextImageArrow(int childIndex) { By nextImageArrow = By.cssSelector(".pi-image:nth-child(" + childIndex + ") .action-next"); wait.forElementClickable(nextImageArrow) .click(); return this; }
Source:
public PerformanceResult call() throws Exception { final Ds3ClientHelpers helpers = Ds3ClientHelpers.wrap(getClient()); final int numberOfFiles = Integer.valueOf(this.numberOfFiles); final long sizeOfFiles = Integer.valueOf(this.sizeOfFiles); try { try { final PutBucketRequest request = new PutBucketRequest(bucketName); getClient().putBucket(request); } catch(final FailedRequestException e) { this.doNotDelete = true; if (e.getStatusCode() == 409) { throw new CommandException("Bucket " + bucketName + " already exists. To avoid any conflict please use a non-existent bucket."); } throw new CommandException("Encountered a DS3 Error", e); } final List<Ds3Object> objList = getDs3Objects(numberOfFiles, sizeOfFiles); transfer(helpers, numberOfFiles, sizeOfFiles, objList, true); transfer(helpers, numberOfFiles, sizeOfFiles, objList, false); } finally { if (!doNotDelete) deleteAllContents(getClient(), this.bucketName); } return new PerformanceResult("Done!"); }

Target:
public PerformanceResult call() throws Exception { final Ds3ClientHelpers helpers = Ds3ClientHelpers.wrap(getClient()); final int numberOfFiles = Integer.valueOf(this.numberOfFiles); final long sizeOfFiles = Integer.valueOf(this.sizeOfFiles); try { try { final PutBucketRequest request = new PutBucketRequest(bucketName); getClient().putBucket(request); } catch(final FailedRequestException e) { this.doNotDelete = true; if (e.getStatusCode() == 409) { throw new CommandException("Bucket " + bucketName + " already exists. To avoid any conflicts please use a non-existent bucket."); } throw new CommandException("Encountered a DS3 Error", e); } final List<Ds3Object> objList = getDs3Objects(numberOfFiles, sizeOfFiles); transfer(helpers, numberOfFiles, sizeOfFiles, objList, true); transfer(helpers, numberOfFiles, sizeOfFiles, objList, false); } finally { if (!doNotDelete) deleteAllContents(getClient(), this.bucketName); } return new PerformanceResult("Done!"); }
Source:
public boolean nextKeyValue() throws IOException, InterruptedException { while (true) { if (pos_ > end_) { reader_.markNoMoreNewBlocks(); } ByteString bs = reader_.readNextProtoByteString(); if(bs == null) { return false; } errorTracker.incRecords(); M decoded = null; try { decoded = deserializer_.fromBytes(bs.toByteArray()); } catch (Throwable e) { errorTracker.incErrors(e); HadoopCompat.incrementCounter(recordErrorsCounter, 1); continue; } if (decoded != null) { if (updatePosition) { pos_ = getLzoFilePos(); updatePosition = false; } key_.set(pos_); value_.set(decoded); pos_ = getLzoFilePos(); HadoopCompat.incrementCounter(recordsReadCounter, 1); return true; } else { HadoopCompat.incrementCounter(recordsSkippedCounter, 1); } } }

Target:
public boolean nextKeyValue() throws IOException, InterruptedException { while (true) { if (pos_ > end_) { reader_.markNoMoreNewBlocks(); } byte[] byteArray = reader_.readNextProtoBytes(); if(byteArray == null) { return false; } errorTracker.incRecords(); M decoded = null; try { decoded = deserializer_.fromBytes(byteArray); } catch (DecodeException e) { errorTracker.incErrors(e); HadoopCompat.incrementCounter(recordErrorsCounter, 1); continue; } if (updatePosition) { pos_ = getLzoFilePos(); updatePosition = false; } if (decoded != null) { key_.set(pos_); value_.set(decoded); pos_ = getLzoFilePos(); HadoopCompat.incrementCounter(recordsReadCounter, 1); return true; } else { HadoopCompat.incrementCounter(recordsSkippedCounter, 1); } } }
Source:
public void startWatch(final IProject project) { ConcurrentMap<String, IWatcher> kindMap = new ConcurrentHashMap<>(); if(watches.putIfAbsent(project, kindMap) == null){ final Connection conn = ConnectionsRegistryUtil.getConnectionFor(project); for (String kind: KINDS) { WatchListener listener = new WatchListener(project, conn, kind, 0, 0); startWatch(project, 0, 0, listener); } } }

Target:
public void startWatch(final IProject project) { ConcurrentMap<String, IWatcher> kindMap = new ConcurrentHashMap<>(); if(watches.putIfAbsent(project, kindMap) == null){ final Connection conn = ConnectionsRegistryUtil.getConnectionFor(project); if(conn == null) return; for (String kind: KINDS) { WatchListener listener = new WatchListener(project, conn, kind, 0, 0); startWatch(project, 0, 0, listener); } } }
Source:
private void forwardEvent(Event event) { if (forwardNodes && event.getNodeid() != null && event.getNodeid() != 0) { maybeUpdateNode(event.getNodeid()); } boolean result = true; if (filterEvents) { ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression(eventFilter); try { result = exp.getValue(event, Boolean.class); } catch (Exception e) { LOG.error(" Event filter : didn't evaluate any result on Event {}", eventFilter, event.toStringSimple(), e); } } if (result) { sendRecord(() -> { final OpennmsModelProtos.Event mappedEvent = protobufMapper.toEvent(event).build(); LOG.debug("Sending event with UEI: {}", mappedEvent.getUei()); return new ProducerRecord<>(eventTopic, mappedEvent.getUei(), mappedEvent.toByteArray()); }); } else { LOG.debug("Event not forwarded based on filter ", event.toStringSimple(), eventFilter); return; } }

Target:
private void forwardEvent(Event event) { if (forwardNodes && event.getNodeid() != null && event.getNodeid() != 0) { maybeUpdateNode(event.getNodeid()); } boolean shouldForwardEvent = true; if (filterEvents) { ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression(eventFilter); try { shouldForwardEvent = exp.getValue(event, Boolean.class); } catch (Exception e) { LOG.error(" Event filter : didn't evaluate any result on Event {}", eventFilter, event.toStringSimple(), e); } } if (shouldForwardEvent) { sendRecord(() -> { final OpennmsModelProtos.Event mappedEvent = protobufMapper.toEvent(event).build(); LOG.debug("Sending event with UEI: {}", mappedEvent.getUei()); return new ProducerRecord<>(eventTopic, mappedEvent.getUei(), mappedEvent.toByteArray()); }); } else { if (LOG.isDebugEnabled()) { LOG.debug("Event not forwarded based on filter ", event.toStringSimple(), eventFilter); } return; } }
Source:
protected boolean isEapProfile() { String profile = ServerProfileModel.getProfile(getServer()); if( "openshift3.eap".equals(profile)) { return false; } return true; }

Target:
protected boolean isEapProfile() { String profile = ServerProfileModel.getProfile(getServer()); if( "openshift3.eap".equals(profile)) { return true; } return false; }
Source:
public void convertsNegativeBigIntegersCorrectly() { int iterations = 100_000; int bitLength = LockServiceImpl.RANDOM_BIT_COUNT; for (int i = 0; i < iterations; i++) { BigInteger randomBigInteger = new BigInteger(bitLength, RANDOM).multiply(new BigInteger("-1")); LockRefreshToken lockRefreshToken = new LockRefreshToken(randomBigInteger, Long.MIN_VALUE); assertConversionFromAndToLegacyPreservesId(lockRefreshToken); } }

Target:
public void convertsNegativeBigIntegersCorrectly() { int iterations = 100_000; int bitLength = LockServiceImpl.RANDOM_BIT_COUNT; for (int i = 0; i < iterations; i++) { BigInteger randomBigInteger = new BigInteger(bitLength, RANDOM).negate(); LockRefreshToken lockRefreshToken = new LockRefreshToken(randomBigInteger, Long.MIN_VALUE); assertConversionFromAndToLegacyPreservesId(lockRefreshToken); } }
Source:
public Object processInvocation(final InterceptorContext context) throws Exception { final StartupCountdown.Frame frame = countdown.enter(); try { Object proceed = context.proceed(); countdown.countDown(); return proceed; } catch (Exception e) { throw e; } finally { StartupCountdown.restore(frame); } }

Target:
public Object processInvocation(final InterceptorContext context) throws Exception { final StartupCountdown.Frame frame = countdown.enter(); try { Object proceed = context.proceed(); countdown.countDown(); return proceed; } finally { StartupCountdown.restore(frame); } }
Source:
private SystemTable checkAndGetTable(ConnectorSession session, ConnectorTableHandle tableHandle) { SystemTableHandle systemTableHandle = (SystemTableHandle) tableHandle; Optional<SystemTable> table = tables.getSystemTable(session, systemTableHandle.getSchemaTableName()); checkArgument(table.isPresent()); return table.get(); }

Target:
private SystemTable checkAndGetTable(ConnectorSession session, ConnectorTableHandle tableHandle) { SystemTableHandle systemTableHandle = (SystemTableHandle) tableHandle; return tables.getSystemTable(session, systemTableHandle.getSchemaTableName()) .orElseThrow(() -> new PrestoException(NOT_FOUND, format("Table %s not found", systemTableHandle.getSchemaTableName()))); }
Source:
public JsonAdapter<?> create(Type type, Set<? extends Annotation> annotations, Moshi moshi) { if (Types.getRawType(type) != baseType || !annotations.isEmpty()) { return null; } int size = labelToType.size(); Map<String, JsonAdapter<Object>> labelToAdapter = new LinkedHashMap<>(size); Map<Type, String> typeToLabel = new LinkedHashMap<>(size); for (Map.Entry<String, Type> entry : labelToType.entrySet()) { String label = entry.getKey(); Type typeValue = entry.getValue(); typeToLabel.put(typeValue, label); labelToAdapter.put(label, moshi.adapter(typeValue)); } JsonAdapter<Object> objectJsonAdapter; if (baseType == Object.class) { objectJsonAdapter = moshi.nextAdapter(this, Object.class, Util.NO_ANNOTATIONS); } else { objectJsonAdapter = moshi.adapter(Object.class); } return new RuntimeJsonAdapter(labelKey, labelToAdapter, typeToLabel, objectJsonAdapter) .nullSafe(); }

Target:
public JsonAdapter<?> create(Type type, Set<? extends Annotation> annotations, Moshi moshi) { if (Types.getRawType(type) != baseType || !annotations.isEmpty()) { return null; } int size = labelToType.size(); Map<String, JsonAdapter<Object>> labelToAdapter = new LinkedHashMap<>(size); Map<Type, String> typeToLabel = new LinkedHashMap<>(size); for (Map.Entry<String, Type> entry : labelToType.entrySet()) { String label = entry.getKey(); Type typeValue = entry.getValue(); typeToLabel.put(typeValue, label); labelToAdapter.put(label, moshi.adapter(typeValue)); } JsonAdapter<Object> objectJsonAdapter = moshi.adapter(Object.class); return new RuntimeJsonAdapter(labelKey, labelToAdapter, typeToLabel, objectJsonAdapter).nullSafe(); }
Source:
public Map<String, Collection<SearchResult>> search(SearchContext context, String query, Collection<String> sites, Collection<String> types, int offset, int limit, String sort, String order) { String fuzzySyntax = getFuzzySyntax(); query = replaceSpecialCharacters(query); HashMap<String, ArrayList<String>> terms = parse(query); query = repeat("\"%s\"", terms.get("quoted"), " ") + " " + repeat("%s" + fuzzySyntax, terms.get("single"), " "); Map<String, Collection<SearchResult>> results = new HashMap<String, Collection<SearchResult>>(); if(query==null || StringUtils.isEmpty(query.trim())) return results; if(null==types || types.isEmpty()) return results; List<String> enabledTypes = UnifiedSearchService.getEnabledSearchTypes(); for(SearchServiceConnector connector:this.getConnectors()){ if(!enabledTypes.contains(connector.getSearchType())) continue; if(!types.contains("all") && !types.contains(connector.getSearchType())) continue; LOG.debug("\n[UNIFIED SEARCH]: connector = " + connector.getClass().getSimpleName()); try { results.put(connector.getSearchType(), connector.search(context, query, sites, offset, limit, sort, order)); } catch (Exception e) { LOG.error(e.getMessage(), e); continue; } } return results; }

Target:
public Map<String, Collection<SearchResult>> search(SearchContext context, String query, Collection<String> sites, Collection<String> types, int offset, int limit, String sort, String order) { String fuzzySyntax = getFuzzySyntax(); query = replaceSpecialCharacters(query); HashMap<String, ArrayList<String>> terms = parse(query); query = repeat("\"%s\"", terms.get("quoted"), " ") + " " + repeat("%s" + fuzzySyntax, terms.get("single"), " "); Map<String, Collection<SearchResult>> results = new HashMap<String, Collection<SearchResult>>(); if(StringUtils.isBlank(query)) return results; if(null==types || types.isEmpty()) return results; List<String> enabledTypes = UnifiedSearchService.getEnabledSearchTypes(); for(SearchServiceConnector connector:this.getConnectors()){ if(!enabledTypes.contains(connector.getSearchType())) continue; if(!types.contains("all") && !types.contains(connector.getSearchType())) continue; LOG.debug("\n[UNIFIED SEARCH]: connector = " + connector.getClass().getSimpleName()); try { results.put(connector.getSearchType(), connector.search(context, query, sites, offset, limit, sort, order)); } catch (Exception e) { LOG.error(e.getMessage(), e); continue; } } return results; }
Source:
BufferAndBacklog pollBuffer() { synchronized (buffers) { Buffer buffer = null; if (buffers.isEmpty()) { flushRequested = false; } while (!buffers.isEmpty()) { BufferConsumer bufferConsumer = buffers.peek(); buffer = bufferConsumer.build(); checkState(bufferConsumer.isFinished() || buffers.size() == 1, "When there are multiple buffers, an unfinished bufferConsumer can not be at the head of the buffers queue."); if (buffers.size() == 1) { flushRequested = false; } if (bufferConsumer.isFinished()) { buffers.pop().close(); decreaseBuffersInBacklogUnsafe(bufferConsumer.isBuffer()); } if (buffer.readableBytes() > 0) { break; } buffer.recycleBuffer(); buffer = null; if (!bufferConsumer.isFinished()) { break; } } if (buffer == null) { dataAvailableNotified = false; return null; } boolean isAvailable = isAvailableUnsafe(); dataAvailableNotified = isAvailable; updateStatistics(buffer); return new BufferAndBacklog( buffer, isAvailable, getBuffersInBacklog(), nextBufferIsEventUnsafe()); } }

Target:
BufferAndBacklog pollBuffer() { synchronized (buffers) { if (isBlockedByCheckpoint) { return null; } Buffer buffer = null; if (buffers.isEmpty()) { flushRequested = false; } while (!buffers.isEmpty()) { BufferConsumer bufferConsumer = buffers.peek(); buffer = bufferConsumer.build(); checkState(bufferConsumer.isFinished() || buffers.size() == 1, "When there are multiple buffers, an unfinished bufferConsumer can not be at the head of the buffers queue."); if (buffers.size() == 1) { flushRequested = false; } if (bufferConsumer.isFinished()) { buffers.pop().close(); decreaseBuffersInBacklogUnsafe(bufferConsumer.isBuffer()); } if (buffer.readableBytes() > 0) { break; } buffer.recycleBuffer(); buffer = null; if (!bufferConsumer.isFinished()) { break; } } if (buffer == null) { dataAvailableNotified = false; return null; } if (buffer.getDataType().isBlockingUpstream()) { isBlockedByCheckpoint = true; } boolean isAvailable = isDataAvailableUnsafe(); dataAvailableNotified = isAvailable; updateStatistics(buffer); return new BufferAndBacklog( buffer, isAvailable, getBuffersInBacklog(), isEventAvailableUnsafe()); } }
Source:
private Command buildDeleteDiagramElement() { Command cmd = UnexecutableCommand.INSTANCE; if (permissionAuthority.canEditInstance(diagramElement) && permissionAuthority.canEditInstance(diagramElement.eContainer())) { boolean semanticElementCanBeDeleted = true; final Set<EObject> allSemanticElements = getSemanticElementsToDestroy(diagramElement); for (final EObject semantic : allSemanticElements) { final EObject container = semantic.eContainer(); if (!permissionAuthority.canDeleteInstance(semantic) || (container != null && !permissionAuthority.canEditInstance(container))) { semanticElementCanBeDeleted = false; } } if (semanticElementCanBeDeleted) { final DCommand result = createEnclosingCommand(); final DDiagram foundDiagram = SiriusUtil.findDiagram(diagramElement); setTool(); if (tool != null) { addDeleteDiagramElementFromTool(result); EObject rootContainer = null; final boolean automaticRefresh = Platform.getPreferencesService().getBoolean(SiriusPlugin.ID, SiriusPreferencesKeys.PREF_AUTO_REFRESH.name(), false, null); if (automaticRefresh) { addRefreshTask(diagramElement, result, tool); rootContainer = EcoreUtil.getRootContainer(diagramElement); } else { EObjectQuery eObjectQuery = new EObjectQuery(diagramElement); DRepresentation dRepresentation = eObjectQuery.getRepresentation().get(); rootContainer = dRepresentation; } cmd = new NoNullResourceCommand(result, diagramElement); } else { cmd = buildDeleteDiagramElementCommandWithoutTool(result, foundDiagram); } } } return cmd; }

Target:
private Command buildDeleteDiagramElement() { Command cmd = UnexecutableCommand.INSTANCE; if (permissionAuthority.canEditInstance(diagramElement) && permissionAuthority.canEditInstance(diagramElement.eContainer())) { boolean semanticElementCanBeDeleted = true; final Set<EObject> allSemanticElements = getSemanticElementsToDestroy(diagramElement); for (final EObject semantic : allSemanticElements) { final EObject container = semantic.eContainer(); if (!permissionAuthority.canDeleteInstance(semantic) || (container != null && !permissionAuthority.canEditInstance(container))) { semanticElementCanBeDeleted = false; } } if (semanticElementCanBeDeleted) { final DCommand result = createEnclosingCommand(); final DDiagram foundDiagram = SiriusUtil.findDiagram(diagramElement); setTool(); if (tool != null) { addDeleteDiagramElementFromTool(result); addRefreshTask(diagramElement, result, tool); cmd = new NoNullResourceCommand(result, diagramElement); } else { cmd = buildDeleteDiagramElementCommandWithoutTool(result, foundDiagram); } } } return cmd; }
Source:
public Object getEntityInstance() { for ( Object obj : projection ) { if ( clazz.isInstance( obj ) ) { return obj; } } return null; }

Target:
public Object getEntityInstance() { return entityInstance; }
Source:
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { Locale userLocale = (Locale) request.getAttribute(LocaleFilter.LOCALE); if (userLocale == null) { log.warn("Detected Locale is null, setting to default: " + LocaleFilter.DEFAULT_LOCALE); userLocale = LocaleFilter.DEFAULT_LOCALE; } List<BrandingTheme> brandingThemes = brandingManager.getBrandingThemes(); request.setAttribute(THEMES_KEY, brandingThemes); ResourceBundle bundle = ResourceBundle.getBundle("BrandingBundle", userLocale, BrandingResourceBundle.getBrandingControl(BLANK)); Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle, userLocale)); chain.doFilter(request, response); }

Target:
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { Locale userLocale = (Locale) request.getAttribute(LocaleFilter.LOCALE); if (userLocale == null) { log.warn("Detected Locale is null, setting to default: " + LocaleFilter.DEFAULT_LOCALE); userLocale = LocaleFilter.DEFAULT_LOCALE; } List<BrandingTheme> brandingThemes = brandingManager.getBrandingThemes(); request.setAttribute(THEMES_KEY, brandingThemes); ResourceBundle bundle = ResourceBundle.getBundle(BRANDING_BASE_NAME, userLocale, BrandingResourceBundle.getBrandingControl(BLANK)); Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle, userLocale)); chain.doFilter(request, response); }
Source:
private boolean identifiedByName(Class<?> type) { return Map.class.equals(type) || byte[].class.equals(type); }

Target:
private boolean identifiedByName(Class<?> type) { return byte[].class.equals(type); }
Source:
public boolean addVertex(final V v) { if (adjacent.put(v, new HashSet<>()) == null) { inDegrees.put(v, 0); rootVertices.add(v); return true; } else { LOG.log(Level.WARNING, "The vertex {0} already exists", new Object[]{v}); return false; } }

Target:
public boolean addVertex(final V v) { if (!adjacent.containsKey(v)) { adjacent.put(v, new HashSet<>()); inDegrees.put(v, 0); rootVertices.add(v); return true; } else { LOG.log(Level.WARNING, "The vertex {0} already exists", new Object[]{v}); return false; } }
Source:
private SimpleTree getTree() { JComponent component = myToolWindow.getContentManager().getComponent(); return myRobot.finder().findByType(component, SimpleTree.class); }

Target:
private JTree getTree() { JComponent component = myToolWindow.getContentManager().getComponent(); return myRobot.finder().findByType(component, JTree.class); }
Source:
private void cleanUnusedFilesFromCache() { try (Stream<Path> pathElements = Files.walk(this.cacheDirectory)) { pathElements .filter(Files::isRegularFile) .forEach(this::deleteCachedFileIfNeeded); } catch (IOException e) { log.error("Cleaning featured mod files cache failed", e); } }

Target:
private void cleanUnusedFilesFromCache() { try (Stream<Path> pathElements = Files.walk(preferencesService.getFeaturedModCachePath())) { pathElements .filter(Files::isRegularFile) .forEach(this::deleteCachedFileIfNeeded); } catch (IOException e) { log.error("Cleaning featured mod files cache failed", e); } }
Source:
private ParticipantObjectIdentificationType createQueryParticipantObjectIdentification(String queryId, String hcid) { ParticipantObjectIdentificationType participantObject = createParticipantObject( DocQueryAuditTransformsConstants.PARTICIPANT_QUERY_OBJ_TYPE_CODE_SYSTEM, DocQueryAuditTransformsConstants.PARTICIPANT_QUERY_OBJ_TYPE_CODE_ROLE, DocQueryAuditTransformsConstants.PARTICIPANT_QUERY_OBJ_ID_TYPE_CODE, DocQueryAuditTransformsConstants.PARTICIPANT_QUERY_OBJ_ID_TYPE_CODE_SYSTEM, DocQueryAuditTransformsConstants.PARTICIPANT_QUERY_OBJ_ID_TYPE_DISPLAY_NAME); if (NullChecker.isNotNullish(queryId)) { participantObject.setParticipantObjectID(queryId); } TypeValuePairType encoding = new TypeValuePairType(); encoding.setType(DocQueryAuditTransformsConstants.QUERY_ENCODING_TYPE); encoding.setValue(DocQueryAuditTransformsConstants.UTF_8.getBytes()); participantObject.getParticipantObjectDetail().add(encoding); if (NullChecker.isNotNullish(hcid)) { TypeValuePairType homeCommunityTypeValue = new TypeValuePairType(); homeCommunityTypeValue.setType(DocQueryAuditTransformsConstants.HOME_COMMUNITY_ID); homeCommunityTypeValue.setValue(hcid.getBytes()); participantObject.getParticipantObjectDetail().add(homeCommunityTypeValue); } return participantObject; }

Target:
private ParticipantObjectIdentificationType createQueryParticipantObjectIdentification(String queryId, String hcid) { ParticipantObjectIdentificationType participantObject = createParticipantObject( DocQueryAuditTransformsConstants.PARTICIPANT_QUERY_OBJ_TYPE_CODE_SYSTEM, DocQueryAuditTransformsConstants.PARTICIPANT_QUERY_OBJ_TYPE_CODE_ROLE, DocQueryAuditTransformsConstants.PARTICIPANT_QUERY_OBJ_ID_TYPE_CODE, DocQueryAuditTransformsConstants.PARTICIPANT_QUERY_OBJ_ID_TYPE_CODE_SYSTEM, DocQueryAuditTransformsConstants.PARTICIPANT_QUERY_OBJ_ID_TYPE_DISPLAY_NAME); if (NullChecker.isNotNullish(queryId)) { participantObject.setParticipantObjectID(queryId); } participantObject.getParticipantObjectDetail().add(getTypeValuePair( DocQueryAuditTransformsConstants.QUERY_ENCODING_TYPE, DocQueryAuditTransformsConstants.UTF_8.getBytes())); if (NullChecker.isNotNullish(hcid)) { participantObject.getParticipantObjectDetail().add(getTypeValuePair( DocQueryAuditTransformsConstants.HOME_COMMUNITY_ID, hcid.getBytes())); } return participantObject; }
Source:
public <T> Model<T> get(Class<T> type, @CheckForNull Class<?> propertyOwner, @Nullable String property) { if (type.getAnnotation(ExportedBean.class) == null) { throw new NotExportableException(type); } return getOrNull(type, propertyOwner, property); }

Target:
public <T> Model<T> get(Class<T> type, @CheckForNull Class<?> propertyOwner, @Nullable String property) throws NotExportableException { Model<T> model = getOrNull(type, propertyOwner, property); if (model == null) { throw new NotExportableException(type); } return model; }
Source:
public ServiceResponse<List<PatientEncounterItem>> returnCurrentDayPatientEncounters() { ServiceResponse<List<PatientEncounterItem>> response = new ServiceResponse<>(); List<PatientEncounterItem> patientEncounterItems = new ArrayList<>(); ExpressionList<PatientEncounter> query = QueryProvider.getPatientEncounterQuery() .where() .ge("id",0); try{ List<PatientItem> patientItems=null; List<? extends IPatientEncounter> patient = patientEncounterRepository.find(query); for (IPatientEncounter patient1 : patient) { DateTime triageDate= patient1.getDateOfTriageVisit(); Date tDate=triageDate.toDate(); String triagePatientDate=dateUtils.getFriendlyDate(tDate); Date todayDate=DateTime.now().toDate(); String currentDate=dateUtils.getFriendlyDate(todayDate); if(triagePatientDate.equalsIgnoreCase(currentDate)) { patientEncounterItems.add(itemModelMapper.createPatientEncounterItem(patient1)); } } response.setResponseObject(patientEncounterItems); } catch (Exception ex) { response.addError("", ex.getMessage()); } return response; }

Target:
public ServiceResponse<List<PatientEncounterItem>> returnCurrentDayPatientEncounters() { ServiceResponse<List<PatientEncounterItem>> response = new ServiceResponse<>(); List<PatientEncounterItem> patientEncounterItems = new ArrayList<>(); DateTime today= DateTime.now(); today=today.withTimeAtStartOfDay(); DateTime tommorrow=today; tommorrow=tommorrow.plusDays(1); ExpressionList<PatientEncounter> query = QueryProvider.getPatientEncounterQuery() .where() .ge("date_of_triage_visit", today) .le("date_of_triage_visit", tommorrow); try{ List<PatientItem> patientItems=null; List<? extends IPatientEncounter> patient = patientEncounterRepository.find(query); for (IPatientEncounter patient1 : patient) { patientEncounterItems.add(itemModelMapper.createPatientEncounterItem(patient1)); } response.setResponseObject(patientEncounterItems); } catch (Exception ex) { response.addError("", ex.getMessage()); } return response; }
Source:
private Set<Capability> searchRepository(Repository osgiRepo, String pkg) { Requirement req = buildRequirement(pkg); Set<Capability> resultSet = new LinkedHashSet<>(); Map<Requirement, Collection<Capability>> providers = osgiRepo.findProviders(Collections.singleton(req)); for (Collection<Capability> values : providers.values()) { if (values == null) { continue; } for (Capability providerCap : values) { resultSet.add(providerCap); } } return resultSet; }

Target:
private Collection<Capability> searchRepository(Repository osgiRepo, String pkg) { final Requirement req = buildRequirement(pkg); Map<Requirement, Collection<Capability>> providers = osgiRepo.findProviders(Collections.singleton(req)); return providers.get(req); }
Source:
public CompletableFuture<Set<String>> keySet() { return applyAll(service -> service.keySet()) .thenApply(results -> results.reduce((s1, s2) -> ImmutableSet.<String>builder().addAll(s1).addAll(s2).build()).orElse(ImmutableSet.of())); }

Target:
public CompletableFuture<Set<String>> keySet() { return applyAll(service -> service.keySet()) .thenApply(results -> results.flatMap(Collection::stream).collect(Collectors.toSet())); }
Source:
private List<String> makeCleanupList(String entityId, List<Statement> data) { Set<String> values = new HashSet<>(); Set<String> refs = new HashSet<>(); munger.mungeWithValues(entityId, data, rdfRepository.getValues(Collections.singletonList(uris.entity() + entityId)), rdfRepository.getRefs(Collections.singletonList(uris.entity() + entityId)), values, refs, null, null); List<String> changeList = new ArrayList<>(); changeList.addAll(values); changeList.addAll(refs); return changeList; }

Target:
private List<String> makeCleanupList(String entityId, List<Statement> data) { Set<String> values = new HashSet<>(); Set<String> refs = new HashSet<>(); munger.mungeWithValues(entityId, data, rdfRepository.getValues(singletonList(uris.entity() + entityId)), rdfRepository.getRefs(singletonList(uris.entity() + entityId)), values, refs, null, null); List<String> changeList = new ArrayList<>(); changeList.addAll(values); changeList.addAll(refs); return changeList; }
Source:
public CustomTxtParserWizard() { super(); setWindowTitle(Messages.CustomTxtParserInputWizardPage_windowTitle); }

Target:
public CustomTxtParserWizard() { this(null); }
Source:
public String evaluate(Object obj, String expression) { String result = ""; try { scriptEngine.put(getType(), obj); result = String.valueOf(scriptEngine.eval(expression)); } catch (Exception ignored) return result; }

Target:
public String evaluate(Object obj, String expression) { String result = ""; try { scriptEngine.put(getType(), obj); result = String.valueOf(scriptEngine.eval(expression)); } catch (Exception exception) { LOGGER.warn("Unable to evaluate expression %s due to: %s. Please check your shell confugration", expression, exception.getMessage()); result = "<evalution error - see log>"; } return result; }
Source:
private void processSeenContent(OwlTelescopeReporter telescope) { Iterable<ModelWithPayload<Content>> brands = Iterables.filter(seenContent.values(), IS_BRAND::test); for (ModelWithPayload<Content> container : brands) { checkAndWriteSeenContent(container, telescope); } Iterable<ModelWithPayload<Content>> series = Iterables.filter(seenContent.values(), IS_SERIES::test); for (ModelWithPayload<Content> container : series) { checkAndWriteSeenContent(container, telescope); } Iterable<ModelWithPayload<Content>> notContainers = seenContent.values() .stream() .filter(and(not(IS_BRAND::test), not(IS_SERIES::test))::apply) .collect(Collectors.toList()); for (ModelWithPayload<Content> notContainer : notContainers) { checkAndWriteSeenContent(notContainer, telescope); } }

Target:
private void processSeenContent(OwlTelescopeReporter telescope) { List<ModelWithPayload<Content>> brands = new ArrayList<>(); List<ModelWithPayload<Content>> series = new ArrayList<>(); List<ModelWithPayload<Content>> notContainers = new ArrayList<>(); for (ModelWithPayload<Content> container : seenContent.values()){ if (container.getModel() instanceof Brand){ brands.add(container); } else if (container.getModel() instanceof Series){ series.add(container); } else { notContainers.add(container); } } brands.stream().forEach(c -> checkAndWriteSeenContent(c, telescope)); series.stream().forEach(c -> checkAndWriteSeenContent(c, telescope)); notContainers.stream().forEach(c -> checkAndWriteSeenContent(c, telescope)); }