auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void main(String[] args) { if (Platform.getCurrent().equals(org.controlsfx.tools.Platform.OSX)) { try { AppleHandlers.getAppleHandlers().addOpenFileListener(list -> { try { openFileHandler.get().accept(list); } catch (Exception e) { LOG.error("exception handling file open event", e); throw new RuntimeException(e); } }); } catch (Throwable e) { LOG.error("exception adding OSX file open handler", e); } } final Optional<RemoteInstance> remoteInstance = SingleInstanceManager.getRemoteInstance(MainApplication.APPLICATION_KEY); if (remoteInstance.isPresent()) { try (RemoteInstance instance = remoteInstance.get()) { LOG.info("An instance of Cryptomator is already running at {}.", instance.getRemotePort()); for (int i = 0; i < args.length; i++) { remoteInstance.get().sendMessage(args[i], 1000); } } catch (Exception e) { LOG.error("Error forwarding arguments to remote instance", e); } } else { Application.launch(MainApplication.class, args); } }

Target:
public static void main(String[] args) { if (SystemUtils.IS_OS_MAC_OSX) { try { AppleHandlers.getAppleHandlers().addOpenFileListener(file -> { try { OPEN_FILE_HANDLER.get().accept(file); } catch (Exception e) { LOG.error("exception handling file open event", e); throw new RuntimeException(e); } }); } catch (RuntimeException e) { LOG.error("exception adding OSX file open handler", e); } } final Optional<RemoteInstance> remoteInstance = SingleInstanceManager.getRemoteInstance(MainApplication.APPLICATION_KEY); if (remoteInstance.isPresent()) { try (RemoteInstance instance = remoteInstance.get()) { LOG.info("An instance of Cryptomator is already running at {}.", instance.getRemotePort()); for (int i = 0; i < args.length; i++) { remoteInstance.get().sendMessage(args[i], 1000); } } catch (Exception e) { LOG.error("Error forwarding arguments to remote instance", e); } } else { Application.launch(MainApplication.class, args); } }
Source:
private boolean locateConf() { this.conf_path = System.getProperty("HDFS_CONF"); if (this.conf_path == null) { Properties prop = new Properties(); String propFilePath = "../vxquery-server/src/main/resources/conf/cluster.properties"; try { prop.load(new FileInputStream(propFilePath)); } catch (FileNotFoundException e) { propFilePath = "vxquery-server/src/main/resources/conf/cluster.properties"; try { prop.load(new FileInputStream(propFilePath)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } this.conf_path = prop.getProperty("HDFS_CONF"); if (this.conf_path == null) { return false; } return true; } return true; }

Target:
private boolean locateConf() { if (this.conf_path == null) { Properties prop = new Properties(); String propFilePath = "../vxquery-server/src/main/resources/conf/cluster.properties"; nodeXMLfile = new File("../vxquery-server/src/main/resources/conf/cluster.xml"); if(!nodeXMLfile.exists()) { nodeXMLfile = new File("vxquery-server/src/main/resources/conf/cluster.xml"); if(!nodeXMLfile.exists()) { nodeXMLfile = new File("vxquery-server/src/main/resources/conf/local.xml"); } if(!nodeXMLfile.exists()) { nodeXMLfile = new File("../vxquery-server/src/main/resources/conf/local.xml"); } } try { prop.load(new FileInputStream(propFilePath)); } catch (FileNotFoundException e) { propFilePath = "vxquery-server/src/main/resources/conf/cluster.properties"; try { prop.load(new FileInputStream(propFilePath)); } catch (IOException e1) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.severe(e1.getMessage()); } } } catch (IOException e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.severe(e.getMessage()); } return false; } this.conf_path = prop.getProperty("HDFS_CONF"); if (this.conf_path == null) { this.conf_path = System.getenv("HADOOP_CONF_DIR"); return this.conf_path != null; } return this.conf_path != null; } return this.conf_path != null; }
Source:
public synchronized void stop() { if (container != null) { try { LOGGER.info("Shutting down the container: of stream processor: {}.", container, processorId); container.shutdown(); LOGGER.info("Waiting milliseconds for the container: to shutdown.", taskShutdownMs, container); jcContainerShutdownLatch.await(taskShutdownMs, TimeUnit.MILLISECONDS); if (executorService != null) { executorService.shutdown(); executorService.awaitTermination(taskShutdownMs, TimeUnit.MILLISECONDS); if (!executorService.isShutdown()) { LOGGER.info("Forcefully shutting down the executor service of the container: {}.", container); executorService.shutdownNow(); } } } catch (Exception exception) { LOGGER.info(String.format("Shutdown of container: %s threw an exception.", container), exception); } } stopJobCoordinator(); }

Target:
public synchronized void stop() { boolean containerShutdownInvoked = false; if (container != null) { try { LOGGER.info("Shutting down the container: of stream processor: {}.", container, processorId); container.shutdown(); LOGGER.info("Waiting milliseconds for the container: to shutdown.", taskShutdownMs, container); containerShutdownInvoked = true; } catch (Exception exception) { LOGGER.error(String.format("Ignoring the exception during the shutdown of container: %s.", container), exception); } } if (!containerShutdownInvoked) { LOGGER.info("Shutting down JobCoordinator from StreamProcessor"); jobCoordinator.stop(); } }
Source:
protected void init() { if (properties == null) { properties = new DescribableList<AbstractFolderProperty<?>,AbstractFolderPropertyDescriptor>(this); } for (AbstractFolderProperty p : properties) { p.setOwner(this); } if (icon == null) { icon = new StockFolderIcon(); } else { icon.setOwner(this); } if (views == null) { views = new CopyOnWriteArrayList<View>(); } if (views.isEmpty()) { try { initViews(views); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to set up the initial view", e); } } if (viewsTabBar == null) { viewsTabBar = new DefaultViewsTabBar(); } if (primaryView == null) { primaryView = views.get(0).getViewName(); } viewGroupMixIn = new ViewGroupMixIn(this) { @Override protected List<View> views() { return views; } @Override protected String primaryView() { return primaryView; } @Override protected void primaryView(String name) { primaryView = name; } }; if (healthMetrics == null) { List<FolderHealthMetric> metrics = new ArrayList<FolderHealthMetric>(); for (FolderHealthMetricDescriptor d : FolderHealthMetricDescriptor.all()) { FolderHealthMetric metric = d.createDefault(); if (metric != null) { metrics.add(metric); } } healthMetrics = new DescribableList<FolderHealthMetric, FolderHealthMetricDescriptor>(this, metrics); } }

Target:
protected void init() { if (properties == null) { properties = new DescribableList<AbstractFolderProperty<?>,AbstractFolderPropertyDescriptor>(this); } else { properties.setOwner(this); } for (AbstractFolderProperty p : properties) { p.setOwner(this); } if (icon == null) { icon = new StockFolderIcon(); } icon.setOwner(this); if (views == null) { views = new CopyOnWriteArrayList<View>(); } if (viewsTabBar == null) { viewsTabBar = new DefaultViewsTabBar(); } viewGroupMixIn = new ViewGroupMixIn(this) { @Override protected List<View> views() { return views; } @Override protected String primaryView() { return primaryView == null ? views.get(0).getViewName() : primaryView; } @Override protected void primaryView(String name) { primaryView = name; } }; if (views.isEmpty()) { try { initViews(views); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to set up the initial view", e); } } if (healthMetrics == null) { List<FolderHealthMetric> metrics = new ArrayList<FolderHealthMetric>(); for (FolderHealthMetricDescriptor d : FolderHealthMetricDescriptor.all()) { FolderHealthMetric metric = d.createDefault(); if (metric != null) { metrics.add(metric); } } healthMetrics = new DescribableList<FolderHealthMetric, FolderHealthMetricDescriptor>(this, metrics); } }
Source:
protected void increaseCount(final String key) { if (ScenarioContext.Current().get(key) == null) { ScenarioContext.Current().put(key, 1); } else { ScenarioContext.Current().put(key, (Integer) ScenarioContext.Current().get(key) + 1); } }

Target:
private void increaseCount(final String key) { if (ScenarioContext.Current().get(key) == null) { ScenarioContext.Current().put(key, 1); } else { ScenarioContext.Current().put(key, (Integer) ScenarioContext.Current().get(key) + 1); } }
Source:
private Font getOrderLabelFont() { FontData[] fontData = JFaceResources.getFontRegistry() .getFontData(org.eclipse.fordiac.ide.util.preferences.PreferenceConstants.DIAGRAM_FONT).clone(); for (int i = 0; i < fontData.length; ++i) { fontData[i].setHeight(TRANSITON_ORDER_LABEL_FONT_SIZE); } JFaceResources.getFontRegistry().put(TRANSITION_ORDER_LABEL_FONT, fontData); return JFaceResources.getFont(TRANSITION_ORDER_LABEL_FONT); }

Target:
private Font getOrderLabelFont() { FontData[] fontData = JFaceResources.getFontRegistry() .getFontData(org.eclipse.fordiac.ide.util.preferences.PreferenceConstants.DIAGRAM_FONT).clone(); Arrays.stream(fontData).forEach(fd -> fd.setHeight(TRANSITON_ORDER_LABEL_FONT_SIZE)); JFaceResources.getFontRegistry().put(TRANSITION_ORDER_LABEL_FONT, fontData); return JFaceResources.getFont(TRANSITION_ORDER_LABEL_FONT); }
Source:
protected void executeVmCommand() { Collection<DiskImage> vmDisks = super.getAdjustedDiskImagesFromConfiguration(); for (DiskImage diskImage : vmDisks) { MoveOrCopyImageGroupParameters copyParams = createCopyParams(diskImage); ActionReturnValue returnValue = runInternalAction(ActionType.CopyImageGroup, copyParams, cloneContextAndDetachFromParent()); if (!returnValue.getSucceeded()) { setSucceeded(false); return; } getParameters().getSrcDiskIdToTargetDiskIdMapping() .put(diskImage.getId(), copyParams.getDestImageGroupId()); } persistCommandIfNeeded(); setSucceeded(true); }

Target:
protected void executeVmCommand() { Collection<DiskImage> vmDisks = super.getAdjustedDiskImagesFromConfiguration(); for (DiskImage diskImage : vmDisks) { MoveOrCopyImageGroupParameters copyParams = createCopyParams(diskImage); ActionReturnValue returnValue = runInternalAction(ActionType.CopyImageGroup, copyParams, createStepsContext()); if (!returnValue.getSucceeded()) { setSucceeded(false); return; } getParameters().getSrcDiskIdToTargetDiskIdMapping() .put(diskImage.getId(), copyParams.getDestImageGroupId()); } persistCommandIfNeeded(); setSucceeded(true); }
Source:
private CsvRowSerializationSchema( RowTypeInfo typeInfo, CsvSchema csvSchema) { this.typeInfo = typeInfo; this.runtimeConverter = createRowRuntimeConverter(typeInfo, true); this.csvMapper = new CsvMapper(); this.csvSchema = csvSchema.withLineSeparator(""); this.objectWriter = csvMapper.writer(this.csvSchema); }

Target:
private CsvRowSerializationSchema( RowTypeInfo typeInfo, CsvSchema csvSchema) { this.typeInfo = typeInfo; this.runtimeConverter = createRowRuntimeConverter(typeInfo, true); this.csvMapper = new CsvMapper(); this.csvSchema = csvSchema; this.objectWriter = csvMapper.writer(csvSchema); }
Source:
public void testConnectorSendsHelloVerifyRequestWithoutCreatingSession() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final List<Record> receivedRecords = new ArrayList<>(); InetSocketAddress endpoint = new InetSocketAddress(12000); LatchDecrementingDataHandler handler = new LatchDecrementingDataHandler(latch) { @Override public boolean process(InetSocketAddress endpoint, final byte[] data) { receivedRecords.addAll(Record.fromByteArray(data, endpoint, null)); return true; } }; UdpConnector rawClient = new UdpConnector(endpoint.getPort(), handler); try{ rawClient.start(); ClientHello clientHello = createClientHello(); rawClient.sendRecord(serverHelper.serverEndpoint, DtlsTestTools.newDTLSRecord(ContentType.HANDSHAKE.getCode(), 0, 0, clientHello.toByteArray())); Assert.assertTrue(latch.await(MAX_TIME_TO_WAIT_SECS, TimeUnit.SECONDS)); Assert.assertFalse(receivedRecords.isEmpty()); Record record = receivedRecords.get(0); Assert.assertThat("Expected HANDSHAKE message from server", record.getType(), is(ContentType.HANDSHAKE)); HandshakeMessage handshake = (HandshakeMessage) record.getFragment(); Assert.assertThat("Expected HELLO_VERIFY_REQUEST from server", handshake.getMessageType(), is(HandshakeType.HELLO_VERIFY_REQUEST)); Assert.assertNull("Server should not have created session for CLIENT_HELLO containging no cookie", serverHelper.serverConnectionStore.get(endpoint)); } finally { rawClient.stop(); } }

Target:
public void testConnectorSendsHelloVerifyRequestWithoutCreatingSession() throws Exception { final CountDownLatch latch = new CountDownLatch(1); final List<Record> receivedRecords = new ArrayList<>(); InetSocketAddress endpoint = new InetSocketAddress(12000); LatchDecrementingDataHandler handler = new LatchDecrementingDataHandler(latch) { @Override public boolean process(InetSocketAddress endpoint, byte[] data) { receivedRecords.addAll(Record.fromByteArray(data, endpoint, null)); return true; } }; UdpConnector rawClient = new UdpConnector(endpoint.getPort(), handler); try{ rawClient.start(); ClientHello clientHello = createClientHello(); rawClient.sendRecord(serverHelper.serverEndpoint, DtlsTestTools.newDTLSRecord(ContentType.HANDSHAKE.getCode(), 0, 0, clientHello.toByteArray())); Assert.assertTrue(latch.await(MAX_TIME_TO_WAIT_SECS, TimeUnit.SECONDS)); Assert.assertFalse(receivedRecords.isEmpty()); Record record = receivedRecords.get(0); Assert.assertThat("Expected HANDSHAKE message from server", record.getType(), is(ContentType.HANDSHAKE)); HandshakeMessage handshake = (HandshakeMessage) record.getFragment(); Assert.assertThat("Expected HELLO_VERIFY_REQUEST from server", handshake.getMessageType(), is(HandshakeType.HELLO_VERIFY_REQUEST)); Assert.assertNull("Server should not have created session for CLIENT_HELLO containging no cookie", serverHelper.serverConnectionStore.get(endpoint)); } finally { rawClient.stop(); } }
Source:
public void createRecommendationsResponseShouldReturnAResult() throws Exception { String string = Utils.getTestResource("response.recommendations.home_page_1.json"); RecommendationsResponse response = ConstructorIO.createRecommendationsResponse(string); assertEquals("pod display name exists", response.getResponse().getPod().getDisplayName(), "You may also like"); assertEquals("pod display name exists", response.getResponse().getPod().getId(), "item_page_1"); assertEquals("search results exist", response.getResponse().getResults().size(), 10); assertEquals("total number of results", (int)response.getResponse().getTotalNumberOfResults(), 10); assertTrue("search result id exists", response.getResultId() != null); }

Target:
public void createRecommendationsResponseShouldReturnAResult() throws Exception { String string = Utils.getTestResource("response.recommendations.home_page_1.json"); RecommendationsResponse response = ConstructorIO.createRecommendationsResponse(string); assertEquals("pod display name exists", response.getResponse().getPod().getDisplayName(), "You may also like"); assertEquals("pod display id exists", response.getResponse().getPod().getId(), "item_page_1"); assertEquals("recommendation results exist", response.getResponse().getResults().size(), 10); assertEquals("total number of results", (int)response.getResponse().getTotalNumberOfResults(), 10); assertTrue("recommendation result id exists", response.getResultId() != null); }
Source:
public Block getRegion(int position, int length) { int positionCount = getPositionCount(); if (position < 0 || length < 0 || position + length > positionCount) { throw new IndexOutOfBoundsException(format("Invalid position range [%s, %s) in block with %s positions", position, position + length, positionCount)); } return new ArrayBlock( position + getOffsetBase(), length, getValueIsNull(), getOffsets(), getValues()); }

Target:
public Block getRegion(int position, int length) { int positionCount = getPositionCount(); checkValidRegion(positionCount, position, length); return new ArrayBlock( position + getOffsetBase(), length, getValueIsNull(), getOffsets(), getValues()); }
Source:
public void clickCancelButton() { new WebDriverWait(seleniumWebDriver, ELEMENT_TIMEOUT_SEC) .until(ExpectedConditions.visibilityOf(cancelButton)) .click(); waitRevertPanelClosed(); }

Target:
public void clickCancelButton() { seleniumWebDriverHelper.waitAndClick(cancelButton, ELEMENT_TIMEOUT_SEC); waitRevertPanelClosed(); }
Source:
protected void stopActions() { server = null; }

Target:
protected void stopActions() { if(fServer != null) { try { fServer.dispose(); } catch (IOException e) { e.printStackTrace(); } } }
Source:
public boolean accept(WindupRuleProvider ruleProvider) { Class<? extends WindupRuleProvider> cls = ruleProvider.getClass(); if(Proxies.isProxyType(cls)) cls = (Class<? extends WindupRuleProvider>) Proxies.unwrapProxyTypes(cls); return this.ruleProviders.contains(cls.getName()); }

Target:
public boolean accept(WindupRuleProvider ruleProvider) { Class<? extends WindupRuleProvider> clazz = ruleProvider.getClass(); if(Proxies.isProxyType(clazz)) clazz = (Class<? extends WindupRuleProvider>) Proxies.unwrapProxyTypes(clazz); return this.ruleProviders.contains(clazz.getName()); }
Source:
@Override public List<Pair<RelTraitSet, List<RelTraitSet>>> passThroughCorrelation(RelTraitSet nodeTraits, List<RelTraitSet> inTraits) { if (RexUtils.hasCorrelation(getProjects())) return ImmutableList.of(); return ImmutableList.of(Pair.of(nodeTraits, ImmutableList.of(inTraits.get(0).replace(TraitUtils.correlation(nodeTraits))))); }

Target:
@Override public List<Pair<RelTraitSet, List<RelTraitSet>>> passThroughCorrelation(RelTraitSet nodeTraits, List<RelTraitSet> inTraits) { Set<CorrelationId> corrIds = RexUtils.extractCorrelationIds(getProjects()); Set<CorrelationId> traitCorrIds = TraitUtils.correlation(nodeTraits).correlationIds(); if (!traitCorrIds.containsAll(corrIds)) return ImmutableList.of(); return ImmutableList.of(Pair.of(nodeTraits, ImmutableList.of(inTraits.get(0).replace(TraitUtils.correlation(nodeTraits))))); }
Source:
private static String extractDoiFromDoiUrl(String doiUrl) { String doi = doiUrl; try { URI uri = new URI(doiUrl); String[] segments = uri.getPath().split("/"); doi = segments[segments.length - 2] + "/" + segments[segments.length - 1]; } catch (URISyntaxException e) { LOG.error("Could not extract DOI. Error is " + e.getMessage(), e); } return doi; }

Target:
protected static String extractDoiFromDoiUrl(String doiUrl) { String doi = doiUrl; try { URI uri = new URI(doiUrl); doi = StringUtils.stripStart(uri.getPath(), "/"); } catch (URISyntaxException e) { LOG.error("Could not extract DOI. Error is " + e.getMessage(), e); } return doi; }
Source:
public void configure(WebSecurity web) throws Exception { super.configure(web); web.httpFirewall(allowUrlEncodedSlashHttpFirewall()); }

Target:
public void configure(WebSecurity web) throws Exception { web.httpFirewall(allowUrlEncodedSlashHttpFirewall()); }
Source:
public VSizeIndexedIntsWriter( final IOPeon ioPeon, final String filenameBase, final int maxValue ) { this.ioPeon = ioPeon; this.valueFileName = StringUtils.safeFormat("%s.values", filenameBase); this.numBytes = VSizeIndexedInts.getNumBytesForMax(maxValue); }

Target:
public VSizeIndexedIntsWriter( final IOPeon ioPeon, final String filenameBase, final int maxValue ) { this.ioPeon = ioPeon; this.valueFileName = StringUtils.format("%s.values", filenameBase); this.numBytes = VSizeIndexedInts.getNumBytesForMax(maxValue); }
Source:
public void setup() { super.setup(); archiveApi = api.getArchiveApi(); archiveUser = identity.toLowerCase() + "_test9"; archiveCounter = retry(new Predicate<Integer>() { public boolean apply(Integer value) { return archiveApi.list().size() == value; } }, 30, 1, SECONDS); }

Target:
public void setup() { super.setup(); archiveApi = api.getArchiveApi(); archiveUser = identity.toLowerCase() + "_test9"; archiveCounter = retry(new Predicate<Integer>() { public boolean apply(Integer value) { return archiveApi.list().size() == value.intValue(); } }, 30, 1, SECONDS); }
Source:
public void testNull_Event() { XDRResponseEventType eventA = new XDRResponseEventType(); XDREventType eventB = new XDREventType(); eventA = null; eventB = null; assertNull(xdrTransformHelper.transformXDRResponseToCheckPolicy(eventA)); assertNull(xdrTransformHelper.transformXDRToCheckPolicy(eventB)); }

Target:
public void testNull_Event() { assertNull(xdrTransformHelper.transformXDRResponseToCheckPolicy(null)); assertNull(xdrTransformHelper.transformXDRToCheckPolicy(null)); }
Source:
public Collection<StepExecution> handle(StepExecutionSplitter stepSplitter, StepExecution stepExecution) throws Exception { final List<Future<StepExecution>> tasks = new ArrayList<Future<StepExecution>>(); final Set<StepExecution> result = new HashSet<StepExecution>(); final ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); Set<StepExecution> partitionStepExecutions = new HashSet<StepExecution>(); int stepExecutionCount = jobRepository.getStepExecutionCount(stepExecution.getJobExecution().getJobInstance(), stepExecution.getStepName()); boolean isRestart = stepExecutionCount > 1; partitionStepExecutions = splitStepExecution(stepSplitter, stepExecution, isRestart); taskExecutor.setCorePoolSize(threads); taskExecutor.setMaxPoolSize(threads); taskExecutor.initialize(); for (final StepExecution curStepExecution : partitionStepExecutions) { final FutureTask<StepExecution> task = createTask(step, curStepExecution); try { taskExecutor.execute(task); tasks.add(task); } catch (TaskRejectedException e) { ExitStatus exitStatus = ExitStatus.FAILED .addExitDescription("TaskExecutor rejected the task for this step."); curStepExecution.setStatus(BatchStatus.FAILED); curStepExecution.setExitStatus(exitStatus); result.add(stepExecution); } } processPartitionResults(tasks, result); return result; }

Target:
public Collection<StepExecution> handle(StepExecutionSplitter stepSplitter, StepExecution stepExecution) throws Exception { final List<Future<StepExecution>> tasks = new ArrayList<Future<StepExecution>>(); final Set<StepExecution> result = new HashSet<StepExecution>(); final ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); int stepExecutionCount = jobRepository.getStepExecutionCount(stepExecution.getJobExecution().getJobInstance(), stepExecution.getStepName()); boolean isRestart = stepExecutionCount > 1; Set<StepExecution> partitionStepExecutions = splitStepExecution(stepExecution, isRestart); taskExecutor.setCorePoolSize(threads); taskExecutor.setMaxPoolSize(threads); taskExecutor.initialize(); for (final StepExecution curStepExecution : partitionStepExecutions) { final FutureTask<StepExecution> task = createTask(step, curStepExecution); try { taskExecutor.execute(task); tasks.add(task); } catch (TaskRejectedException e) { ExitStatus exitStatus = ExitStatus.FAILED .addExitDescription("TaskExecutor rejected the task for this step."); curStepExecution.setStatus(BatchStatus.FAILED); curStepExecution.setExitStatus(exitStatus); result.add(stepExecution); } } processPartitionResults(tasks, result); return result; }
Source:
public final void saveBoardAs() { Optional<String> response = promptForNewBoardName(); response.ifPresent(boardName -> { createAndOpenNewBoard(boardName, panels.getCurrentPanelInfos()); }); }

Target:
public final void saveBoardAs() { Optional<String> response = promptForBoardName(); response.ifPresent(boardName -> { createAndOpenNewBoard(boardName, panels.getCurrentPanelInfos()); }); }
Source:
public Map<Map.Entry<Long, Long>, Map.Entry<Long, Long>> apply(Set<Map.Entry<Long, Long>> request) { if (offHeapTimestampCache.cacheDescriptor.get().currentSize().get() >= offHeapTimestampCache.maxSize) { offHeapTimestampCache.taggedMetricRegistry.meter(CACHE_NUKE).mark(); offHeapTimestampCache.clear(); } CacheDescriptor cacheDescriptor = offHeapTimestampCache.cacheDescriptor.get(); try { Map<Long, Long> response = offHeapTimestampCache.persistentTimestampStore.multiGet( cacheDescriptor.storeNamespace(), request.stream().map(Map.Entry::getKey).collect(Collectors.toList())); Map<Long, Long> toWrite = ImmutableMap.copyOf(Sets.difference(request, response.entrySet())); offHeapTimestampCache.persistentTimestampStore.multiPut( cacheDescriptor.storeNamespace(), toWrite); cacheDescriptor.currentSize().addAndGet(toWrite.size()); offHeapTimestampCache.taggedMetricRegistry.counter(CACHE_SIZE).inc(toWrite.size()); } catch (SafeIllegalArgumentException exception) { log.warn("Clear called concurrently, writing failed", exception); } finally { offHeapTimestampCache.inflightRequests.clear(); } return KeyedStream.of(request.stream()).collectToMap(); }

Target:
public Map<Map.Entry<Long, Long>, Map.Entry<Long, Long>> apply(Set<Map.Entry<Long, Long>> request) { if (offHeapTimestampCache.cacheDescriptor.get().currentSize().get() >= offHeapTimestampCache.maxSize) { offHeapTimestampCache.taggedMetricRegistry.counter(CACHE_NUKE).inc(); offHeapTimestampCache.clear(); } CacheDescriptor cacheDescriptor = offHeapTimestampCache.cacheDescriptor.get(); try { Map<Long, Long> response = offHeapTimestampCache.persistentTimestampStore.multiGet( cacheDescriptor.storeNamespace(), request.stream().map(Map.Entry::getKey).collect(Collectors.toList())); Map<Long, Long> toWrite = ImmutableMap.copyOf(Sets.difference(request, response.entrySet())); offHeapTimestampCache.persistentTimestampStore.multiPut( cacheDescriptor.storeNamespace(), toWrite); cacheDescriptor.currentSize().addAndGet(toWrite.size()); } catch (SafeIllegalArgumentException exception) { log.warn("Clear called concurrently, writing failed", exception); } finally { offHeapTimestampCache.inflightRequests.clear(); } return KeyedStream.of(request.stream()).collectToMap(); }
Source:
public EntityInteractHandler getItemHandler() { return (e, item, offhand) -> { Entity entity = e.getRightClicked(); if (entity.getType() == EntityType.ZOMBIE_VILLAGER) { Player p = e.getPlayer(); if (p.getGameMode() != GameMode.CREATIVE) { ItemUtils.consumeItem(item, false); } p.playSound(p.getLocation(), Sound.ENTITY_ZOMBIE_VILLAGER_CONVERTED, 1, 1); ZombieVillager zombieVillager = (ZombieVillager) entity; zombieVillager.setConversionTime(1); if (SlimefunPlugin.getMinecraftVersion().isAtLeast(MinecraftVersion.MINECRAFT_1_15)) { zombieVillager.setConversionPlayer(p); } } else if (SlimefunPlugin.getMinecraftVersion().isAtLeast(MinecraftVersion.MINECRAFT_1_16) && entity.getType() == EntityType.ZOMBIFIED_PIGLIN) { Player p = e.getPlayer(); if (p.getGameMode() != GameMode.CREATIVE) { ItemUtils.consumeItem(item, false); } Location loc = entity.getLocation(); p.playSound(loc, Sound.ENTITY_ZOMBIE_VILLAGER_CONVERTED, 1, 1); entity.remove(); loc.getWorld().spawnEntity(loc, EntityType.PIGLIN); } }; }

Target:
public EntityInteractHandler getItemHandler() { return (e, item, offhand) -> { Entity entity = e.getRightClicked(); Player p = e.getPlayer(); if (entity instanceof ZombieVillager) { useItem(p); healZombieVillager((ZombieVillager) entity, p); } else if (SlimefunPlugin.getMinecraftVersion().isAtLeast(MinecraftVersion.MINECRAFT_1_16) && entity instanceof PigZombie) { useItem(p); healZombifiedPiglin((PigZombie) entity); } }; }
Source:
private void next(final String email) { FirebaseAuth firebaseAuth = mActivityHelper.getFirebaseAuth(); firebaseAuth.sendPasswordResetEmail(email) .addOnFailureListener( new TaskFailureLogger(TAG, "Error sending password reset email")) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mActivityHelper.dismissDialog(); new AlertDialog.Builder(RecoverPasswordActivity.this, R.style.FirebaseUI_Dialog) .setTitle(R.string.title_confirm_recover_password_activity) .setMessage(String.format( getString(R.string.confirm_recovery_body), email)) .setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface anInterface) { finish(RESULT_OK, new Intent()); } }) .setPositiveButton(android.R.string.ok, null) .show(); } }) .addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { mActivityHelper.dismissDialog(); if (e instanceof FirebaseAuthInvalidUserException) { mEmailEditText.setError(getString(R.string.error_email_does_not_exist)); } } }); }

Target:
private void next(final String email) { FirebaseAuth firebaseAuth = mActivityHelper.getFirebaseAuth(); firebaseAuth.sendPasswordResetEmail(email) .addOnFailureListener( new TaskFailureLogger(TAG, "Error sending password reset email")) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { mActivityHelper.dismissDialog(); RecoveryEmailSentDialog.show(email, getSupportFragmentManager()); } }) .addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { mActivityHelper.dismissDialog(); if (e instanceof FirebaseAuthInvalidUserException) { mEmailEditText.setError(getString(R.string.error_email_does_not_exist)); } } }); }
Source:
public void testOtherFieldsNotValidatedInImport() { ImportVmParameters parameters = createParameters(); String stringOf5000Chars = StringUtils.repeat("A", BusinessEntitiesDefinitions.GENERAL_MAX_SIZE + 1); parameters.getVm().setUserDefinedProperties(stringOf5000Chars); parameters.setImportAsNewEntity(true); ImportVmCommand command = new ImportVmCommand(parameters); Set<ConstraintViolation<ImportVmParameters>> validate = ValidationUtils.getValidator().validate(parameters, command.getValidationGroups().toArray(new Class<?>[0])); assertTrue(validate.isEmpty()); parameters.getVm().setUserDefinedProperties(stringOf5000Chars); parameters.setImportAsNewEntity(false); command = new ImportVmCommand(parameters); validate = ValidationUtils.getValidator().validate(parameters, command.getValidationGroups().toArray(new Class<?>[0])); assertTrue(validate.isEmpty()); }

Target:
public void testOtherFieldsNotValidatedInImport() { ImportVmParameters parameters = createParameters(); String stringOf5000Chars = RandomUtils.instance().nextNameString(BusinessEntitiesDefinitions.GENERAL_MAX_SIZE + 1); parameters.getVm().setUserDefinedProperties(stringOf5000Chars); parameters.setImportAsNewEntity(true); ImportVmCommand command = new ImportVmCommand(parameters); Set<ConstraintViolation<ImportVmParameters>> validate = ValidationUtils.getValidator().validate(parameters, command.getValidationGroups().toArray(new Class<?>[0])); assertTrue(validate.isEmpty()); parameters.getVm().setUserDefinedProperties(stringOf5000Chars); parameters.setImportAsNewEntity(false); command = new ImportVmCommand(parameters); validate = ValidationUtils.getValidator().validate(parameters, command.getValidationGroups().toArray(new Class<?>[0])); assertTrue(validate.isEmpty()); }
Source:
public void startBroadcast() { try { sendBroadCast(); service = Executors.newSingleThreadScheduledExecutor(); Runnable runnable = new Runnable() { public void run() { logger.info("Listening to broadcast"); try { listenToBroadCast(); } catch (Exception e) { logger.error("Broadcasting has been interrupted" + e.getMessage()); } } }; service.scheduleAtFixedRate(runnable, 0, 300, TimeUnit.SECONDS); } catch (Exception e) { logger.info("Broadcasting has been interrupted " + e.getMessage()); e.printStackTrace(); } }

Target:
public void startBroadcast() { BroadCastServer.turnOnBroadcast = true; try { sendBroadCast(); Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { try { while (turnOnBroadcast) { listenToBroadCast(); } } catch (Exception e) { logger.error("Broadcasting has been interrupted" + e.getMessage()); stopBroadCast(); } } } }); } catch (Exception e) { logger.info("Broadcasting has been interrupted " + e.getMessage()); stopBroadCast(); } }
Source:
protected void sanityCheckTableMetadata(TableReference tableRef, byte[] tableMetadata) { if (tableMetadata == null || Arrays.equals(tableMetadata, AtlasDbConstants.EMPTY_TABLE_METADATA)) { throw new IllegalArgumentException( String.format( "Passing in empty table metadata for table '%s' is disallowed," + " as reasoning about such tables is hard. Consider using" + " AtlasDbConstants.GENERIC_TABLE_METADATA instead.", tableRef)); } }

Target:
protected static void sanityCheckTableMetadata(TableReference tableRef, byte[] tableMetadata) { if (tableMetadata == null || Arrays.equals(tableMetadata, AtlasDbConstants.EMPTY_TABLE_METADATA)) { throw new IllegalArgumentException( String.format( "Passing in empty table metadata for table '%s' is disallowed," + " as reasoning about such tables is hard. Consider using" + " AtlasDbConstants.GENERIC_TABLE_METADATA instead.", tableRef)); } }
Source:
public void onDiscordGameJoinEvent(DiscordJoinEvent discordJoinEvent) { Integer gameId = discordJoinEvent.getGameId(); Game game = getByUid(gameId); boolean disallowJoinsViaDiscord = preferencesService.getPreferences().isDisallowJoinsViaDiscord(); if (disallowJoinsViaDiscord) { log.debug("Join was requested via Discord but was rejected due to it being disabled in settings"); return; } if (game == null) { throw new IllegalStateException(MessageFormat.format("Could not find game to join, with id: {0}", discordJoinEvent.getGameId())); } joinGame(game, ""); }

Target:
public void onDiscordGameJoinEvent(DiscordJoinEvent discordJoinEvent) { Integer gameId = discordJoinEvent.getGameId(); Game game = getByUid(gameId); boolean disallowJoinsViaDiscord = preferencesService.getPreferences().isDisallowJoinsViaDiscord(); if (disallowJoinsViaDiscord) { log.debug("Join was requested via Discord but was rejected due to it being disabled in settings"); return; } if (game == null) { throw new IllegalStateException(String.format("Could not find game to join, with id: %d", discordJoinEvent.getGameId())); } joinGame(game, ""); }
Source:
private void applyStateChanges(Set<String> brokers, String state) { if (state == null) { return; } switch (state) { case "ONLINE": brokers.retainAll(_pinotHelixResourceManager.getOnlineInstanceList()); break; case "OFFLINE": brokers.removeAll(_pinotHelixResourceManager.getOnlineInstanceList()); break; } }

Target:
private void applyStateChanges(Set<String> brokers, String state) { if (state == null) { return; } switch (state) { case CommonConstants.Helix.StateModel.BrokerResourceStateModel.ONLINE: brokers.retainAll(_pinotHelixResourceManager.getOnlineInstanceList()); break; case CommonConstants.Helix.StateModel.BrokerResourceStateModel.OFFLINE: brokers.removeAll(_pinotHelixResourceManager.getOnlineInstanceList()); break; } }
Source:
public void checkIfConnectionIsClosedInAfterCompletion() throws Exception { transactionManager.begin(); Connection connectionToTest = getConnectionToTest(); connectionToTest.clearWarnings(); transactionManager.getTransaction().registerSynchronization(new Synchronization() { @Override public void beforeCompletion() { } @Override public void afterCompletion(int status) { try { connectionToTest.isClosed(); connectionToTest.close(); } catch (SQLException e) { fail("Could not close connection: " + e.getMessage()); } } }); transactionManager.commit(); verify(connection, times(2)).isClosed(); }

Target:
public void checkIfConnectionIsClosedInAfterCompletion() throws Exception { transactionManager.begin(); ConnectionImple connectionToTest = getConnectionToTest(); connectionToTest.clearWarnings(); transactionManager.getTransaction().registerSynchronization(new Synchronization() { @Override public void beforeCompletion() { } @Override public void afterCompletion(int status) { try { connectionToTest.isClosed(); } catch (SQLException e) { fail("Could not check isClosed on connection: " + e.getMessage()); } } }); transactionManager.commit(); verify(connection, times(1)).isClosed(); }
Source:
public void checkDecisionServerContainerAMQ() throws NamingException { log.info("Running test checkDecisionServerContainerAMQ"); log.info("Trying to connect to AMQ HOST: " + AMQ_HOST); getKieJmsServiceClient().listContainers().getResult().getContainers().stream().forEach(container -> { String containerAliasToID = new SumCoder.MD5().encode(container.getResolvedReleaseId().getArtifactId() + "=" + container.getReleaseId()); if (!containerAliasToID.equals(container.getContainerId())){ containerAliasToID = new SumCoder.MD5().encode("AnotherContainer=" + container.getReleaseId()); } Assert.assertTrue(container.getContainerId().equals(containerAliasToID)); Assert.assertEquals(org.kie.server.api.model.KieContainerStatus.STARTED, container.getStatus()); }); }

Target:
public void checkDecisionServerContainerAMQ() throws NamingException { log.info("Running test checkDecisionServerContainerAMQ"); log.info("Trying to connect to AMQ HOST: " + AMQ_HOST); for (KieContainerResource container : getKieJmsServiceClient().listContainers().getResult().getContainers()) { String containerAliasToID = new SumCoder.MD5().encode(container.getResolvedReleaseId().getArtifactId() + "=" + container.getReleaseId()); if (!containerAliasToID.equals(container.getContainerId())) { containerAliasToID = new SumCoder.MD5().encode("AnotherContainer=" + container.getReleaseId()); } Assert.assertTrue(container.getContainerId().equals(containerAliasToID)); Assert.assertEquals(org.kie.server.api.model.KieContainerStatus.STARTED, container.getStatus()); } }
Source:
public Response generateBuyKey(@Context HttpServletRequest request) { Hashtable<String, String> props = new Hashtable<String, String>(); TOTPManager totpManager = (TOTPManager) CarbonContext.getThreadLocalCarbonContext().getOSGiService (TOTPManager.class, props); String secretKey = CharacterEncoder.getSafeText(request.getParameter("secretKey")); String token = null; try { token = totpManager.generateTOTPToken(secretKey); return Response.ok("{\"token\":\"" + token + "\"}", MediaType.APPLICATION_JSON_TYPE).build(); } catch (TOTPException e) { log.error("TOTPKeyGenerator endpoint could not generate the token", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error when generating the token") .type(MediaType.APPLICATION_JSON_TYPE).build(); } }

Target:
public Response generateBuyKey(@Context HttpServletRequest request) { Hashtable<String, String> props = new Hashtable<String, String>(); TOTPManager totpManager = (TOTPManager) CarbonContext.getThreadLocalCarbonContext().getOSGiService (TOTPManager.class, props); String secretKey = CharacterEncoder.getSafeText(request.getParameter("secretKey")); String token; try { token = totpManager.generateTOTPToken(secretKey); return Response.ok("{\"token\":\"" + token + "\"}", MediaType.APPLICATION_JSON_TYPE).build(); } catch (TOTPException e) { log.error("TOTPKeyGenerator endpoint could not generate the token", e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error when generating the token") .type(MediaType.APPLICATION_JSON_TYPE).build(); } }
Source:
public void writeVertex(Vertex<VKmer, VertexValueWritable, NullWritable, ?> vertex) throws IOException, InterruptedException { byte state = (byte) (vertex.getVertexValue().getState() & State.VERTEX_MASK); if (state == State.IS_MARK) getRecordWriter().write(vertex.getVertexId(), vertex.getVertexValue().getCopyAsNode()); }

Target:
public void writeVertex(Vertex<VKmer, VertexValueWritable, NullWritable, ?> vertex) throws IOException, InterruptedException { byte state = (byte) (vertex.getVertexValue().getState() & State.VERTEX_MASK); if (state == State.KEEP_NODE) getRecordWriter().write(vertex.getVertexId(), vertex.getVertexValue().getCopyAsNode()); }
Source:
private String streamOutput(InputStream inputStream) throws IOException, InterruptedException, ExecutionException { BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(new Callable() { public String call() throws IOException { try { String line = null; while ((line = br.readLine()) != null) { System.out.print("."); if (line.contains(ready_marker)) { break; } } } finally { br.close(); } return "\nIAM Microservice started"; } }); try { return future.get(timeout, TimeUnit.SECONDS); } catch (TimeoutException toe) { br.close(); return "\nWarning: IAM Microservice timed out to start. See the logs for the details."; } finally { executor.shutdownNow(); future.cancel(true); } }

Target:
private static String streamOutput(InputStream inputStream) throws IOException, InterruptedException, ExecutionException { BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(new Callable() { public String call() throws IOException { try { String line = null; while ((line = br.readLine()) != null) { System.out.print("."); if (line.contains(READY_MARKER)) { break; } } } finally { br.close(); } return "\nIAM Microservice started"; } }); try { return future.get(TIMEOUT, TimeUnit.SECONDS); } catch (TimeoutException toe) { br.close(); LOGGER.warn("Warning: IAM Microservice timed out to start. See the logs for the details."); return "\nWarning: IAM Microservice timed out to start. See the logs for the details."; } finally { executor.shutdownNow(); future.cancel(true); } }
Source:
private List<QueryParameters.SpatialRelationship> getSpatialRelationships(Geometry a, Geometry b) { List<QueryParameters.SpatialRelationship> relationships = new ArrayList<>(); if (GeometryEngine.crosses(a, b)) relationships.add(QueryParameters.SpatialRelationship.CROSSES); if (GeometryEngine.contains(a, b)) relationships.add(QueryParameters.SpatialRelationship.CONTAINS); if (GeometryEngine.disjoint(a, b)) relationships.add(QueryParameters.SpatialRelationship.DISJOINT); if (GeometryEngine.intersects(a, b)) relationships.add(QueryParameters.SpatialRelationship.INTERSECTS); if (GeometryEngine.overlaps(a, b)) relationships.add(QueryParameters.SpatialRelationship.OVERLAPS); if (GeometryEngine.touches(a, b)) relationships.add(QueryParameters.SpatialRelationship.TOUCHES); if (GeometryEngine.within(a, b)) relationships.add(QueryParameters.SpatialRelationship.WITHIN); return relationships; }

Target:
private static List<QueryParameters.SpatialRelationship> getSpatialRelationships(Geometry a, Geometry b) { List<QueryParameters.SpatialRelationship> relationships = new ArrayList<>(); if (GeometryEngine.crosses(a, b)) relationships.add(QueryParameters.SpatialRelationship.CROSSES); if (GeometryEngine.contains(a, b)) relationships.add(QueryParameters.SpatialRelationship.CONTAINS); if (GeometryEngine.disjoint(a, b)) relationships.add(QueryParameters.SpatialRelationship.DISJOINT); if (GeometryEngine.intersects(a, b)) relationships.add(QueryParameters.SpatialRelationship.INTERSECTS); if (GeometryEngine.overlaps(a, b)) relationships.add(QueryParameters.SpatialRelationship.OVERLAPS); if (GeometryEngine.touches(a, b)) relationships.add(QueryParameters.SpatialRelationship.TOUCHES); if (GeometryEngine.within(a, b)) relationships.add(QueryParameters.SpatialRelationship.WITHIN); return relationships; }
Source:
public List<MetricFamilySamples> collect() { return Arrays.asList( createSample("hikaricp_active_connections", "Active connections", poolStats.getActiveConnections()), createSample("hikaricp_idle_connections", "Idle connections", poolStats.getIdleConnections()), createSample("hikaricp_pending_threads", "Pending threads", poolStats.getPendingThreads()), createSample("hikaricp_total_connections", "Total connections", poolStats.getTotalConnections()) ); }

Target:
public List<MetricFamilySamples> collect() { return Arrays.asList( createSample("hikaricp_active_connections", "Active connections", poolStats.getActiveConnections()), createSample("hikaricp_idle_connections", "Idle connections", poolStats.getIdleConnections()), createSample("hikaricp_pending_threads", "Pending threads", poolStats.getPendingThreads()), createSample("hikaricp_connections", "The number of current connections", poolStats.getTotalConnections()) ); }
Source:
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (mItemList.get(position) instanceof ParentObject) { ParentViewHolder parentViewHolder = (ParentViewHolder) holder; if (mCustomParentAnimationViewId != -1l && mAnimationDuration != -1l) { parentViewHolder.setCustomClickableView(mCustomParentAnimationViewId); parentViewHolder.setAnimationDuration(mAnimationDuration); } else if (mCustomParentAnimationViewId != -1l) { parentViewHolder.setCustomClickableView(mCustomParentAnimationViewId); parentViewHolder.cancelAnimation(); } else { parentViewHolder.setMainItemClickToExpand(); } parentViewHolder.setExpanded(((ParentObject) mItemList.get(position)).isExpanded()); onBindParentViewHolder(parentViewHolder, position); } else if (mItemList.get(position) instanceof ChildObject) { onBindChildViewHolder((ChildViewHolder) holder, position); } else { throw new IllegalStateException("Incorrect ViewHolder found"); } }

Target:
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (mItemList.get(position) instanceof ParentObject) { ParentViewHolder parentViewHolder = (ParentViewHolder) holder; if (mParentAndIconClickable) { if (mCustomParentAnimationViewId != CUSTOM_ANIMATION_VIEW_NOT_SET && mAnimationDuration != CUSTOM_ANIMATION_DURATION_NOT_SET) { parentViewHolder.setCustomClickableViewAndItem(mCustomParentAnimationViewId); parentViewHolder.setAnimationDuration(mAnimationDuration); } else if (mCustomParentAnimationViewId != CUSTOM_ANIMATION_VIEW_NOT_SET) { parentViewHolder.setCustomClickableViewAndItem(mCustomParentAnimationViewId); parentViewHolder.cancelAnimation(); } else { parentViewHolder.setMainItemClickToExpand(); } } else { if (mCustomParentAnimationViewId != CUSTOM_ANIMATION_VIEW_NOT_SET && mAnimationDuration != CUSTOM_ANIMATION_DURATION_NOT_SET) { parentViewHolder.setCustomClickableViewOnly(mCustomParentAnimationViewId); parentViewHolder.setAnimationDuration(mAnimationDuration); } else if (mCustomParentAnimationViewId != CUSTOM_ANIMATION_VIEW_NOT_SET) { parentViewHolder.setCustomClickableViewOnly(mCustomParentAnimationViewId); parentViewHolder.cancelAnimation(); } else { parentViewHolder.setMainItemClickToExpand(); } } parentViewHolder.setExpanded(((ParentObject) mItemList.get(position)).isExpanded()); onBindParentViewHolder(parentViewHolder, position); } else if (mItemList.get(position) instanceof ChildObject) { onBindChildViewHolder((ChildViewHolder) holder, position); } else { throw new IllegalStateException("Incorrect ViewHolder found"); } }
Source:
public static String prettyPrintRule(Rule rule) { StringBuilder sb = new StringBuilder(); if (rule instanceof Context) { final Context ctx = (Context) rule; WindupRuleProvider ruleProvider = (WindupRuleProvider) ctx.get(RuleMetadata.RULE_PROVIDER); if (ruleProvider != null) { sb.append(ruleProvider.getPhase()).append(" - "); sb.append(ruleProvider.getID()).append(' '); } Object categories = (String) ctx.get(RuleMetadata.CATEGORY); if (categories instanceof String ) sb.append('[').append(categories).append("] "); if (categories instanceof Iterable){ sb.append('['); for(Object cat : (Iterable) categories) sb.append(cat).append(", "); sb.append("] "); } } return sb.append(rule.getId()).toString(); }

Target:
public static String prettyPrintRule(Rule rule) { StringBuilder sb = new StringBuilder(); if (rule instanceof Context) { final Context ctx = (Context) rule; WindupRuleProvider ruleProvider = (WindupRuleProvider) ctx.get(RuleMetadata.RULE_PROVIDER); if (ruleProvider != null) { sb.append(ruleProvider.getPhase()).append(" - "); sb.append(ruleProvider.getID()).append(' '); } Object categories = ctx.get(RuleMetadata.TAGS); if (categories instanceof String ) sb.append('[').append(categories).append("] "); else if (categories instanceof Iterable) { sb.append('['); for(Object cat : (Iterable) categories) sb.append(cat).append(", "); sb.append("] "); } } return sb.append(rule.getId()).toString(); }
Source:
public void ignoreCaseShouldNotBeApplicableToComparisonOtherThanEquals() { final String emi = "EMI Studios, London"; session.save(new Studio(emi)); assertThat(session.loadAll(Studio.class, new Filter("name", ComparisonOperator.EQUALS, "eMi Studios, London").ignoreCase(), 0)) .hasSize(1) .extracting(Studio::getName) .containsExactly(emi); }

Target:
public void ignoreCaseShouldNotBeApplicableToComparisonOtherThanEquals() { final String emi = "EMI Studios, London"; session.save(new Studio(emi)); final Filter nameFilter = new Filter("name", ComparisonOperator.EQUALS, "eMi Studios, London").ignoreCase(); assertThat(session.loadAll(Studio.class, nameFilter, 0)) .hasSize(1) .extracting(Studio::getName) .containsExactly(emi); }