auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private List<Path> createTestStructure() throws IOException{ Path rootDir = Paths.get(folder.getRoot().toURI()); Path dataDir = rootDir.resolve("data"); File file1 = folder.newFile("file1.txt"); Path file1Path = Paths.get(file1.toURI()); file1.createNewFile(); File dir1 = folder.newFolder("folder1"); dir1.mkdir(); File file2 = folder.newFile("file2.txt"); Path file2Path = Paths.get(file2.toURI()); file2.createNewFile(); boolean isWindows = System.getProperty("os.name").contains("Windows"); File hiddenFile = folder.newFile(".hiddentFile.txt"); if (isWindows){ Files.setAttribute(Paths.get(hiddenFile.toURI()), "dos:hidden", true); } assertTrue(hiddenFile.isHidden()); File hiddenDirectory = folder.newFolder(".hiddenFolder"); if (isWindows){ Files.setAttribute(Paths.get(hiddenDirectory.toURI()), "dos:hidden", true); } assertTrue(hiddenDirectory + " should be hidden unless on windows", hiddenDirectory.isHidden()); File hiddenFile2 = new File(hiddenDirectory, ".hiddenFile2.txt"); hiddenFile2.createNewFile(); if (isWindows){ Files.setAttribute(Paths.get(hiddenFile2.toURI()), "dos:hidden", true); } File file3 = new File(hiddenDirectory, "file3.txt"); file3.createNewFile(); return Arrays.asList(dataDir.resolve(file1Path.getFileName()), dataDir.resolve(file2Path.getFileName())); }

Target:
private List<Path> createTestStructure() throws IOException{ Path rootDir = Paths.get(folder.getRoot().toURI()); Path dataDir = rootDir.resolve("data"); Path file1Path = createEmptyFile(folder, "file1.txt"); File dir1 = folder.newFolder("folder1"); dir1.mkdir(); Path file2Path = createEmptyFile(folder, "file2.txt"); File hiddenFile = folder.newFile(".hiddentFile.txt"); hideIfWindows(hiddenFile); assertTrue(hiddenFile.isHidden()); File hiddenDirectory = folder.newFolder(".hiddenFolder"); hideIfWindows(hiddenDirectory); assertTrue(hiddenDirectory + " should be hidden unless on windows", hiddenDirectory.isHidden()); File hiddenFile2 = new File(hiddenDirectory, ".hiddenFile2.txt"); hiddenFile2.createNewFile(); hideIfWindows(hiddenFile2); File file3 = new File(hiddenDirectory, "file3.txt"); file3.createNewFile(); return Arrays.asList(dataDir.resolve(file1Path.getFileName()), dataDir.resolve(file2Path.getFileName())); }
Source:
if( !initialized && prefs.getApplicationId() != null && prefs.getApiKey() != null ) Backendless.initApplicationFromProperties( ContextHandler.getAppContext() ); } catch( IllegalStateException e ) { if( !e.getMessage().equals( "Backendless application was not initialized" ) ) throw e; }

Target:
if( !initialized && prefs.getApplicationId() != null && prefs.getApiKey() != null ) Backendless.initApplicationFromProperties( ContextHandler.getAppContext() ); } catch( IllegalStateException e ) { if( !ExceptionMessage.NOT_INITIALIZED.equals( e.getMessage() ) ) throw e; }
Source:
double getSumOfScores(Map<SoftConstraint, Float> originScoresMap) { return originScoresMap.entrySet().stream().map(constraintToOriginScore -> { float score = MIN_MAX_SCALER.scale(constraintToOriginScore.getValue()); float weight = MODEL.get(constraintToOriginScore.getKey().getType()); return score * weight; }).mapToDouble(i -> i).sum(); }

Target:
float getSumOfScores(Map<SoftConstraint, Float> originScoresMap) { float sum = 0; for (Map.Entry<SoftConstraint, Float> softConstraintScoreEntry : originScoresMap.entrySet()) { SoftConstraint softConstraint = softConstraintScoreEntry.getKey(); float score = softConstraint.getScalerFunction().scale(softConstraintScoreEntry.getValue()); float weight = MODEL.get(softConstraint); sum += score * weight; } return sum; }
Source:
public WeightedRandomModel(ResourceLocation parent, VariantList variants) throws Exception { this.variants = variants.getVariantList(); this.locations = new ArrayList<>(); this.textures = Sets.newHashSet(); this.models = new ArrayList<>(); ImmutableList.Builder<Pair<IModel, IModelState>> builder = ImmutableList.builder(); for (Variant v : this.variants) { ResourceLocation loc = v.getModelLocation(); locations.add(loc); IModel model; if(loc.equals(MODEL_MISSING)) { model = ModelLoaderRegistry.getMissingModel(); } else { model = ModelLoaderRegistry.getModel(loc); } model = v.process(model); for(ResourceLocation location : model.getDependencies()) { ModelLoaderRegistry.getModelOrMissing(location); } textures.addAll(model.getTextures()); models.add(model); IModelState modelDefaultState = model.getDefaultState(); if (modelDefaultState != null) { builder.add(Pair.of(model, new ModelStateComposition(v.getState(), modelDefaultState))); } else { throw new NullPointerException("Model " + loc + " returned null as default state"); } } if (models.size() == 0) { IModel missing = ModelLoaderRegistry.getMissingModel(); models.add(missing); builder.add(Pair.of(missing, TRSRTransformation.identity())); } defaultState = new MultiModelState(builder.build()); }

Target:
public WeightedRandomModel(ResourceLocation parent, VariantList variants) throws Exception { this.variants = variants.getVariantList(); this.locations = new ArrayList<>(); this.textures = Sets.newHashSet(); this.models = new ArrayList<>(); ImmutableList.Builder<Pair<IModel, IModelState>> builder = ImmutableList.builder(); for (Variant v : this.variants) { ResourceLocation loc = v.getModelLocation(); locations.add(loc); IModel model; if(loc.equals(MODEL_MISSING)) { model = ModelLoaderRegistry.getMissingModel(); } else { model = ModelLoaderRegistry.getModel(loc); } model = v.process(model); for(ResourceLocation location : model.getDependencies()) { ModelLoaderRegistry.getModelOrMissing(location); } textures.addAll(model.getTextures()); models.add(model); IModelState modelDefaultState = model.getDefaultState(); Preconditions.checkNotNull(modelDefaultState, "Model %s returned null as default state", loc); builder.add(Pair.of(model, new ModelStateComposition(v.getState(), modelDefaultState))); } if (models.size() == 0) { IModel missing = ModelLoaderRegistry.getMissingModel(); models.add(missing); builder.add(Pair.of(missing, TRSRTransformation.identity())); } defaultState = new MultiModelState(builder.build()); }
Source:
public void configure() { synchronized(hasSRAMPPackageDeployed) { KieSrampUtil kieSrampUtil = new KieSrampUtil(); Governance governance = new Governance(); String groupId = governance.getGovernanceWorkflowGroup(); String artifactId = governance.getGovernanceWorkflowName(); String version = null; try { version = SrampMavenUtil.getVersion(SRAMP_KIE_MODEL, groupId, artifactId, governance.getGovernanceWorkflowVersion()); } catch (SrampClientException e) { e.printStackTrace(); } catch (SrampAtomException e) { e.printStackTrace(); } if (kieSrampUtil.isSRAMPPackageDeployed(groupId, artifactId, version)) { KModuleDeploymentUnit unit = new KModuleDeploymentUnit( groupId, artifactId, version, Governance.DEFAULT_GOVERNANCE_WORKFLOW_PACKAGE, Governance.DEFAULT_GOVERNANCE_WORKFLOW_KSESSION); RuntimeManager runtimeManager = kieSrampUtil.getRuntimeManager(processEngineService, unit); RuntimeEngine runtime = runtimeManager.getRuntimeEngine(EmptyContext.get()); runtime.getTaskService().toString(); } } }

Target:
public void configure() { synchronized(hasSRAMPPackageDeployed) { KieSrampUtil kieSrampUtil = new KieSrampUtil(); Governance governance = new Governance(); String groupId = governance.getGovernanceWorkflowGroup(); String artifactId = governance.getGovernanceWorkflowName(); String workflowVersion = governance.getGovernanceWorkflowVersion(); String version = null; try { version = SrampMavenUtil.getVersion(SRAMP_KIE_MODEL, groupId, artifactId, workflowVersion); } catch (SrampClientException e) { throw new RuntimeException(Messages.i18n.format("maven.version.not.found.error", groupId, artifactId, workflowVersion), e); } catch (SrampAtomException e) { throw new RuntimeException(Messages.i18n.format("maven.version.not.found.error", groupId, artifactId, workflowVersion), e); } if (StringUtils.isBlank(version)) { throw new RuntimeException(Messages.i18n.format("maven.version.not.found", groupId, artifactId, workflowVersion)); } if (kieSrampUtil.isSRAMPPackageDeployed(groupId, artifactId, version)) { KModuleDeploymentUnit unit = new KModuleDeploymentUnit( groupId, artifactId, version, Governance.DEFAULT_GOVERNANCE_WORKFLOW_PACKAGE, Governance.DEFAULT_GOVERNANCE_WORKFLOW_KSESSION); RuntimeManager runtimeManager = kieSrampUtil.getRuntimeManager(processEngineService, unit); RuntimeEngine runtime = runtimeManager.getRuntimeEngine(EmptyContext.get()); runtime.getTaskService().toString(); } } }
Source:
void startLoadJob(ProjectWrapper projectWrapper, IExceptionHandler handler) { new Job("load project") { @Override protected IStatus run(IProgressMonitor monitor) { try { WatchManager.getInstance().startWatch(projectWrapper.getResource()); Collection<IResource> resources = new HashSet<>(); for (String kind : RESOURCE_KINDS) { resources.addAll(projectWrapper.getResource().getResources(kind)); } resources.forEach(r -> resourceCache.add(r)); projectWrapper.initWithResources(resources); projectWrapper.fireChanged(); } catch (OperationCanceledException e) { projectWrapper.setLoadingState(LoadingState.LOAD_STOPPED); } catch (Throwable e) { projectWrapper.setLoadingState(LoadingState.LOAD_STOPPED); handler.handleException(e); } return Status.OK_STATUS; } }.schedule(); }

Target:
void startLoadJob(ProjectWrapper projectWrapper, IExceptionHandler handler) { new Job("Load project contents") { @Override protected IStatus run(IProgressMonitor monitor) { try { IProject project = projectWrapper.getWrapped(); WatchManager.getInstance().startWatch(project); Collection<IResource> resources = new HashSet<>(); for (String kind : RESOURCE_KINDS) { resources.addAll(getWrapped().getResources(kind, project.getNamespace())); } resources.forEach(r -> resourceCache.add(r)); projectWrapper.initWithResources(resources); projectWrapper.fireChanged(); } catch (OperationCanceledException e) { projectWrapper.setLoadingState(LoadingState.LOAD_STOPPED); } catch (Throwable e) { projectWrapper.setLoadingState(LoadingState.LOAD_STOPPED); handler.handleException(e); } return Status.OK_STATUS; } }.schedule(); }
Source:
public Collection<CacheEntry<K, K>> performOperationRehashAware( IntermediateCollector<Collection<CacheEntry<K, K>>> response) { BaseStream<?, ?> stream = supplier.get().sequential(); List<CacheEntry<K, K>> collectedValues = new ArrayList(batchSize); List<V> currentList = new ArrayList<>(); ByRef<K> ref = new ByRef<>(null); stream = ((Stream<Map.Entry<K, ?>>) stream).peek(e -> { if (!currentList.isEmpty()) { collectedValues.add(new ImmortalCacheEntry(ref.get(), null)); if (collectedValues.size() >= batchSize) { handleList(currentList); response.sendDataResonse(collectedValues); collectedValues.clear(); currentList.clear(); } } ref.set(e.getKey()); }); for (IntermediateOperation intermediateOperation : intermediateOperations) { stream = intermediateOperation.perform(stream); } S convertedStream = ((S) stream); handleStreamForEach(convertedStream, currentList); if (!currentList.isEmpty()) { handleList(currentList); collectedValues.add(new ImmortalCacheEntry(ref.get(), null)); } return collectedValues; }

Target:
public Collection<CacheEntry<K, K>> performOperationRehashAware( IntermediateCollector<Collection<CacheEntry<K, K>>> response) { BaseStream<?, ?> stream = supplier.get().sequential(); List<CacheEntry<K, K>> collectedValues = new ArrayList(batchSize); List<V> currentList = new ArrayList<>(); ByRef<K> currentKey = new ByRef<>(null); stream = ((Stream<Map.Entry<K, ?>>) stream).peek(e -> { if (!currentList.isEmpty()) { collectedValues.add(new ImmortalCacheEntry(currentKey.get(), null)); if (collectedValues.size() >= batchSize) { handleList(currentList); response.sendDataResonse(collectedValues); collectedValues.clear(); currentList.clear(); } } currentKey.set(e.getKey()); }); for (IntermediateOperation intermediateOperation : intermediateOperations) { stream = intermediateOperation.perform(stream); } S convertedStream = ((S) stream); handleStreamForEach(convertedStream, currentList); if (!currentList.isEmpty()) { handleList(currentList); collectedValues.add(new ImmortalCacheEntry(currentKey.get(), null)); } return collectedValues; }
Source:
public void loadState(HueState state, String... lightIdentifiers) { if (!hueFacade.bridgeAvailable()) { throw new StateNotLoadedException("Hue bridge is not available"); } String[] ids = getLightIdentifiers(lightIdentifiers); restoreState = () -> { new BlankState().execute(hueFacade, ids); state.execute(hueFacade, ids); log.debug("Light states restored!"); }; new BlankState().execute(hueFacade, ids); state.execute(hueFacade, ids); }

Target:
public void loadState(HueState state, String... lightIdentifiers) { if (!hueFacade.isBridgeAvailable()) { throw new StateNotLoadedException("Hue bridge is not available"); } String[] ids = getLightIdentifiers(lightIdentifiers); restoreState = () -> { new BlankState().execute(hueFacade, ids); state.execute(hueFacade, ids); log.debug("Light states restored!"); }; new BlankState().execute(hueFacade, ids); state.execute(hueFacade, ids); }
Source:
public void testCantSetChangeDetectionOnIndex() throws Exception { Assume.assumeTrue(HbaseCompatCapabilities.hasPreWALAppend()); try (Connection conn = DriverManager.getConnection(getUrl())) { SchemaBuilder builder = new SchemaBuilder(getUrl()); builder.withTableDefaults().build(); try { String badIndexSql = "CREATE INDEX IDX_SHOULD_FAIL" + " ON " + builder.getEntityTableName() + "(COL1) " + CHANGE_DETECTION_ENABLED + "=TRUE"; conn.createStatement().execute(badIndexSql); Assert.fail("Didn't throw a SQLException for setting change detection on an " + "index at create time!"); } catch (SQLException se) { TestUtil.assertSqlExceptionCode( SQLExceptionCode.CHANGE_DETECTION_SUPPORTED_FOR_TABLES_AND_VIEWS_ONLY, se); } } }

Target:
public void testCantSetChangeDetectionOnIndex() throws Exception { Assume.assumeTrue(HbaseCompatCapabilities.hasPreWALAppend()); try (Connection conn = DriverManager.getConnection(getUrl())) { SchemaBuilder builder = new SchemaBuilder(getUrl()); builder.withTableDefaults().build(); try { String badIndexSql = "CREATE INDEX IDX_SHOULD_FAIL" + " ON " + builder.getEntityTableName() + "(COL1) " + CHANGE_DETECTION_ENABLED + "=TRUE"; conn.createStatement().execute(badIndexSql); fail("Didn't throw a SQLException for setting change detection on an " + "index at create time!"); } catch (SQLException se) { TestUtil.assertSqlExceptionCode( SQLExceptionCode.CHANGE_DETECTION_SUPPORTED_FOR_TABLES_AND_VIEWS_ONLY, se); } } }
Source:
public void testClientsConnections() throws Exception { String host = ignite.configuration().getClientConnectorConfiguration().getHost(); if (host == null) host = ignite.configuration().getLocalHost(); int port = ignite.configuration().getClientConnectorConfiguration().getPort(); try (IgniteClient client = Ignition.startClient(new ClientConfiguration().setAddresses(host + ":" + port))) { try (Connection conn = new IgniteJdbcThinDriver().connect("jdbc:ignite:thin://" + host, new Properties())) { TabularDataSupport conns = systemView(CLI_CONN_SYS_VIEW); Consumer<CompositeData> checkThin = c -> { assertEquals("THIN", c.get("type")); assertTrue(c.get("localAddress").toString().endsWith(Integer.toString(port))); assertEquals(c.get("version"), DEFAULT_VER.asString()); }; Consumer<CompositeData> checkJdbc = c -> { assertEquals("JDBC", c.get("type")); assertTrue(c.get("localAddress").toString().endsWith(Integer.toString(port))); assertEquals(c.get("version"), CURRENT_VER.asString()); }; CompositeData c0 = conns.get(new Object[] {0}); CompositeData c1 = conns.get(new Object[] {1}); if (c0.get("type").equals("JDBC")) { checkJdbc.accept(c0); checkThin.accept(c1); } else { checkJdbc.accept(c1); checkThin.accept(c0); } assertEquals(2, conns.size()); } } }

Target:
public void testClientsConnections() throws Exception { String host = ignite.configuration().getClientConnectorConfiguration().getHost(); if (host == null) host = ignite.configuration().getLocalHost(); int port = ignite.configuration().getClientConnectorConfiguration().getPort(); try (IgniteClient client = Ignition.startClient(new ClientConfiguration().setAddresses(host + ":" + port))) { try (Connection conn = new IgniteJdbcThinDriver().connect("jdbc:ignite:thin://" + host, new Properties())) { TabularDataSupport conns = systemView(CLI_CONN_SYS_VIEW); Consumer<CompositeData> checkThin = c -> { assertEquals("THIN", c.get("type")); assertTrue(c.get("localAddress").toString().endsWith(Integer.toString(port))); assertEquals(c.get("version"), ProtocolVersion.CURRENT_VER.toString()); }; Consumer<CompositeData> checkJdbc = c -> { assertEquals("JDBC", c.get("type")); assertTrue(c.get("localAddress").toString().endsWith(Integer.toString(port))); assertEquals(c.get("version"), JdbcConnectionContext.CURRENT_VER.asString()); }; CompositeData c0 = conns.get(new Object[] {0}); CompositeData c1 = conns.get(new Object[] {1}); if (c0.get("type").equals("JDBC")) { checkJdbc.accept(c0); checkThin.accept(c1); } else { checkJdbc.accept(c1); checkThin.accept(c0); } assertEquals(2, conns.size()); } } boolean res = GridTestUtils.waitForCondition(() -> systemView(CLI_CONN_SYS_VIEW).isEmpty(), 5_000); assertTrue(res); }
Source:
public void enqueueSuspended(ScheduledTaskDescriptor descriptor, boolean force) { if (logger.isFinestEnabled()) { log(FINEST, "Enqueuing suspended, i.e., backup: " + descriptor.getDefinition()); } boolean keyExists = tasks.containsKey(descriptor.getDefinition().getName()); if (force || !(keyExists)) { taskLifecycleHook.preSuspendedEnqueue(name, descriptor, !keyExists); tasks.put(descriptor.getDefinition().getName(), descriptor); taskLifecycleHook.postSuspendedEnqueue(name, descriptor, !keyExists); } }

Target:
public void enqueueSuspended(ScheduledTaskDescriptor descriptor, boolean force) { if (logger.isFinestEnabled()) { log(FINEST, "Enqueuing suspended, i.e., backup: " + descriptor.getDefinition()); } boolean keyExists = tasks.containsKey(descriptor.getDefinition().getName()); if (force || !keyExists) { tasks.put(descriptor.getDefinition().getName(), descriptor); } }
Source:
public List<Integer> getHistoryIds(long sessionId) throws DatabaseException { return getHistoryIdsByParams(sessionId,0, true, null); }

Target:
public List<Integer> getHistoryIds(long sessionId) throws DatabaseException { return getHistoryIdsOfHistType(sessionId, null); }
Source:
public void bindView(View view, Context context, Cursor cursor) { view.setBackgroundResource(R.drawable.selectable_item_background); TextView title = (TextView) view.findViewById(R.id.page_list_item_title); ImageView thumbnail = (ImageView) view.findViewById(R.id.page_list_item_image); HistoryEntry entry = HistoryEntry.PERSISTENCE_HELPER.fromCursor(cursor); title.setText(entry.getTitle().getDisplayText()); view.setTag(entry); if (app.isImageDownloadEnabled()) { Picasso.with(getActivity()) .load(cursor.getString(HistoryEntryContentProvider.COL_INDEX_IMAGE)) .placeholder(R.drawable.ic_pageimage_placeholder) .error(R.drawable.ic_pageimage_placeholder) .into(thumbnail); } else { Picasso.with(getActivity()) .load(R.drawable.ic_pageimage_placeholder) .into(thumbnail); } String curTime, prevTime = ""; if (cursor.getPosition() != 0) { Cursor prevCursor = (Cursor) getItem(cursor.getPosition() - 1); HistoryEntry prevEntry = HistoryEntry.PERSISTENCE_HELPER.fromCursor(prevCursor); prevTime = getDateString(prevEntry.getTimestamp()); } curTime = getDateString(entry.getTimestamp()); TextView sectionHeader = (TextView) view.findViewById(R.id.page_list_header_text); if (!curTime.equals(prevTime)) { sectionHeader.setText(curTime); sectionHeader.setVisibility(View.VISIBLE); } else { sectionHeader.setVisibility(View.GONE); } }

Target:
public void bindView(View view, Context context, Cursor cursor) { TextView title = (TextView) view.findViewById(R.id.page_list_item_title); ImageView thumbnail = (ImageView) view.findViewById(R.id.page_list_item_image); HistoryEntry entry = HistoryEntry.PERSISTENCE_HELPER.fromCursor(cursor); title.setText(entry.getTitle().getDisplayText()); view.setTag(entry); if (app.isImageDownloadEnabled()) { Picasso.with(getActivity()) .load(cursor.getString(HistoryEntryContentProvider.COL_INDEX_IMAGE)) .placeholder(R.drawable.ic_pageimage_placeholder) .error(R.drawable.ic_pageimage_placeholder) .into(thumbnail); } else { Picasso.with(getActivity()) .load(R.drawable.ic_pageimage_placeholder) .into(thumbnail); } String curTime, prevTime = ""; if (cursor.getPosition() != 0) { Cursor prevCursor = (Cursor) getItem(cursor.getPosition() - 1); HistoryEntry prevEntry = HistoryEntry.PERSISTENCE_HELPER.fromCursor(prevCursor); prevTime = getDateString(prevEntry.getTimestamp()); } curTime = getDateString(entry.getTimestamp()); TextView sectionHeader = (TextView) view.findViewById(R.id.page_list_header_text); if (!curTime.equals(prevTime)) { sectionHeader.setText(curTime); sectionHeader.setVisibility(View.VISIBLE); } else { sectionHeader.setVisibility(View.GONE); } }
Source:
public void groupForOrphanItemsTest() { final String ORPHAN_ITEM = "orphanitem"; NavTreeBuilder builder = new NavTreeBuilder(); LayoutTemplate lt = new LayoutTemplate("lt1"); LayoutTemplate lt2 = new LayoutTemplate(ORPHAN_ITEM); final String ITEM = "item1"; final String ITEM_TO_REMOVE = "item2"; final String GROUP = "group"; builder.group(GROUP, GROUP, "", false); builder.item(ITEM, ITEM, "", false, NavWorkbenchCtx.perspective(lt.getName())); builder.item(ITEM_TO_REMOVE, ITEM_TO_REMOVE, "", false); builder.endGroup(); List<LayoutTemplate> templates = new ArrayList<>(); templates.add(lt); templates.add(lt2); NavTree originalTree = builder.build(); assertNull(originalTree.getItemById(RuntimeNavigationBuilder.ORPHAN_GROUP_ID)); assertEquals(1, originalTree.getRootItems().size()); NavTree runtimeTree = runtimeNavigationBuilder.buildRuntimeTree(originalTree, templates); assertEquals(2, runtimeTree.getRootItems().size()); NavGroup orphanItemsGroup = (NavGroup) runtimeTree.getItemById(RuntimeNavigationBuilder.ORPHAN_GROUP_ID); assertNotNull(orphanItemsGroup); assertEquals(1, orphanItemsGroup.getChildren().size()); NavItem orphanItem = runtimeTree.getItemById(ORPHAN_ITEM); String resourceId = NavWorkbenchCtx.get(orphanItem).getResourceId(); assertEquals(ORPHAN_ITEM, resourceId); assertEquals(orphanItemsGroup, orphanItem.getParent()); }

Target:
public void groupForOrphanItemsTest() { final String ORPHAN_ITEM = "orphanitem"; NavTreeBuilder builder = new NavTreeBuilder(); LayoutTemplate lt = new LayoutTemplate("lt1"); LayoutTemplate lt2 = new LayoutTemplate(ORPHAN_ITEM); final String ITEM_TO_REMOVE = "item2"; builder.group(GROUP, GROUP, "", false); builder.item(ITEM, ITEM, "", false, NavWorkbenchCtx.perspective(lt.getName())); builder.item(ITEM_TO_REMOVE, ITEM_TO_REMOVE, "", false); builder.endGroup(); List<LayoutTemplate> templates = Arrays.asList(lt, lt2); NavTree originalTree = builder.build(); assertNull(originalTree.getItemById(RuntimeNavigationBuilder.ORPHAN_GROUP_ID)); assertEquals(1, originalTree.getRootItems().size()); NavTree runtimeTree = runtimeNavigationBuilder.buildRuntimeTree(originalTree, templates); assertEquals(2, runtimeTree.getRootItems().size()); NavGroup orphanItemsGroup = (NavGroup) runtimeTree.getItemById(RuntimeNavigationBuilder.ORPHAN_GROUP_ID); assertNotNull(orphanItemsGroup); assertEquals(1, orphanItemsGroup.getChildren().size()); NavItem orphanItem = runtimeTree.getItemById(ORPHAN_ITEM); String resourceId = NavWorkbenchCtx.get(orphanItem).getResourceId(); assertEquals(ORPHAN_ITEM, resourceId); assertEquals(orphanItemsGroup, orphanItem.getParent()); }
Source:
public void accept(Event<CollectLoadBalancerMetadataRequest> collectLBMetadataRequestEvent) { LOGGER.debug("Received event: {}", collectLBMetadataRequestEvent); CollectLoadBalancerMetadataRequest request = collectLBMetadataRequestEvent.getData(); try { CloudConnector<Object> connector = cloudPlatformConnectors.get(request.getCloudContext().getPlatformVariant()); AuthenticatedContext ac = connector.authentication().authenticate(request.getCloudContext(), request.getCloudCredential()); List<CloudLoadBalancerMetadata> loadBalancerStatuses = connector.metadata() .collectLoadBalancer(ac, request.getGatewayGroupNames()); CollectLoadBalancerMetadataResult collectLBMetadataResult = new CollectLoadBalancerMetadataResult(request.getResourceId(), loadBalancerStatuses); request.getResult().onNext(collectLBMetadataResult); eventBus.notify(collectLBMetadataResult.selector(), new Event<>(collectLBMetadataRequestEvent.getHeaders(), collectLBMetadataResult)); LOGGER.debug("Load balancer metadata collection successfully finished"); } catch (RuntimeException e) { LOGGER.error("Collecting metadata failed", e); CollectLoadBalancerMetadataResult failure = new CollectLoadBalancerMetadataResult(e, request.getResourceId()); request.getResult().onNext(failure); eventBus.notify(failure.selector(), new Event<>(collectLBMetadataRequestEvent.getHeaders(), failure)); } }

Target:
public void accept(Event<CollectLoadBalancerMetadataRequest> collectLBMetadataRequestEvent) { LOGGER.debug("Received event: {}", collectLBMetadataRequestEvent); CollectLoadBalancerMetadataRequest request = collectLBMetadataRequestEvent.getData(); try { CloudConnector<Object> connector = cloudPlatformConnectors.get(request.getCloudContext().getPlatformVariant()); AuthenticatedContext ac = connector.authentication().authenticate(request.getCloudContext(), request.getCloudCredential()); List<CloudLoadBalancerMetadata> loadBalancerStatuses = connector.metadata().collectLoadBalancer(ac, request.getTypesPresentInStack()); CollectLoadBalancerMetadataResult collectLBMetadataResult = new CollectLoadBalancerMetadataResult(request.getResourceId(), loadBalancerStatuses); request.getResult().onNext(collectLBMetadataResult); eventBus.notify(collectLBMetadataResult.selector(), new Event<>(collectLBMetadataRequestEvent.getHeaders(), collectLBMetadataResult)); LOGGER.debug("Load balancer metadata collection successfully finished"); } catch (RuntimeException e) { LOGGER.error("Collecting metadata failed", e); CollectLoadBalancerMetadataResult failure = new CollectLoadBalancerMetadataResult(e, request.getResourceId()); request.getResult().onNext(failure); eventBus.notify(failure.selector(), new Event<>(collectLBMetadataRequestEvent.getHeaders(), failure)); } }
Source:
public CompletableFuture<ClientResponse> run(byte[] jarfileBytes, String classesToDeleteSelector) { if (!allowPausedModeWork(false, isAdminConnection())) { return makeQuickResponse( ClientResponse.SERVER_UNAVAILABLE, "Server is paused and is available in read-only mode - please try again later."); } boolean useDDLSchema = VoltDB.instance().getCatalogContext().cluster.getUseddlschema(); if (!useDDLSchema) { return makeQuickResponse( ClientResponse.GRACEFUL_FAILURE, "Cluster is configured to use @UpdateApplicationCatalog " + "to change application schema. Use of @UpdateClasses is forbidden."); } logCatalogUpdateInvocation("@UpdateClasses"); return updateApplication("@UpdateClasses", jarfileBytes, classesToDeleteSelector, new String[0], new ArrayList<>(), null, false, useDDLSchema); }

Target:
public CompletableFuture<ClientResponse> run(byte[] jarfileBytes, String classesToDeleteSelector) { if (!allowPausedModeWork(false, isAdminConnection())) { return makeQuickResponse( ClientResponse.SERVER_UNAVAILABLE, "Server is paused and is available in read-only mode - please try again later."); } boolean useDDLSchema = VoltDB.instance().getCatalogContext().cluster.getUseddlschema(); if (!useDDLSchema) { return makeQuickResponse( ClientResponse.GRACEFUL_FAILURE, "Cluster is configured to use @UpdateApplicationCatalog " + "to change application schema. Use of @UpdateClasses is forbidden."); } logCatalogUpdateInvocation("@UpdateClasses"); return updateApplication("@UpdateClasses", jarfileBytes, classesToDeleteSelector, new String[0], Collections.emptyList(), null, false, useDDLSchema); }
Source:
public GatewayResponse authorise(AuthorisationGatewayRequest request) { logger.info("Calling Stripe for authorisation of charge [{}]", request.getChargeExternalId()); Response sourceResponse = client.postRequest( request.getGatewayAccount(), AUTHORISE, URI.create(stripeGatewayConfig.getUrl() + "/v1/tokens"), stripeUrlEncodedSourcePayload(request), getAuthHeaderValue(), APPLICATION_FORM_URLENCODED_TYPE); String token = sourceResponse.readEntity(Map.class).get("id").toString(); Response authorisationResponse = client.postRequest( request.getGatewayAccount(), AUTHORISE, URI.create(stripeGatewayConfig.getUrl() + "/v1/charges"), stripeAuthoriseJsonPayload(request, token), getAuthHeaderValue(), APPLICATION_JSON_TYPE); GatewayResponse.GatewayResponseBuilder<BaseResponse> responseBuilder = GatewayResponse.GatewayResponseBuilder.responseBuilder(); return responseBuilder.withResponse(StripeAuthorisationResponse.of(authorisationResponse)).build(); }

Target:
public GatewayResponse authorise(AuthorisationGatewayRequest request) { logger.info("Calling Stripe for authorisation of charge [{}]", request.getChargeExternalId()); Response sourceResponse = client.postRequest( request.getGatewayAccount(), AUTHORISE, URI.create(stripeGatewayConfig.getUrl() + "/v1/tokens"), sourcePayload(request), getAuthHeaderValue(), APPLICATION_FORM_URLENCODED_TYPE); String token = sourceResponse.readEntity(Map.class).get("id").toString(); Response authorisationResponse = client.postRequest( request.getGatewayAccount(), AUTHORISE, URI.create(stripeGatewayConfig.getUrl() + "/v1/charges"), authorisePayload(request, token), getAuthHeaderValue(), APPLICATION_FORM_URLENCODED_TYPE); GatewayResponse.GatewayResponseBuilder<BaseResponse> responseBuilder = GatewayResponse.GatewayResponseBuilder.responseBuilder(); return responseBuilder.withResponse(StripeAuthorisationResponse.of(authorisationResponse)).build(); }
Source:
private void writeRecoveryStates(CorfuPayloadMsg<LogRecoveryStateWriteMsg> msg, ChannelHandlerContext ctx, IServerRouter r) { LogRecoveryStateWriteMsg recoveryState = msg.getPayload(); log.debug("writeRecoveryStates: Writing log entries, garbage entries, " + "compaction mark: {}", recoveryState.getLogEntries().size(), recoveryState.getLogEntries().size(), recoveryState.getCompactionMark()); batchWriter.addTask(RECOVERY_STATE_WRITE, msg) .thenRunAsync(() -> { streamLog.updateCommittedTail(recoveryState.getCompactionMark()); r.sendResponse(ctx, msg, CorfuMsgType.WRITE_OK.msg()); }) .exceptionally(ex -> { handleException(ex, ctx, msg, r); return null; }); }

Target:
private void writeRecoveryStates(CorfuPayloadMsg<LogRecoveryStateWriteMsg> msg, ChannelHandlerContext ctx, IServerRouter r) { LogRecoveryStateWriteMsg recoveryState = msg.getPayload(); log.debug("writeRecoveryStates: Writing log entries, garbage entries, " + "compaction mark: {}", recoveryState.getLogEntries().size(), recoveryState.getLogEntries().size(), recoveryState.getCompactionMark()); streamLog.updateGlobalCompactionMark(recoveryState.getCompactionMark()); batchWriter.addTask(RECOVERY_STATE_WRITE, msg) .thenRunAsync(() -> r.sendResponse(ctx, msg, CorfuMsgType.WRITE_OK.msg())) .exceptionally(ex -> { handleException(ex, ctx, msg, r); return null; }); }
Source:
public void refreshTimeEstimation(List<ScriptGeneratorAction> scriptGenContent, ScriptDefinitionWrapper scriptDefinition) throws InterruptedException, ExecutionException, PythonNotReadyException { if (pythonReady) { CompletableFuture.supplyAsync(() -> { try { return scriptDefinitionsWrapper.estimateTime(convertScriptGenContentToPython(scriptGenContent), scriptDefinition); } catch (Py4JException e) { LOG.error(e); handlePythonReadinessChange(false); return false; } }, THREAD).thenAccept(timeEstimate -> firePropertyChange(TIME_ESTIMATE_PROPERTY, null, timeEstimate) ); } else { handlePythonReadinessChange(false); throw new PythonNotReadyException("When getting time estimation"); } if (!pythonReady) { throw new PythonNotReadyException("When getting time estimation"); } }

Target:
public void refreshTimeEstimation(List<ScriptGeneratorAction> scriptGenContent, ScriptDefinitionWrapper scriptDefinition) throws InterruptedException, ExecutionException, PythonNotReadyException { if (pythonReady) { CompletableFuture.supplyAsync(() -> { try { return scriptDefinitionsWrapper.estimateTime(convertScriptGenContentToPython(scriptGenContent), scriptDefinition); } catch (Py4JException e) { LOG.error(e); handlePythonReadinessChange(false); return false; } }, THREAD).thenAccept(timeEstimate -> firePropertyChange(TIME_ESTIMATE_PROPERTY, null, timeEstimate) ); } else { handlePythonReadinessChange(false); throw new PythonNotReadyException("When getting time estimation"); } }
Source:
private void handleTokenQuery(CorfuPayloadMsg<TokenRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { TokenRequest req = msg.getPayload(); List<UUID> streams = req.getStreams(); List<Long> streamTails; Token token; if (req.getStreams().isEmpty()) { token = new Token(sequencerEpoch, globalLogTail - 1); streamTails = Collections.emptyList(); } else { token = new Token(sequencerEpoch, globalLogTail - 1); streamTails = new ArrayList<>(streams.size()); for (UUID stream : streams) { streamTails.add(streamTailToGlobalTailMap.getOrDefault(stream, Address.NON_EXIST)); } } r.sendResponse(ctx, msg, CorfuMsgType.TOKEN_RES.payloadMsg(new TokenResponse( TokenType.NORMAL, TokenResponse.NO_CONFLICT_KEY, TokenResponse.NO_CONFLICT_STREAM, token, Collections.emptyMap(), streamTails))); }

Target:
private void handleTokenQuery(CorfuPayloadMsg<TokenRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { TokenRequest req = msg.getPayload(); List<UUID> streams = req.getStreams(); Map<UUID, Long> streamTails; Token token; if (req.getStreams().isEmpty()) { token = new Token(sequencerEpoch, globalLogTail - 1); streamTails = Collections.emptyMap(); } else { token = new Token(sequencerEpoch, globalLogTail - 1); streamTails = new HashMap<>(streams.size()); for (UUID stream : streams) { streamTails.put(stream, streamTailToGlobalTailMap.getOrDefault(stream, Address.NON_EXIST)); } } r.sendResponse(ctx, msg, CorfuMsgType.TOKEN_RES.payloadMsg(new TokenResponse( TokenType.NORMAL, TokenResponse.NO_CONFLICT_KEY, TokenResponse.NO_CONFLICT_STREAM, token, Collections.emptyMap(), streamTails))); }
Source:
private SecurityGroup(SecurityGroup securityGroup) { this( securityGroup.id, securityGroup.tenantId, securityGroup.name, securityGroup.description, securityGroup.securityGroupRules ); }

Target:
private SecurityGroup(SecurityGroup securityGroup) { this(securityGroup.id, securityGroup.tenantId, securityGroup.name, securityGroup.description, securityGroup.rules ); }
Source:
protected ExpressionRewriteRuleSet(ExpressionRewriteRule rewrite) { this.rewriter = rewrite; }

Target:
public ExpressionRewriteRuleSet(ExpressionRewriteRule rewrite) { this.rewriter = rewrite; }
Source:
public static <E extends Exception> void assertException( ThrowingAction<E> f, Class typeOfException ) throws Exception { try { f.apply(); fail( "Expected exception of type " + typeOfException + ", but no exception was thrown" ); } catch ( Exception e ) { if ( !typeOfException.isInstance( e ) ) { fail( "Got unexpected exception " + e.getClass() + "\nExpected: " + typeOfException ); } } }

Target:
public static <E extends Exception> void assertException( ThrowingAction<E> f, Class typeOfException ) throws Exception { assertException( f, typeOfException, null ); }
Source:
private void trackAATestCourseOutline() { if (!isVideoMode && environment.getConfig().getFirebaseConfig().isEnabled()) { final FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance(); firebaseRemoteConfig.fetchAndActivate().addOnCompleteListener(task -> { final String group = firebaseRemoteConfig.getString(Analytics.Keys.AA_EXPERIMENT); if (!TextUtils.isEmpty(group) && environment.getLoginPrefs().getCurrentUserProfile() != null) { final Map<String, String> values = new HashMap<>(); values.put(Analytics.Keys.EXPERIMENT, Analytics.Keys.AA_EXPERIMENT); values.put(Analytics.Keys.GROUP, group); values.put(Analytics.Keys.USER_ID, environment.getLoginPrefs().getCurrentUserProfile().id.toString()); values.put(Analytics.Keys.COURSE_ID, courseData.getCourse().getId()); environment.getAnalyticsRegistry().trackExperimentParams(Analytics.Events.MOBILE_EXPERIMENT_EVALUATED, values); } }); } }

Target:
private void trackAATestCourseOutline() { if (!isVideoMode && environment.getConfig().getFirebaseConfig().isEnabled()) { final FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance(); firebaseRemoteConfig.fetchAndActivate().addOnCompleteListener(task -> { final String group = firebaseRemoteConfig.getString(Analytics.Keys.AA_EXPERIMENT); final ProfileModel profileModel = environment.getLoginPrefs().getCurrentUserProfile(); if (!TextUtils.isEmpty(group) && profileModel != null) { final Map<String, String> values = new HashMap<>(); values.put(Analytics.Keys.EXPERIMENT, Analytics.Keys.AA_EXPERIMENT); values.put(Analytics.Keys.GROUP, group); values.put(Analytics.Keys.USER_ID, profileModel.id.toString()); values.put(Analytics.Keys.COURSE_ID, courseData.getCourse().getId()); environment.getAnalyticsRegistry().trackExperimentParams(Analytics.Events.MOBILE_EXPERIMENT_EVALUATED, values); } }); } }
Source:
private void detachOrCloseSpans(HttpServletRequest request, HttpServletResponse response, Span spanFromRequest, Throwable exception) { if (spanFromRequest != null) { addResponseTags(response, exception); if (spanFromRequest.hasSavedSpan() && requestHasAlreadyBeenHandled(request)) { reportParentSpan(spanFromRequest.getSavedSpan()); } else if (!requestHasAlreadyBeenHandled(request)) { spanFromRequest = this.tracer.close(spanFromRequest); } reportParentSpan(spanFromRequest); if (httpStatusSuccessful(response)) { if (log.isDebugEnabled()) { log.debug("Closing the span " + spanFromRequest + " since the response was successful"); } this.tracer.close(spanFromRequest); } else if (errorAlreadyHandled(request)) { if (log.isDebugEnabled()) { log.debug( "Won't detach the span " + spanFromRequest + " since error has already been handled"); } } else { if (log.isDebugEnabled()) { log.debug("Detaching the span " + spanFromRequest + " since the response was unsuccessful"); } this.tracer.detach(spanFromRequest); } } }

Target:
private void detachOrCloseSpans(HttpServletRequest request, HttpServletResponse response, Span spanFromRequest, Throwable exception) { if (spanFromRequest != null) { addResponseTags(response, exception); if (spanFromRequest.hasSavedSpan() && requestHasAlreadyBeenHandled(request)) { recordParentSpan(spanFromRequest.getSavedSpan()); } else if (!requestHasAlreadyBeenHandled(request)) { spanFromRequest = this.tracer.close(spanFromRequest); } recordParentSpan(spanFromRequest); if (httpStatusSuccessful(response)) { if (log.isDebugEnabled()) { log.debug("Closing the span " + spanFromRequest + " since the response was successful"); } this.tracer.close(spanFromRequest); } else if (errorAlreadyHandled(request)) { if (log.isDebugEnabled()) { log.debug( "Won't detach the span " + spanFromRequest + " since error has already been handled"); } } else { if (log.isDebugEnabled()) { log.debug("Detaching the span " + spanFromRequest + " since the response was unsuccessful"); } this.tracer.detach(spanFromRequest); } } }
Source:
private String addAttribute(KafkaMetric metric) { try { MetricName metricName = metric.metricName(); if (metricName.tags().containsKey(DO_NOT_REPORT_TAG)) { return null; } String mBeanName = getMBeanName(prefix, metricName); if (!this.mbeans.containsKey(mBeanName)) mbeans.put(mBeanName, new KafkaMbean(mBeanName)); KafkaMbean mbean = this.mbeans.get(mBeanName); mbean.setAttribute(metricName.name(), metric); return mBeanName; } catch (JMException e) { throw new KafkaException("Error creating mbean attribute for metricName :" + metric.metricName(), e); } }

Target:
private String addAttribute(KafkaMetric metric) { try { MetricName metricName = metric.metricName(); String mBeanName = getMBeanName(prefix, metricName); if (!this.mbeans.containsKey(mBeanName)) mbeans.put(mBeanName, new KafkaMbean(mBeanName)); KafkaMbean mbean = this.mbeans.get(mBeanName); mbean.setAttribute(metricName.name(), metric); return mBeanName; } catch (JMException e) { throw new KafkaException("Error creating mbean attribute for metricName :" + metric.metricName(), e); } }
Source:
private Map<String, String> getExtensionVersions() { final Injector injector = Initialization.makeStartupInjector(); final ExtensionsConfig config = injector.getInstance(ExtensionsConfig.class); final List<DruidModule> druidModules = Initialization.getFromExtensions(config, DruidModule.class); Map<String, String> moduleVersions = new HashMap<>(); for (DruidModule module : druidModules) { Package pkg = module.getClass().getPackage(); moduleVersions.put(pkg.getImplementationTitle(), pkg.getImplementationVersion()); } return moduleVersions; }

Target:
private static List<ModuleVersion> getExtensionVersions() { final Injector injector = Initialization.makeStartupInjector(); final ExtensionsConfig config = injector.getInstance(ExtensionsConfig.class); final List<DruidModule> druidModules = Initialization.getFromExtensions(config, DruidModule.class); List<ModuleVersion> moduleVersions = new ArrayList<>(); for (DruidModule module : druidModules) { String artifact = module.getClass().getPackage().getImplementationTitle(); String version = module.getClass().getPackage().getImplementationVersion(); ModuleVersion moduleVersion; if (artifact != null) { moduleVersion = new ModuleVersion(module.getClass().getCanonicalName(), artifact, version); } else { moduleVersion = new ModuleVersion(module.getClass().getCanonicalName()); } moduleVersions.add(moduleVersion); } return moduleVersions; }
Source:
private long createToken(Token token, String tokenType) { try { return tokenDAO.create(token); } catch (Exception ex) { String msg = "Error linking " + tokenType + " account"; LOG.error(msg, ex); throw new CustomWebApplicationException(msg, HttpStatus.SC_BAD_REQUEST); } }

Target:
private long createToken(Token token, String tokenType) { try { return tokenDAO.create(token); } catch (Exception ex) { String msg = "Error linking " + tokenType + " account"; LOG.error(msg, ex); throw new CustomWebApplicationException(msg, HttpStatus.SC_INTERNAL_SERVER_ERROR); } }
Source:
public long copyStoreFiles( CatchupAddressProvider catchupAddressProvider, StoreId expectedStoreId, StoreFileStreams storeFileStreams, Supplier<TerminationCondition> requestWiseTerminationCondition ) throws StoreCopyFailedException { try { PrepareStoreCopyResponse prepareStoreCopyResponse = listFiles( catchupAddressProvider.primary(), expectedStoreId, storeFileStreams ); copyFilesIndividually( prepareStoreCopyResponse, expectedStoreId, catchupAddressProvider, storeFileStreams, requestWiseTerminationCondition ); copyLuceneSnapshotIndividually( prepareStoreCopyResponse, expectedStoreId, catchupAddressProvider, storeFileStreams, requestWiseTerminationCondition ); return prepareStoreCopyResponse.lastTransactionId(); } catch ( CatchupAddressResolutionException | CatchUpClientException e ) { throw new StoreCopyFailedException( e ); } }

Target:
long copyStoreFiles( CatchupAddressProvider catchupAddressProvider, StoreId expectedStoreId, StoreFileStreams storeFileStreams, Supplier<TerminationCondition> requestWiseTerminationCondition ) throws StoreCopyFailedException { try { PrepareStoreCopyResponse prepareStoreCopyResponse = listFiles( catchupAddressProvider.primary(), expectedStoreId, storeFileStreams ); copyFilesIndividually( prepareStoreCopyResponse, expectedStoreId, catchupAddressProvider, storeFileStreams, requestWiseTerminationCondition ); copyIndexSnapshotIndividually( prepareStoreCopyResponse, expectedStoreId, catchupAddressProvider, storeFileStreams, requestWiseTerminationCondition ); return prepareStoreCopyResponse.lastTransactionId(); } catch ( CatchupAddressResolutionException | CatchUpClientException e ) { throw new StoreCopyFailedException( e ); } }
Source:
public MarshallableEntry loadEntry(Object key) throws PersistenceException { V value = loadValue(key); if (value != null) { Duration expiry = Expiration.getExpiry(expiryPolicy, Expiration.Operation.CREATION); long now = ctx.getTimeService().wallClockTime(); if (expiry == null || expiry.isEternal()) { return ctx.getMarshallableEntryFactory().create(key, value); } else { long exp = now + expiry.getTimeUnit().toMillis(expiry.getDurationAmount()); JCacheInternalMetadata meta = new JCacheInternalMetadata(now, exp); return ctx.getMarshallableEntryFactory().create(key, value, meta, now, 0); } } return null; }

Target:
public MarshallableEntry<K,V> loadEntry(Object key) throws PersistenceException { V value = loadValue(key); if (value != null) { Duration expiry = Expiration.getExpiry(expiryPolicy, Expiration.Operation.CREATION); if (expiry == null || expiry.isEternal()) { return ctx.<K,V>getMarshallableEntryFactory().create(key, value); } else { long now = ctx.getTimeService().wallClockTime(); long exp = now + expiry.getTimeUnit().toMillis(expiry.getDurationAmount()); Metadata meta = new EmbeddedMetadata.Builder().lifespan(exp - now).build(); return ctx.<K,V>getMarshallableEntryFactory().create(key, value, meta, now, -1); } } return null; }
Source:
private static Set<Class<?>> getAllAnnotatedClasses() { Set<Class<?>> metadataStoreResult = ClassScanner.getAnnotatedClasses(METADATA_STORE_ANNOTATIONS); Set<Class<?>> entityResult = ClassScanner.getAnnotatedClasses(METADATA_STORE_ENTITY_ANNOTATION); Set<Class<?>> includeResult = ClassScanner.getAnnotatedClasses(Include.class); entityResult.retainAll(includeResult); metadataStoreResult.addAll(entityResult); return metadataStoreResult; }

Target:
private static Set<Class<?>> getAllAnnotatedClasses() { Set<Class<?>> metadataStoreResult = ClassScanner.getAnnotatedClasses(METADATA_STORE_ANNOTATIONS, (clazz) -> { if (clazz.getAnnotation(Entity.class) != null) { if (clazz.getAnnotation(Include.class) != null) { return true; } return false; } return true; }); return metadataStoreResult; }
Source:
public void testOperatorDropdownWhenOperatorCanBeSet() { final String operatorPlaceholder = "--- please choose ---"; registerFakeProvider(); when(translationService.format(GuidedDecisionTableErraiConstants.OperatorPage_NoOperator)).thenReturn("(no operator)"); when(presenter.getDataModelOracle()).thenReturn(oracle); when(plugin.getFactField()).thenReturn("factField"); when(plugin.editingCol()).thenReturn(editingCol); when(plugin.operatorPlaceholder()).thenReturn(operatorPlaceholder); when(editingCol.getOperator()).thenReturn(""); mockGetOperatorCompletionsToReturn(OperatorsOracle.STANDARD_OPERATORS); spyOperatorsDropdown(); page.operatorDropdown(widget -> { assertTrue(widget instanceof CEPOperatorsDropdown); final CEPOperatorsDropdown dropdown = (CEPOperatorsDropdown) widget; verify(dropdown.getBox()).setSelectedIndex(0); verify(dropdown.getBox()).addChangeHandler(any()); verify(dropdown).addPlaceholder(operatorPlaceholder, operatorPlaceholder); verify(dropdown).insertItem("(no operator)", "", 1); }); }

Target:
public void testOperatorDropdownWhenOperatorCanBeSet() { final String operatorPlaceholder = "--- please choose ---"; registerFakeProvider(); when(translationService.format(GuidedDecisionTableErraiConstants.OperatorPage_NoOperator)).thenReturn("(no operator)"); when(presenter.getDataModelOracle()).thenReturn(oracle); when(plugin.getFactField()).thenReturn("factField"); when(plugin.operatorPlaceholder()).thenReturn(operatorPlaceholder); when(editingCol.getOperator()).thenReturn(""); mockGetOperatorCompletionsToReturn(OperatorsOracle.STANDARD_OPERATORS); spyOperatorsDropdown(); mockListBox(operatorPlaceholder, "", "equal to"); page.operatorDropdown(widget -> { assertTrue(widget instanceof CEPOperatorsDropdown); final CEPOperatorsDropdown dropdown = (CEPOperatorsDropdown) widget; verify(listBox).setSelectedIndex(1); verify(listBox).addChangeHandler(any()); verify(dropdown).addPlaceholder(operatorPlaceholder, operatorPlaceholder); verify(dropdown).insertItem("(no operator)", "", 1); }); }