auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
synchronized private Config getResourceDescription(ConfigResource resource) { switch (resource.type()) { case BROKER: { int brokerId = Integer.parseInt(resource.name()); if (brokerId >= brokerConfigs.size()) { throw new InvalidRequestException("Broker " + resource.name() + " not found."); } return toConfigObject(brokerConfigs.get(brokerId)); } case TOPIC: { TopicMetadata topicMetadata = allTopics.get(resource.name()); if (topicMetadata != null && !topicMetadata.markedForDeletion) { if (topicMetadata.fetchesRemainingUntilVisible > 0) topicMetadata.fetchesRemainingUntilVisible--; else return new Config(topicMetadata.configs.entrySet().stream() .map(entry -> new ConfigEntry(entry.getKey(), entry.getValue())) .collect(Collectors.toList())); } throw new UnknownTopicOrPartitionException("Resource " + resource + " not found."); } default: throw new UnsupportedOperationException("Not implemented yet"); } }

Target:
synchronized private Config getResourceDescription(ConfigResource resource) { switch (resource.type()) { case BROKER: { int brokerId = Integer.parseInt(resource.name()); if (brokerId >= brokerConfigs.size()) { throw new InvalidRequestException("Broker " + resource.name() + " not found."); } return toConfigObject(brokerConfigs.get(brokerId)); } case TOPIC: { TopicMetadata topicMetadata = allTopics.get(resource.name()); if (topicMetadata != null && !topicMetadata.markedForDeletion) { if (topicMetadata.fetchesRemainingUntilVisible > 0) topicMetadata.fetchesRemainingUntilVisible = Math.max(0, topicMetadata.fetchesRemainingUntilVisible - 1); else return new Config(topicMetadata.configs.entrySet().stream() .map(entry -> new ConfigEntry(entry.getKey(), entry.getValue())) .collect(Collectors.toList())); } throw new UnknownTopicOrPartitionException("Resource " + resource + " not found."); } default: throw new UnsupportedOperationException("Not implemented yet"); } }
Source:
List getNetworkInterfaces(VM vm){ List net = new ArrayList(); Map resultMap = new HashMap(); List Inet6List = new ArrayList(); List Inet4List = new ArrayList(); resultMap.put("name", "eth0"); Inet6List.add("fe80::21a:4aff:fe16:2016"); Inet6List.add("2620:52:0:2380:21a:4aff:fe16:2016"); resultMap.put("inet6", Inet6List); Inet4List.add(vm.getIp()); resultMap.put("inet", Inet4List); resultMap.put("hw", vm.getMacAddress()); net.add(resultMap); log.debug("network list is {}", net.toString()); return net; }

Target:
List getNetworkInterfaces(VM vm){ List<Map> net = new ArrayList(); Map<String, Object> resultMap = new HashMap(); List Inet6List = new ArrayList(); List Inet4List = new ArrayList(); resultMap.put("name", "eth0"); Inet6List.add("fe80::21a:4aff:fe16:2016"); Inet6List.add("2620:52:0:2380:21a:4aff:fe16:2016"); resultMap.put("inet6", Inet6List); Inet4List.add(vm.getIp()); resultMap.put("inet", Inet4List); resultMap.put("hw", vm.getMacAddress()); net.add(resultMap); log.debug("network list is {}", net.toString()); return net; }
Source:
private void moveObject(PID objPid) { aclService.assertHasAccess("Agent " + agent.getUsername() + " does not have permission to move object " + objPid, objPid, agent.getPrincipals(), Permission.move); RepositoryObject moveObj = repositoryObjectLoader.getRepositoryObject(objPid); ContentObject moveContent = (ContentObject) moveObj; destroyProxy(objPid); destContainer.addMember(moveContent); }

Target:
private void moveObject(PID objPid) { aclService.assertHasAccess("Agent " + agent.getUsername() + " does not have permission to move object " + objPid, objPid, agent.getPrincipals(), Permission.move); ContentObject moveContent = (ContentObject) repositoryObjectLoader.getRepositoryObject(objPid); destroyProxy(objPid); destContainer.addMember(moveContent); }
Source:
public void testPublishAndReadMessages() throws Exception { eventBus = new SimpleEventBus(); ProducerFactory<String, byte[]> producerFactory = ProducerConfigUtil.ackProducerFactory(kafka, ByteArraySerializer.class); KafkaPublisher<String, byte[]> publisher = KafkaPublisher.<String, byte[]>builder() .messageSource(eventBus) .producerFactory(producerFactory) .topic("integration") .build(); publisher.start(); ConsumerFactory<String, byte[]> cf = new DefaultConsumerFactory<>(minimal(kafka, "consumer1", ByteArrayDeserializer.class)); Fetcher fetcher = AsyncFetcher.<String, byte[]>builder() .consumerFactory(cf) .topic("integration") .pollTimeout(300, TimeUnit.MILLISECONDS) .build(); KafkaMessageSource messageSource = new KafkaMessageSource(fetcher); BlockingStream<TrackedEventMessage<?>> stream1 = messageSource.openStream(null); stream1.close(); BlockingStream<TrackedEventMessage<?>> stream2 = messageSource.openStream(null); eventBus.publish(asEventMessage("test")); assertTrue(stream2.hasNextAvailable(20, TimeUnit.SECONDS)); TrackedEventMessage<?> actual = stream2.nextAvailable(); assertNotNull(actual); stream2.close(); producerFactory.shutDown(); fetcher.shutdown(); publisher.shutDown(); }

Target:
public void testPublishAndReadMessages() throws Exception { eventBus = new SimpleEventBus(); ProducerFactory<String, byte[]> producerFactory = ProducerConfigUtil.ackProducerFactory(kafka, ByteArraySerializer.class); KafkaPublisher<String, byte[]> publisher = KafkaPublisher.<String, byte[]>builder() .messageSource(eventBus) .producerFactory(producerFactory) .topic("integration") .build(); publisher.start(); ConsumerFactory<String, byte[]> consumerFactory = new DefaultConsumerFactory<>(minimal(kafka, "consumer1", ByteArrayDeserializer.class)); Fetcher fetcher = AsyncFetcher.<String, byte[]>builder() .consumerFactory(consumerFactory) .topic("integration") .pollTimeout(300, TimeUnit.MILLISECONDS) .build(); KafkaMessageSource messageSource = new KafkaMessageSource(fetcher); BlockingStream<TrackedEventMessage<?>> stream1 = messageSource.openStream(null); stream1.close(); BlockingStream<TrackedEventMessage<?>> stream2 = messageSource.openStream(null); eventBus.publish(asEventMessage("test")); assertTrue(stream2.hasNextAvailable(20, TimeUnit.SECONDS)); TrackedEventMessage<?> actual = stream2.nextAvailable(); assertNotNull(actual); stream2.close(); producerFactory.shutDown(); fetcher.shutdown(); publisher.shutDown(); }
Source:
public void decorate(Object element, IDecoration decoration) { if (element instanceof IProject) { IProject prj = (IProject) element; String prjName = prj.getName(); Object suffix; try { suffix = prj.getSessionProperty(DECO_PROP); } catch (CoreException e) { e.printStackTrace(); suffix = null; } if (suffix != null) { decoration.addSuffix((String) suffix); } if (prjName.equals(TestWorkspace.P1_PROJECT_NAME)) { try { semaphoreDecoratorP1Ran.release(); semaphoreBlockDecoration.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } } else if (prjName.equals(TestWorkspace.P2_PROJECT_NAME)) { try { semaphoreDecoratorP2Ran.release(); semaphoreBlockDecoration.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } } } }

Target:
public void decorate(Object element, IDecoration decoration) { if (!(element instanceof IProject)) { return; } IProject prj = (IProject) element; String prjName = prj.getName(); Object suffix; try { suffix = prj.getSessionProperty(DECO_PROP); } catch (CoreException e) { e.printStackTrace(); suffix = null; } if (suffix != null) { decoration.addSuffix((String) suffix); } if (prjName.equals(TestWorkspace.P1_PROJECT_NAME)) { try { semaphoreDecoratorP1Ran.release(); semaphoreBlockDecoration.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } } else if (prjName.equals(TestWorkspace.P2_PROJECT_NAME)) { try { semaphoreDecoratorP2Ran.release(); semaphoreBlockDecoration.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } } }
Source:
public DictionaryLemmatizer(final InputStream dictionary) { this.dictMap = new HashMap<>(); final BufferedReader breader = new BufferedReader( new InputStreamReader(dictionary)); String line; try { while ((line = breader.readLine()) != null) { final String[] elems = line.split("\t"); this.dictMap.put(Arrays.asList(elems[0], elems[1]), Arrays.asList(elems[2])); } } catch (final IOException e) { e.printStackTrace(); } }

Target:
public DictionaryLemmatizer(final InputStream dictionary) throws IOException { this.dictMap = new HashMap<>(); final BufferedReader breader = new BufferedReader( new InputStreamReader(dictionary)); String line; while ((line = breader.readLine()) != null) { final String[] elems = line.split("\t"); this.dictMap.put(Arrays.asList(elems[0], elems[1]), Arrays.asList(elems[2])); } }
Source:
public static void addHostAndPortToConstructor(Element element, BeanDefinitionBuilder builder, ParserContext parserContext) { String host = element.getAttribute(IpAdapterParserUtils.HOST); String socketExpression = element.getAttribute(IpAdapterParserUtils.SOCKET_EXPRESSION); if (!StringUtils.hasText(host) && StringUtils.isEmpty(socketExpression)) { parserContext.getReaderContext().error(IpAdapterParserUtils.HOST + " is required for IP outbound channel adapters", element); } builder.addConstructorArgValue(host); String port = IpAdapterParserUtils.getPort(element, parserContext); if (StringUtils.isEmpty(port)) { port = "0"; } builder.addConstructorArgValue(port); }

Target:
private static void addHostAndPortToConstructor(Element element, BeanDefinitionBuilder builder, ParserContext parserContext) { String host = element.getAttribute(IpAdapterParserUtils.HOST); if (!StringUtils.hasText(host)) { parserContext.getReaderContext().error(IpAdapterParserUtils.HOST + " is required for IP outbound channel adapters", element); } builder.addConstructorArgValue(host); String port = IpAdapterParserUtils.getPort(element, parserContext); builder.addConstructorArgValue(port); }
Source:
public static JSONObject addForwardReverse(Collection col) throws ConfirmModSchemaException { String name = "Basic (and reversed card)"; Models mm = col.getModels(); JSONObject m = newBasicModel(col); try { m.put("name", name); JSONObject t = mm.newTemplate("Card 2"); t.put("qfmt", "{{Back}}"); t.put("afmt", "{{FrontSide}}\n\n<hr id=answer>\n\n{{Front}}"); mm.addTemplate(m, t); } catch (JSONException e) { throw new RuntimeException(e); } return m; }

Target:
public static JSONObject addForwardReverse(Collection col) { String name = "Basic (and reversed card)"; Models mm = col.getModels(); JSONObject m = _newBasicModel(col); try { m.put("name", name); JSONObject t = mm.newTemplate("Card 2"); t.put("qfmt", "{{Back}}"); t.put("afmt", "{{FrontSide}}\n\n<hr id=answer>\n\n{{Front}}"); mm.addTemplateInNewModel(m, t); mm.add(m); } catch (JSONException e) { throw new RuntimeException(e); } return m; }
Source:
private static Configuration getPythonConfiguration(CommandLine line) { try { Class<?> clazz = Class.forName( "org.apache.flink.python.util.PythonDependencyUtils", true, Thread.currentThread().getContextClassLoader()); Method parsePythonDependencyConfiguration = clazz.getMethod("parsePythonDependencyConfiguration", CommandLine.class); return (Configuration) parsePythonDependencyConfiguration.invoke(null, line); } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new SqlClientException("Parse the Python command line options failed.", e); } }

Target:
private static Configuration getPythonConfiguration(CommandLine line) { try { Class<?> clazz = Class.forName( "org.apache.flink.python.util.PythonDependencyUtils", true, Thread.currentThread().getContextClassLoader()); Method parsePythonDependencyConfiguration = clazz.getMethod("parsePythonDependencyConfiguration", CommandLine.class); return (Configuration) parsePythonDependencyConfiguration.invoke(null, line); } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new SqlClientException("Failed to parse the Python command line options.", e); } }
Source:
public void shouldAuthoriseSuccessfullyWithNoAddressInRequest() { setUpAndCheckThatEpdqIsUp(); PaymentProvider paymentProvider = getEpdqPaymentProvider(); AuthorisationGatewayRequest request = buildAuthorisationRequest(chargeEntity); request.getAuthCardDetails().setAddress(null); GatewayResponse<EpdqAuthorisationResponse> response = paymentProvider.authorise(request); assertThat(response.isSuccessful(), is(true)); }

Target:
public void shouldAuthoriseSuccessfullyWithNoAddressInRequest() { setUpAndCheckThatEpdqIsUp(); AuthorisationGatewayRequest request = buildAuthorisationRequest(chargeEntity); request.getAuthCardDetails().setAddress(null); GatewayResponse<EpdqAuthorisationResponse> response = paymentProvider.authorise(request); assertThat(response.isSuccessful(), is(true)); }
Source:
public static void afterClass() throws IOException, TimeoutException, InterruptedException { try { operations.writeAttribute(WEBSERVICES_ADDRESS, STATISTICS_ENABLED, originalStatisticsEnabledValue); administration.restartIfRequired(); administration.reloadIfRequired(); } finally { IOUtils.closeQuietly(client); } }

Target:
public static void afterClass() throws IOException, TimeoutException, InterruptedException { try { DEPLOYMENT_FILE.delete(); if (originalStatisticsEnabledValue != null) { operations.writeAttribute(WEBSERVICES_ADDRESS, STATISTICS_ENABLED, originalStatisticsEnabledValue); } administration.restartIfRequired(); administration.reloadIfRequired(); } finally { IOUtils.closeQuietly(client); } }
Source:
public AssetReportCreateRequest withEmail(String email) { notNull(email, "email"); options = options.orElse(new Options()); options.get().user = options.get().user.orElse(new Options.UserOptions()); options.get().user.get().clientUserId = email; return this; }

Target:
public AssetReportCreateRequest withEmail(String email) { notNull(email, "email"); options = options.orElse(new Options()); options.get().user = options.get().user.orElse(new Options.UserOptions()); options.get().user.get().email = email; return this; }
Source:
protected boolean set(MapInfo mapInfo, Vector2i value) { MapData mapData = (MapData)mapInfo; mapData.calculateMapCenter(value.getX(), value.getX(), mapData.scale); mapData.markDirty(); return true; }

Target:
protected boolean set(MapInfo mapInfo, Vector2i value) { MapData mapData = (MapData) mapInfo; mapData.calculateMapCenter(value.getX(), value.getY(), mapData.scale); mapData.markDirty(); return true; }
Source:
protected List<VdcReturnValueBase> executeChildCommands() { List<VdcReturnValueBase> results = new ArrayList<>(); for (CommandBase<?> command : childCommandsMap.values()) { results.add(getBackendCommandObjectsHandler().runAction(command, getExecutionContext())); } return results; }

Target:
protected List<VdcReturnValueBase> executeChildCommands() { List<VdcReturnValueBase> results = new ArrayList<>(childCommandsMap.size()); for (Entry<Guid, CommandBase<?>> entry : childCommandsMap.entrySet()) { results.add(executeChildCommand(entry.getKey())); } return results; }
Source:
public synchronized void waitOnClosingSources() { boolean locked = false; try { locked = m_allowCatalogUpdate.tryAcquire(1, UPDATE_CORE_TIMEOUT_SECONDS, TimeUnit.SECONDS); if (!locked && !m_dataSourcesClosing.isEmpty()) { exportLog.warn("After " + UPDATE_CORE_TIMEOUT_SECONDS + " seconds, these export streams are still closing: " + m_dataSourcesClosing.keySet()); } } catch (Exception ex) { if (!m_dataSourcesClosing.isEmpty()) { exportLog.warn("Unable to wait: " + ex + ", these export streams are still closing: " + m_dataSourcesClosing.keySet()); } } finally { if (locked) { m_allowCatalogUpdate.release(); } } }

Target:
public void waitOnClosingSources() { boolean locked = false; try { locked = m_allowCatalogUpdate.tryAcquire(UPDATE_CORE_TIMEOUT_SECONDS, TimeUnit.SECONDS); if (!locked && !m_dataSourcesClosing.isEmpty()) { exportLog.warn("After " + UPDATE_CORE_TIMEOUT_SECONDS + " seconds, these export streams are still closing: " + m_dataSourcesClosing.keySet()); } } catch (Exception ex) { if (!m_dataSourcesClosing.isEmpty()) { exportLog.warn("Unable to wait: " + ex + ", these export streams are still closing: " + m_dataSourcesClosing.keySet()); } } finally { if (locked) { m_allowCatalogUpdate.release(); } } }
Source:
protected <T> void executeAndStream( DockerHttpClient.Request request, ResultCallback<T> callback, Consumer<DockerHttpClient.Response> sourceConsumer ) { CountDownLatch onStart = new CountDownLatch(1); Thread thread = new Thread(() -> { Thread streamingThread = Thread.currentThread(); try (DockerHttpClient.Response response = execute(request)) { onStart.countDown(); callback.onStart(() -> { streamingThread.interrupt(); response.close(); }); sourceConsumer.accept(response); callback.onComplete(); } catch (Exception e) { callback.onError(e); } finally { onStart.countDown(); } }, "docker-java-stream-" + Objects.hashCode(request)); thread.setDaemon(true); thread.start(); try { onStart.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }

Target:
protected <T> void executeAndStream( DockerHttpClient.Request request, ResultCallback<T> callback, Consumer<DockerHttpClient.Response> sourceConsumer ) { Thread thread = new Thread(() -> { Thread streamingThread = Thread.currentThread(); try (DockerHttpClient.Response response = execute(request)) { callback.onStart(() -> { streamingThread.interrupt(); response.close(); }); sourceConsumer.accept(response); callback.onComplete(); } catch (Exception e) { callback.onError(e); } }, "docker-java-stream-" + Objects.hashCode(request)); thread.setDaemon(true); thread.start(); }
Source:
public int findIndex(List<WorldSetupWrapper> worldsList,String worldName) { for(int i = 0 ;i<worldsList.size();i++) { WorldSetupWrapper random = worldsList.get(i); Name customName= random.getWorldName(); if(customName.toString().equals(worldName)) { return i; } } return -1; }

Target:
public int findIndex(List<WorldSetupWrapper> worldsList, String worldName) { for (int i = 0; i < worldsList.size(); i++) { WorldSetupWrapper currentWorldFromList = worldsList.get(i); Name customName = currentWorldFromList.getWorldName(); if (customName.toString().equals(worldName)) { return i; } } return -1; }
Source:
public void doubleClick(DoubleClickEvent event) { final IStructuredSelection structuredSelection = (IStructuredSelection)event.getSelection(); if (structuredSelection == null || structuredSelection.isEmpty()) { return; } final Object selection = structuredSelection.getFirstElement(); final ITreeContentProvider provider = (ITreeContentProvider)treeViewer.getContentProvider(); if (provider.hasChildren(selection)) { if (treeViewer.getExpandedState(selection)) { treeViewer.collapseToLevel(selection, AbstractTreeViewer.ALL_LEVELS); } else { treeViewer.expandToLevel(selection, 1); } } else { NodeSelection nodeSelection = NodeSelection.from(this.treeViewer.getSelection()); if (isEnabledFor(nodeSelection)) { run(); } } }

Target:
public void doubleClick(DoubleClickEvent event) { NodeSelection nodeSelection = NodeSelection.from(this.treeViewer.getSelection()); if (isEnabledFor(nodeSelection)) { run(); } else if (nodeSelection.isSingleSelection()) { Object selected = nodeSelection.toList().get(0); IContentProvider provider = this.treeViewer.getContentProvider(); if (provider instanceof ITreeContentProvider && ((ITreeContentProvider) provider).hasChildren(selected)) { if (this.treeViewer.getExpandedState(selected)) { this.treeViewer.collapseToLevel(selected, AbstractTreeViewer.ALL_LEVELS); } else { this.treeViewer.expandToLevel(selected, 1); } } } }
Source:
public float getFloat() { return foundValue.floatValue(); }

Target:
public float getFloat() { return (float) foundValue; }
Source:
public void onPluginEnable(final PluginEnableEvent event) { if (event.getPlugin().getName().equals("EssentialsChat")) { ess.getSettings().setEssentialsChatActive(true); } ess.getPermissionsHandler().setUseSuperperms(ess.getSettings().useBukkitPermissions()); ess.getPermissionsHandler().checkPermissions(); ess.getPermissionsHandler().registerContext("ess-afk", player -> Collections.singleton(String.valueOf(ess.getUser(player).isAfk())), () -> ImmutableSet.of("true", "false")); ess.getPermissionsHandler().registerContext("ess-muted", player -> Collections.singleton(String.valueOf(ess.getUser(player).isMuted())), () -> ImmutableSet.of("true", "false")); ess.getPermissionsHandler().registerContext("ess-vanished", player -> Collections.singleton(String.valueOf(ess.getUser(player).isHidden())), () -> ImmutableSet.of("true", "false")); ess.getAlternativeCommandsHandler().addPlugin(event.getPlugin()); if (!Methods.hasMethod() && Methods.setMethod(ess.getServer().getPluginManager())) { ess.getLogger().log(Level.INFO, "Payment method found (" + Methods.getMethod().getLongName() + " version: " + ess.getPaymentMethod().getMethod().getVersion() + ")"); } }

Target:
public void onPluginEnable(final PluginEnableEvent event) { if (event.getPlugin().getName().equals("EssentialsChat")) { ess.getSettings().setEssentialsChatActive(true); } ess.getPermissionsHandler().setUseSuperperms(ess.getSettings().useBukkitPermissions()); ess.getPermissionsHandler().checkPermissions(); ess.getAlternativeCommandsHandler().addPlugin(event.getPlugin()); if (!Methods.hasMethod() && Methods.setMethod(ess.getServer().getPluginManager())) { ess.getLogger().log(Level.INFO, "Payment method found (" + Methods.getMethod().getLongName() + " version: " + ess.getPaymentMethod().getMethod().getVersion() + ")"); } }
Source:
public CloudBigtableScanConfiguration build() { if (request == null) { ReadHooks readHooks = new DefaultReadHooks(); if (scan == null) { scan = new Scan(); } Query query = Query.create(tableId.get()); Adapters.SCAN_ADAPTER.adapt(scan, readHooks, query); ValueProvider<String> appProfileIdValue = additionalConfiguration.get(BigtableOptionsFactory.APP_PROFILE_ID_KEY); String appProfileId = ""; if (appProfileIdValue != null) { appProfileId = appProfileIdValue.get(); } RequestContext requestContext = RequestContext .create(InstanceName.of(projectId.get(), instanceId.get()), appProfileId); readHooks.applyPreSendHook(query); request = StaticValueProvider.of(query.toProto(requestContext)); } return new CloudBigtableScanConfiguration(projectId, instanceId, tableId, request, additionalConfiguration); }

Target:
public CloudBigtableScanConfiguration build() { if (request == null) { withScan(new Scan()); } return new CloudBigtableScanConfiguration(projectId, instanceId, tableId, request, additionalConfiguration); }
Source:
protected CacheEntryEvent<K, V> shouldInvoke(CacheEntryEvent<K, V> event, boolean isLocalNodePrimaryOwner) { if (onlyPrimary && !isLocalNodePrimaryOwner) return null; if (event instanceof EventImpl) { EventImpl<K, V> eventImpl = (EventImpl<K, V>)event; boolean isPre = eventImpl.isPre(); if (!observation.shouldInvoke(isPre)) return null; if (isPre && clustered) return null; EventType eventType; if (filter != null && (eventType = getEvent(eventImpl)) != null) { if (filterAndConvert) { Object newValue = ((CacheEventFilterConverter)filter).filterAndConvert(eventImpl.getKey(), eventImpl.getOldValue(), eventImpl.getOldMetadata(), eventImpl.getValue(), eventImpl.getMetadata(), eventType); if (newValue != null) { EventImpl<K, V> clone = eventImpl.clone(); clone.setValue((V) newValue); return clone; } else { return null; } } else if (!filter.accept(eventImpl.getKey(), eventImpl.getOldValue(), eventImpl.getOldMetadata(), eventImpl.getValue(), eventImpl.getMetadata(), eventType)) { return null; } } } return event; }

Target:
protected CacheEntryEvent<K, V> shouldInvoke(CacheEntryEvent<K, V> event, boolean isLocalNodePrimaryOwner) { if (onlyPrimary && !isLocalNodePrimaryOwner) return null; if (event instanceof EventImpl) { EventImpl<K, V> eventImpl = (EventImpl<K, V>)event; boolean isPre = eventImpl.isPre(); if (!observation.shouldInvoke(isPre)) return null; EventType eventType; if (filter != null && (eventType = getEvent(eventImpl)) != null) { if (filterAndConvert) { Object newValue = ((CacheEventFilterConverter)filter).filterAndConvert(eventImpl.getKey(), eventImpl.getOldValue(), eventImpl.getOldMetadata(), eventImpl.getValue(), eventImpl.getMetadata(), eventType); if (newValue != null) { EventImpl<K, V> clone = eventImpl.clone(); clone.setValue((V) newValue); return clone; } else { return null; } } else if (!filter.accept(eventImpl.getKey(), eventImpl.getOldValue(), eventImpl.getOldMetadata(), eventImpl.getValue(), eventImpl.getMetadata(), eventType)) { return null; } } } return event; }
Source:
public void emitTuples() { try { final Transaction transaction = client.createTransaction(TransferDirection.RECEIVE); if (transaction == null) { LOGGER.warn("A transaction could not be created, returning..."); return; } DataPacket dataPacket = transaction.receive(); if (dataPacket == null) { transaction.confirm(); transaction.complete(); LOGGER.debug("No data available to pull, returning and will try again..."); return; } final List<T> tuples = new ArrayList<>(); do { tuples.add(createTuple(dataPacket)); dataPacket = transaction.receive(); } while (dataPacket != null); transaction.confirm(); emitTuples(tuples); transaction.complete(); } catch (IOException ioe) { throw new RuntimeException("Error communicating with NiFi", ioe); } }

Target:
public void emitTuples() { if (recoveredTuples.size() > 0) { emitTuples(recoveredTuples); recoveredTuples.clear(); return; } try { final Transaction transaction = client.createTransaction(TransferDirection.RECEIVE); if (transaction == null) { LOGGER.warn("A transaction could not be created, returning..."); return; } DataPacket dataPacket = transaction.receive(); if (dataPacket == null) { transaction.confirm(); transaction.complete(); LOGGER.debug("No data available to pull, returning and will try again..."); return; } final List<T> tuples = new ArrayList<>(); do { tuples.add(createTuple(dataPacket)); dataPacket = transaction.receive(); } while (dataPacket != null); transaction.confirm(); currentWindowTuples.addAll(tuples); windowDataManager.save(currentWindowTuples, operatorContextId, currentWindowId); transaction.complete(); emitTuples(tuples); } catch (IOException e) { DTThrowable.rethrow(e); } }
Source:
public void checkInterrupted() { if (nIterrationsSinceCheck == nIterrationsPerCheck) { nIterrationsSinceCheck = 0; int nRead = nf.peek(fd, buffer, bufferSize); if (nRead == 0) { return; } if (nRead < 0) { throw CairoException.instance(0).put("Interrupting SQL processings, client fd ").put(fd).put(" is closed"); } int index = 0; long ptr = buffer; while (index < nRead) { byte b = Unsafe.getUnsafe().getByte(ptr + index); if (b != (byte) '\r' && b != (byte) '\n') { break; } index++; } if (index > 0) { nf.recv(fd, buffer, index); } } else { nIterrationsSinceCheck++; } }

Target:
public void checkInterrupted() { assert fd != -1; if (nIterationsSinceCheck == nIterationsPerCheck) { nIterationsSinceCheck = 0; int nRead = nf.peek(fd, buffer, bufferSize); if (nRead == 0) { return; } if (nRead < 0) { throw CairoException.instance(0).put("Interrupting SQL processing, client fd ").put(fd).put(" is closed"); } int index = 0; long ptr = buffer; while (index < nRead) { byte b = Unsafe.getUnsafe().getByte(ptr + index); if (b != (byte) '\r' && b != (byte) '\n') { break; } index++; } if (index > 0) { nf.recv(fd, buffer, index); } } else { nIterationsSinceCheck++; } }
Source:
public ActivityEvent(String handle, String kind, String summary, Date date, Map<String, String> attributes) { Assert.isNotNull("Handle should not be null", handle); Assert.isNotNull("Task kind should not be null", kind); Assert.isNotNull("Task summary should not be null", summary); this.handle = handle; this.kind = kind; this.summary = summary; this.date = date; this.attributes = attributes; }

Target:
public ActivityEvent(String handle, String kind, String summary, Date date, Map<String, String> attributes) { Assert.isNotNull("Handle must not be null", handle); Assert.isNotNull("Task kind must not be null", kind); Assert.isNotNull("Task summary must not be null", summary); this.handle = handle; this.kind = kind; this.summary = summary; this.date = date; this.attributes = attributes; }
Source:
protected void findInDiagram(ScopeEntry scopeEntry) { for (AbstractResultEntry match : fResults) { Object source = null; if (match instanceof AttributeMatch) { source = ((AttributeMatch) match).getSource(); } else { source = match.getSource(); } if (source instanceof Element) { List<View> views = getViewsToSelect((Element) source); if (views != null && !views.isEmpty()) { for (View view : views) { ViewerMatch viewMatch = new ViewerMatch(view, scopeEntry, source); fResults.add(viewMatch); } } } } }

Target:
protected void findInDiagram(ScopeEntry scopeEntry) { Set<AbstractResultEntry> viewResults = new HashSet<AbstractResultEntry>(); for (AbstractResultEntry match : fResults) { Object source = null; if (match instanceof AttributeMatch) { source = ((AttributeMatch) match).getSource(); } else { source = match.getSource(); } if (source instanceof Element) { List<View> views = getViewsToSelect((Element) source); if (views != null && !views.isEmpty()) { for (View view : views) { ViewerMatch viewMatch = new ViewerMatch(view, scopeEntry, source); viewResults.add(viewMatch); } } } } fResults.addAll(viewResults); }
Source:
public void detectBOM() throws URISyntaxException, IOException { byte[] b = ByteOrderMark.UTF_16BE.getBytes(); assertThat(charsets.detectBOM(b)).isEqualTo(ByteOrderMark.UTF_16BE); Path utf8 = Paths.get(this.getClass().getClassLoader().getResource("org/sonar/scanner/scan/filesystem/UTF-8.txt").toURI()); Path utf16be = Paths.get(this.getClass().getClassLoader().getResource("org/sonar/scanner/scan/filesystem/UTF-16BE.txt").toURI()); Path utf16le = Paths.get(this.getClass().getClassLoader().getResource("org/sonar/scanner/scan/filesystem/UTF-16LE.txt").toURI()); Path utf32be = Paths.get(this.getClass().getClassLoader().getResource("org/sonar/scanner/scan/filesystem/UTF-32BE.txt").toURI()); Path utf32le = Paths.get(this.getClass().getClassLoader().getResource("org/sonar/scanner/scan/filesystem/UTF-32LE.txt").toURI()); assertThat(charsets.detectBOM(Files.readAllBytes(utf8))).isEqualTo(ByteOrderMark.UTF_8); assertThat(charsets.detectBOM(Files.readAllBytes(utf16le))).isEqualTo(ByteOrderMark.UTF_16LE); assertThat(charsets.detectBOM(Files.readAllBytes(utf16be))).isEqualTo(ByteOrderMark.UTF_16BE); assertThat(charsets.detectBOM(Files.readAllBytes(utf32le))).isEqualTo(ByteOrderMark.UTF_32LE); assertThat(charsets.detectBOM(Files.readAllBytes(utf32be))).isEqualTo(ByteOrderMark.UTF_32BE); }

Target:
public void detectBOM() throws URISyntaxException, IOException { byte[] b = ByteOrderMark.UTF_16BE.getBytes(); assertThat(charsets.detectBOM(b)).isEqualTo(ByteOrderMark.UTF_16BE); assertThat(charsets.detectBOM(readFile("UTF-8"))).isEqualTo(ByteOrderMark.UTF_8); assertThat(charsets.detectBOM(readFile("UTF-16BE"))).isEqualTo(ByteOrderMark.UTF_16BE); assertThat(charsets.detectBOM(readFile("UTF-16LE"))).isEqualTo(ByteOrderMark.UTF_16LE); assertThat(charsets.detectBOM(readFile("UTF-32BE"))).isEqualTo(ByteOrderMark.UTF_32BE); assertThat(charsets.detectBOM(readFile("UTF-32LE"))).isEqualTo(ByteOrderMark.UTF_32LE); }
Source:
Judgment getJudgment() { return judgment; }

Target:
public Judgment getJudgment() { return judgment; }
Source:
public void shouldFindAllIdeasByTagId() throws Exception { long tagID = 1L; List<Idea> ideas = ideaRepository.findByUserId(tagID); assertThat(ideas).hasSize(1); assertThatIdea(ideas.get(0)) .hasId(1L) .hasTitle("Test title") .hasDescription("Test description") .hasRating(5); }

Target:
public void shouldFindAllIdeasByTagId() throws Exception { long tagID = 3L; List<Idea> ideas = ideaRepository.findByTagId(tagID); assertThat(ideas).hasSize(1); assertThatIdea(ideas.get(0)) .hasId(2L) .hasTitle("Test title") .hasDescription("Test description") .hasRating(5); }
Source:
public String _getVanishingItemsPolicy() { String value = config.getString("vanishing-items-policy", "keep").toLowerCase(Locale.ENGLISH); if (!value.equals("delete") && !value.equals("drop") && !value.equals("keep")) { value = "delete"; } return value; }

Target:
public KeepInvPolicy _getVanishingItemsPolicy() { String value = config.getString("vanishing-items-policy", "keep").toLowerCase(Locale.ENGLISH); try { return KeepInvPolicy.valueOf(value.toUpperCase(Locale.ENGLISH)); } catch (IllegalArgumentException e) { return KeepInvPolicy.KEEP; } }
Source:
public void build(GridBuilder builder, Coordinate coordinate) { builder.placeTeleporter(coordinate, null); }

Target:
public void build(GridBuilder builder, Coordinate coordinate) { builder.placeTeleporter(coordinate, destination); }
Source:
public InputStream decryptSecretValues() { log.debug("Scanning activiti.xml for Secret Alias attribute"); boolean hasSecretValue = false; Iterator iteratorBeans = activitiConfigElement.getChildrenWithLocalName("bean"); while (iteratorBeans.hasNext()) { Iterator iteratorProperties = ((OMElement) iteratorBeans.next()).getChildrenWithLocalName("property"); while (iteratorProperties.hasNext()) { OMElement propertyOMElement = (OMElement) iteratorProperties.next(); String secretValue = getSecureVaultValue(secretResolver, propertyOMElement); if (secretValue != null) { hasSecretValue = true; propertyOMElement.addAttribute("value", secretValue, null); propertyOMElement.removeAttribute( propertyOMElement.getAttribute( new QName(BPMNConstants.SECURE_VAULT_NS, BPMNConstants.SECRET_ALIAS_ATTR_NAME) ) ); } } } log.debug("Scanning complete"); if (hasSecretValue) { log.debug("Secret Alias found in activiti.xml"); InputStream activitiConfigStream = new ByteArrayInputStream(activitiConfigElement.toString().getBytes()); return activitiConfigStream; } else { log.debug("No Secret Alias found in activiti.xml"); return null; } }

Target:
public InputStream decryptSecretValues() { boolean hasSecretValue = false; Iterator iteratorBeans = activitiConfigElement.getChildrenWithLocalName("bean"); while (iteratorBeans.hasNext()) { Iterator iteratorProperties = ((OMElement) iteratorBeans.next()).getChildrenWithLocalName("property"); while (iteratorProperties.hasNext()) { OMElement propertyOMElement = (OMElement) iteratorProperties.next(); String secretValue = getSecureVaultValue(secretResolver, propertyOMElement); if (secretValue != null) { hasSecretValue = true; propertyOMElement.addAttribute("value", secretValue, null); propertyOMElement.removeAttribute( propertyOMElement.getAttribute( new QName(BPMNConstants.SECURE_VAULT_NS, BPMNConstants.SECRET_ALIAS_ATTR_NAME) ) ); } } } if (hasSecretValue) { InputStream activitiConfigStream = new ByteArrayInputStream(activitiConfigElement.toString().getBytes()); return activitiConfigStream; } else { return null; } }
Source:
public void testBuildServiceNameForToken() { String serviceID = "omService"; String nodeIDs = "om1,om2,om3"; configuration.set(OMConfigKeys.OZONE_OM_SERVICE_IDS_KEY, serviceID); configuration.set(OMConfigKeys.OZONE_OM_NODE_ID_KEY, nodeIDs); configuration.setBoolean(HADOOP_SECURITY_TOKEN_SERVICE_USE_IP, false); Collection<String> nodeIDList = configuration.getStringCollection( OMConfigKeys.OZONE_OM_NODE_ID_KEY); String expectedOmServiceAddress = buildOMNodeAddresses(nodeIDList, serviceID); SecurityUtil.setConfiguration(configuration); String omserviceAddr = OzoneS3Util.buildServiceNameForToken(configuration, serviceID, nodeIDList); Assert.assertEquals(expectedOmServiceAddress, omserviceAddr); }

Target:
public void testBuildServiceNameForToken() { Collection<String> nodeIDList = OmUtils.getOMNodeIds(configuration, serviceID); configuration.set(OmUtils.addKeySuffixes(OMConfigKeys.OZONE_OM_ADDRESS_KEY, serviceID, "om1"), "om1:9862"); configuration.set(OmUtils.addKeySuffixes(OMConfigKeys.OZONE_OM_ADDRESS_KEY, serviceID, "om2"), "om2:9862"); configuration.set(OmUtils.addKeySuffixes(OMConfigKeys.OZONE_OM_ADDRESS_KEY, serviceID, "om3"), "om3:9862"); String expectedOmServiceAddress = buildServiceAddress(nodeIDList); SecurityUtil.setConfiguration(configuration); String omserviceAddr = OzoneS3Util.buildServiceNameForToken(configuration, serviceID, nodeIDList); Assert.assertEquals(expectedOmServiceAddress, omserviceAddr); }
Source:
public DataDependentEDDifferentialPrivacy(double epsilonAnon, double epsilonSearch, double delta, int steps) { super(delta); this.epsilonAnon = epsilonAnon; this.epsilonSearch = epsilonSearch; this.beta = calculateBeta(epsilonAnon); this.k = calculateK(getDelta(), epsilonAnon, this.beta); this.steps = steps; }

Target:
public DataDependentEDDifferentialPrivacy(double epsilonAnon, double epsilonSearch, double delta, int steps) { this(epsilonAnon, epsilonSearch, delta, steps, false); }
Source:
protected ICompilationUnit getCompilationUnit(IJavaStackFrame frame) { ILaunch launch = frame.getLaunch(); if (launch == null) { return null; } try { IJavaElement sourceElement = JavaDebugUtils.resolveJavaElement(frame, launch); if (sourceElement instanceof ICompilationUnit) { return (ICompilationUnit) sourceElement; } return null; } catch (CoreException e) { return null; } }

Target:
protected ICompilationUnit getCompilationUnit(IJavaStackFrame frame) { ILaunch launch = frame.getLaunch(); if (launch == null) { return null; } try { IJavaElement sourceElement = JavaDebugUtils.resolveJavaElement(frame, launch); if (sourceElement instanceof IType) { return ((IType) sourceElement).getCompilationUnit(); } if (sourceElement instanceof ICompilationUnit) { return (ICompilationUnit) sourceElement; } return null; } catch (CoreException e) { return null; } }
Source:
private byte[] encrypt(final byte[] bytes) throws IOException { final byte[] encrypted; try (final Formatter formatter = new Formatter()) { for (final byte byt : this.create().doFinal(bytes)) { formatter.format("%02x", byt); } encrypted = formatter.toString().getBytes(); } return encrypted; }

Target:
private byte[] encrypt(final byte[] bytes) throws IOException { try (final Formatter formatter = new Formatter()) { for (final byte byt : this.create().doFinal(bytes)) { formatter.format("%02x", byt); } return formatter.toString().getBytes(); } }
Source:
void handleBookieFailure(final Map<Integer, BookieSocketAddress> failedBookies) { int curBlockAddCompletions = blockAddCompletions.incrementAndGet(); if (bk.disableEnsembleChangeFeature.isAvailable()) { blockAddCompletions.decrementAndGet(); if (LOG.isDebugEnabled()) { LOG.debug("Ensemble change is disabled. Retry sending to failed bookies for ledger {}.", failedBookies, ledgerId); } unsetSuccessAndSendWriteRequest(failedBookies.keySet()); return; } int curNumEnsembleChanges = numEnsembleChanges.incrementAndGet(); if (curNumEnsembleChanges > maxNumEnsembleChanges){ if (LOG.isDebugEnabled()) { LOG.debug("touch maxNumEnsembleChanges"); } handleUnrecoverableErrorDuringAdd(WriteException); return; } synchronized (metadata) { try { EnsembleInfo ensembleInfo = replaceBookieInMetadata(failedBookies, curNumEnsembleChanges); if (ensembleInfo.replacedBookies.isEmpty()) { blockAddCompletions.decrementAndGet(); return; } if (LOG.isDebugEnabled()) { LOG.debug("[EnsembleChange-L{}-{}] : writing new ensemble info = {}, block add completions = {}", getId(), curNumEnsembleChanges, ensembleInfo, curBlockAddCompletions); } writeLedgerConfig(new ChangeEnsembleCb(ensembleInfo, curBlockAddCompletions, curNumEnsembleChanges)); } catch (BKException.BKNotEnoughBookiesException e) { LOG.error("Could not get additional bookie to remake ensemble, closing ledger: {}", ledgerId); handleUnrecoverableErrorDuringAdd(e.getCode()); return; } } }

Target:
void handleBookieFailure(final Map<Integer, BookieSocketAddress> failedBookies) { int curBlockAddCompletions = blockAddCompletions.incrementAndGet(); if (bk.getDisableEnsembleChangeFeature().isAvailable()) { blockAddCompletions.decrementAndGet(); if (LOG.isDebugEnabled()) { LOG.debug("Ensemble change is disabled. Retry sending to failed bookies for ledger {}.", failedBookies, ledgerId); } unsetSuccessAndSendWriteRequest(failedBookies.keySet()); return; } int curNumEnsembleChanges = numEnsembleChanges.incrementAndGet(); if (curNumEnsembleChanges > maxAllowedEnsembleChanges){ if (LOG.isDebugEnabled()) { LOG.debug("Ledger reaches max allowed ensemble change number {}", ledgerId, maxAllowedEnsembleChanges); } handleUnrecoverableErrorDuringAdd(WriteException); return; } synchronized (metadata) { try { EnsembleInfo ensembleInfo = replaceBookieInMetadata(failedBookies, curNumEnsembleChanges); if (ensembleInfo.replacedBookies.isEmpty()) { blockAddCompletions.decrementAndGet(); return; } if (LOG.isDebugEnabled()) { LOG.debug("[EnsembleChange-L{}-{}] : writing new ensemble info = {}, block add completions = {}", getId(), curNumEnsembleChanges, ensembleInfo, curBlockAddCompletions); } writeLedgerConfig(new ChangeEnsembleCb(ensembleInfo, curBlockAddCompletions, curNumEnsembleChanges)); } catch (BKException.BKNotEnoughBookiesException e) { LOG.error("Could not get additional bookie to remake ensemble, closing ledger: {}", ledgerId); handleUnrecoverableErrorDuringAdd(e.getCode()); return; } } }
Source:
private void sendWarningForNonExportableDisks(List<Disk> nonExportableDisks) { if(!nonExportableDisks.isEmpty()) { final StringBuilder s = new StringBuilder(); for(Disk disk : nonExportableDisks) { if(s.length() > 0) { s.append(", "); } s.append(disk.getDiskAlias()); } getModel().setMessage(ConstantsManager.getInstance().getMessages().disksWillNotBePartOfTheExportedVMTemplate(s.toString())); } }

Target:
private void sendWarningForNonExportableDisks(List<Disk> nonExportableDisks) { if (!nonExportableDisks.isEmpty()) { final List<String> list = new ArrayList<String>(); for (Disk disk : nonExportableDisks) { list.add(disk.getDiskAlias()); } final String s = StringUtils.join(list, ", "); getModel().setMessage(ConstantsManager.getInstance().getMessages().disksWillNotBePartOfTheExportedVMTemplate(s)); } }
Source:
public final int[] checkQueueIntegrity() throws IOException { return queueFile.scanAll(); }

Target:
public final void checkQueueIntegrity() throws IOException { queueFile.checkQueueIntegrity(); }
Source:
public static PutRequest readFrom(DataInputStream stream, ClusterMap map) throws IOException { int correlationId = stream.readInt(); String clientId = Utils.readIntString(stream); BlobId id = new BlobId(stream, map); BlobProperties properties = BlobPropertiesSerDe.getBlobPropertiesFromStream(stream); ByteBuffer metadata = Utils.readIntBuffer(stream); long dataSize = stream.readLong(); BlobDataType dataType = BlobDataType.values()[stream.readShort()]; InputStream data = stream; return new PutRequest(correlationId, clientId, id, properties, metadata, data, dataSize, dataType, Put_Request_Version_V2); }

Target:
static PutRequest readFrom(DataInputStream stream, ClusterMap map) throws IOException { int correlationId = stream.readInt(); String clientId = Utils.readIntString(stream); BlobId id = new BlobId(stream, map); BlobProperties properties = BlobPropertiesSerDe.getBlobPropertiesFromStream(stream); ByteBuffer metadata = Utils.readIntBuffer(stream); BlobType blobType = BlobType.values()[stream.readShort()]; long blobSize = stream.readLong(); return new PutRequest(correlationId, clientId, id, properties, metadata, stream, blobSize, blobType, Put_Request_Version_V2); }
Source:
private void addUpdates(TextChangeManager changeManager, IProgressMonitor pm, RefactoringStatus status) throws CoreException { pm.beginTask("", fCus.length); for (ICompilationUnit fCu : fCus) { if (pm.isCanceled()) throw new OperationCanceledException(); addUpdates(changeManager, fCu, new SubProgressMonitor(pm, 1), status); } }

Target:
private void addUpdates(TextChangeManager changeManager, IProgressMonitor pm, RefactoringStatus status) throws CoreException { pm.beginTask("", fCus.length); for (ICompilationUnit cu : fCus) { if (pm.isCanceled()) throw new OperationCanceledException(); addUpdates(changeManager, cu, new SubProgressMonitor(pm, 1), status); } }
Source:
public synchronized void start() throws LifecycleException { if (isRunning) { throw new LifecycleException("Process already started"); } else { log.info("Starting Jmxtrans on : {}", configuration.getProcessConfigDirOrFile()); try { this.serverScheduler.start(); this.startupWatchdir(); this.startupSystem(); this.registerMBeans(); } catch (Exception e) { log.error(e.getMessage(), e); throw new LifecycleException(e); } Runtime.getRuntime().addShutdownHook(shutdownHook); isRunning = true; } }

Target:
public synchronized void start() throws LifecycleException { if (isRunning) { throw new LifecycleException("Process already started"); } else { log.info("Starting Jmxtrans on : {}", configuration.getProcessConfigDirOrFile()); try { this.serverScheduler.start(); this.startupWatchdir(); this.startupSystem(); } catch (Exception e) { log.error(e.getMessage(), e); throw new LifecycleException(e); } Runtime.getRuntime().addShutdownHook(shutdownHook); isRunning = true; } }
Source:
public String convertToString(Object o) { if(!(o instanceof Coord)){ log.error("Object is not of type Coord: " + o.getClass().toString()); return null; } Coord c = (Coord)o; return String.format(Locale.ROOT, "(%f;%f)", c.getX(), c.getY()); }

Target:
public String convertToString(Object o) { if(!(o instanceof Coord)){ log.error("Object is not of type Coord: " + o.getClass().toString()); return null; } Coord c = (Coord)o; return String.format("(%s;%s)", Double.toString(c.getX()), Double.toString(c.getY())); }
Source:
private void updateChannelTopic() { boolean hasTopic = channel.getTopic() != null; topicPane.setVisible(hasTopic); if (!hasTopic) { return; } String topic = channel.getTopic() == null ? "" : channel.getTopic(); Arrays.stream(topic.split("\\s")) .forEach(word -> { if (URL_REGEX_PATTERN.matcher(word).matches()) { Hyperlink link = new Hyperlink(word); link.setOnAction(event -> platformService.showDocument(word)); topicText.getChildren().add(link); } else { topicText.getChildren().add(new Label(word + " ")); } }); }

Target:
private void updateChannelTopic() { boolean hasTopic = !Strings.isNullOrEmpty(channel.getTopic()); topicPane.setVisible(hasTopic); if (!hasTopic) { return; } String topic = channel.getTopic(); Arrays.stream(topic.split("\\s")) .forEach(word -> { if (URL_REGEX_PATTERN.matcher(word).matches()) { Hyperlink link = new Hyperlink(word); link.setOnAction(event -> platformService.showDocument(word)); topicText.getChildren().add(link); } else { topicText.getChildren().add(new Label(word + " ")); } }); }
Source:
public void updateParticipantDoesNotTransferSubstudyIds() { Set<String> substudies = ImmutableSet.of("substudyA", "substudyB"); StudyParticipant participant = mockSubstudiesInRequest(substudies, substudies); mockHealthCodeAndAccountRetrieval(); account.getAccountSubstudies().add(AccountSubstudy.create(STUDY.getIdentifier(), "substudyC", ID)); account.getAccountSubstudies().add(AccountSubstudy.create(STUDY.getIdentifier(), "substudyA", ID)); participantService.updateParticipant(STUDY, participant); verify(accountDao).updateAccount(accountCaptor.capture(), any()); Set<AccountSubstudy> accountSubstudies = accountCaptor.getValue().getAccountSubstudies(); assertEquals(2, accountSubstudies.size()); AccountSubstudy substudyA = accountSubstudies.stream() .filter((as) -> as.getSubstudyId().equals("substudyC")).findAny().get(); assertEquals(STUDY.getIdentifier(), substudyA.getStudyId()); assertEquals(ID, substudyA.getAccountId()); AccountSubstudy substudyB = accountSubstudies.stream() .filter((as) -> as.getSubstudyId().equals("substudyA")).findAny().get(); assertEquals(STUDY.getIdentifier(), substudyB.getStudyId()); assertEquals(ID, substudyB.getAccountId()); }

Target:
public void updateParticipantDoesNotTransferSubstudyIds() { Set<String> substudies = ImmutableSet.of("substudyA", "substudyB"); StudyParticipant participant = mockSubstudiesInRequest(substudies, substudies); mockHealthCodeAndAccountRetrieval(); account.getAccountSubstudies().add(AccountSubstudy.create(STUDY.getIdentifier(), "substudyC", ID)); account.getAccountSubstudies().add(AccountSubstudy.create(STUDY.getIdentifier(), "substudyA", ID)); participantService.updateParticipant(STUDY, participant); verify(accountDao).updateAccount(accountCaptor.capture(), eq(null)); Set<AccountSubstudy> accountSubstudies = accountCaptor.getValue().getAccountSubstudies(); assertEquals(2, accountSubstudies.size()); AccountSubstudy substudyA = accountSubstudies.stream() .filter((as) -> as.getSubstudyId().equals("substudyC")).findAny().get(); assertEquals(STUDY.getIdentifier(), substudyA.getStudyId()); assertEquals(ID, substudyA.getAccountId()); AccountSubstudy substudyB = accountSubstudies.stream() .filter((as) -> as.getSubstudyId().equals("substudyA")).findAny().get(); assertEquals(STUDY.getIdentifier(), substudyB.getStudyId()); assertEquals(ID, substudyB.getAccountId()); }