auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { if (isPresent != null) { isPresent.flush(); if(!foundNulls) { isPresentOutStream.suppress(); if (rowIndexStream != null) { removeIsPresentPositions(); } } } OrcProto.StripeStatistics.Builder stripeStatsBuilder = OrcProto.StripeStatistics.newBuilder(); writeStripeStatistics(stripeStatsBuilder, this); stripeStatsBuilders.add(stripeStatsBuilder); foundNulls = false; builder.addColumns(getEncoding()); if (streamFactory.hasWriterTimeZone()) { builder.setWriterTimezone(TimeZone.getDefault().getID()); } if (rowIndexStream != null) { if (rowIndex.getEntryCount() != requiredIndexEntries) { throw new IllegalArgumentException("Column has wrong number of " + "index entries found: " + rowIndex.getEntryCount() + " expected: " + requiredIndexEntries); } rowIndex.build().writeTo(rowIndexStream); rowIndexStream.flush(); } rowIndex.clear(); rowIndexEntry.clear(); if (bloomFilterStream != null) { bloomFilterIndex.build().writeTo(bloomFilterStream); bloomFilterStream.flush(); bloomFilterIndex.clear(); bloomFilterEntry.clear(); } }

Target:
void writeStripe(OrcProto.StripeFooter.Builder builder, int requiredIndexEntries) throws IOException { if (isPresent != null) { isPresent.flush(); if(!foundNulls) { isPresentOutStream.suppress(); if (rowIndexStream != null) { removeIsPresentPositions(); } } } OrcProto.StripeStatistics.Builder stripeStatsBuilder = OrcProto.StripeStatistics.newBuilder(); writeStripeStatistics(stripeStatsBuilder, this); stripeStatsBuilders.add(stripeStatsBuilder); foundNulls = false; builder.addColumns(getEncoding()); if (streamFactory.hasWriterTimeZone()) { builder.setWriterTimezone(streamFactory.getTimeZone().getID()); } if (rowIndexStream != null) { if (rowIndex.getEntryCount() != requiredIndexEntries) { throw new IllegalArgumentException("Column has wrong number of " + "index entries found: " + rowIndex.getEntryCount() + " expected: " + requiredIndexEntries); } rowIndex.build().writeTo(rowIndexStream); rowIndexStream.flush(); } rowIndex.clear(); rowIndexEntry.clear(); if (bloomFilterStream != null) { bloomFilterIndex.build().writeTo(bloomFilterStream); bloomFilterStream.flush(); bloomFilterIndex.clear(); bloomFilterEntry.clear(); } }
Source:
private int threadIndex() { final int index = (int) Thread.currentThread().getId(); return STRIDE * (index & (stripes - 1)); }

Target:
private int threadIndex() { final int index = (int) Thread.currentThread().getId(); return STRIDE * (index & stripeMask); }
Source:
@Test public void performSubmitWithFetchActionWithSuccessCompletionCallback() { String pausedTag = "pausedTag"; dispatcher.pausedTags.add(pausedTag); assertThat(dispatcher.pausedActions).isEmpty(); Callback callback = mockCallback(); FetchAction fetchAction1 = new FetchAction(mockPicasso(), new Request.Builder(URI_1).build(), false, URI_KEY_1, pausedTag, callback); dispatcher.performSubmit(fetchAction1); fetchAction1.complete(bitmap1, MEMORY); verify(callback).onSuccess(); assertThat(dispatcher.pausedActions).hasSize(1); }

Target:
@Test public void performSubmitWithFetchActionWithSuccessCompletionCallback() { String pausedTag = "pausedTag"; Callback callback = mockCallback(); FetchAction fetchAction = new FetchAction(mockPicasso(), new Request.Builder(URI_1).build(), 0, 0, pausedTag, URI_KEY_1, callback); dispatcher.performSubmit(fetchAction); fetchAction.complete(bitmap1, MEMORY); verify(callback).onSuccess(); }
Source:
public void recreateSocketAddresses() { InetAddress address = null; try { address = getReachableAddress(this.hostname, 2000); LOG.info("Resolved hostname: to address: {}", this.hostname, address); this.addr = new InetSocketAddress(address, this.port); if (this.electionPort > 0){ this.electionAddr = new InetSocketAddress(address, this.electionPort); } } catch (UnknownHostException ex) { LOG.warn("Failed to resolve address: {}", this.hostname, ex); if (this.addr != null) { return; } this.addr = InetSocketAddress.createUnresolved(this.hostname, this.port); if (this.electionPort > 0){ this.electionAddr = InetSocketAddress.createUnresolved(this.hostname, this.electionPort); } } }

Target:
public void recreateSocketAddresses() { InetAddress address = null; try { int ipReachableTimeout = 0; String ipReachableValue = System.getProperty("zookeeper.ipReachableTimeout"); if (ipReachableValue != null) { try { ipReachableTimeout = Integer.parseInt(ipReachableValue); } catch (NumberFormatException e) { LOG.error("{} is not a valid number", ipReachableValue); } } if (ipReachableTimeout <= 0) { address = InetAddress.getByName(this.hostname); } else { address = getReachableAddress(this.hostname, ipReachableTimeout); } LOG.info("Resolved hostname: to address: {}", this.hostname, address); this.addr = new InetSocketAddress(address, this.port); if (this.electionPort > 0){ this.electionAddr = new InetSocketAddress(address, this.electionPort); } } catch (UnknownHostException ex) { LOG.warn("Failed to resolve address: {}", this.hostname, ex); if (this.addr != null) { return; } this.addr = InetSocketAddress.createUnresolved(this.hostname, this.port); if (this.electionPort > 0){ this.electionAddr = InetSocketAddress.createUnresolved(this.hostname, this.electionPort); } } }
Source:
private SettableFuture<Boolean> logFenceEntryInJournal(Journal journal) { SettableFuture<Boolean> result; synchronized (this) { result = logFenceResult = SettableFuture.create(); } ByteBuf entry = createLedgerFenceEntry(ledgerId); journal.logAddEntry(entry, (rc, ledgerId, entryId, addr, ctx) -> { LOG.debug("Record fenced state for ledger in journal with rc {}", ledgerId, BKException.codeLogger(rc)); if (rc == 0) { fenceEntryPersisted.compareAndSet(false, true); result.set(true); } else { result.set(false); } }, null); return result; }

Target:
private SettableFuture<Boolean> logFenceEntryInJournal(Journal journal) { SettableFuture<Boolean> result; synchronized (this) { result = logFenceResult = SettableFuture.create(); } ByteBuf entry = createLedgerFenceEntry(ledgerId); journal.logAddEntry(entry, (rc, ledgerId, entryId, addr, ctx) -> { if (LOG.isDebugEnabled()) { LOG.debug("Record fenced state for ledger in journal with rc {}", ledgerId, BKException.codeLogger(rc)); } if (rc == 0) { fenceEntryPersisted.compareAndSet(false, true); result.set(true); } else { result.set(false); } }, null); return result; }
Source:
public void shouldSerializeServerConfigToJSON() { ServerConfig serverConfig = new ServerConfig(); serverConfig.ensureServerIdExists(); serverConfig.setSecureSiteUrl("<LINK_1>"); serverConfig.setSiteUrl("<LINK_0>"); CurrentGoCDVersion goCDVersion = CurrentGoCDVersion.getInstance(); MessageHandlerForServerInfoRequestProcessor2_0 processor = new MessageHandlerForServerInfoRequestProcessor2_0(); assertThat(processor.serverInfoToJSON(serverConfig), is(format("{\"server_id\":\"%s\",\"site_url\":\"%s\",\"secure_site_url\":\"%s\"," + "\"go_version\":\"%s\"," + "\"dist_version\":\"%s\"," + "\"git_revision\":\"%s\"" + "}", serverConfig.getServerId(), serverConfig.getSiteUrl().getUrl(), serverConfig.getSecureSiteUrl().getUrl(), goCDVersion.goVersion(), goCDVersion.distVersion(), goCDVersion.gitRevision() ))); }

Target:
public void shouldSerializeServerConfigToJSON() { ServerConfig serverConfig = new ServerConfig(); serverConfig.ensureServerIdExists(); serverConfig.setSecureSiteUrl("<LINK_1>"); serverConfig.setSiteUrl("<LINK_0>"); CurrentGoCDVersion goCDVersion = CurrentGoCDVersion.getInstance(); MessageHandlerForServerInfoRequestProcessor2_0 processor = new MessageHandlerForServerInfoRequestProcessor2_0(); String expectedJsonStr = format("{\"server_id\":\"%s\"," + "\"site_url\":\"%s\"," + "\"secure_site_url\":\"%s\"," + "\"go_version\":\"%s\"," + "\"dist_version\":\"%s\"," + "\"git_revision\":\"%s\"" + "}", serverConfig.getServerId(), serverConfig.getSiteUrl().getUrl(), serverConfig.getSecureSiteUrl().getUrl(), goCDVersion.goVersion(), goCDVersion.distVersion(), goCDVersion.gitRevision() ); assertThatJson(expectedJsonStr).isEqualTo(processor.serverInfoToJSON(serverConfig)); }
Source:
private byte[] generateZeroRowFile( ConnectorSession session, HdfsContext hdfsContext, Properties properties, String serDe, String outputFormatName, HiveCompressionCodec compressionCodec) { String tmpDirectoryPath = System.getProperty("java.io.tmpdir"); String tmpFileName = format("presto-hive-zero-row-file-creator-%s-%s", session.getQueryId(), randomUUID().toString()); java.nio.file.Path tmpFilePath = Paths.get(tmpDirectoryPath, tmpFileName); try { Path target = new Path(format("file://%s/%s", tmpDirectoryPath, tmpFileName)); JobConf conf = configureCompression(hdfsEnvironment.getConfiguration(hdfsContext, target), compressionCodec); initializeSerializer(conf, properties, serDe); RecordWriter recordWriter = HiveWriteUtils.createRecordWriter( target, conf, properties, outputFormatName, session); recordWriter.close(false); return readAllBytes(tmpFilePath); } catch (IOException e) { throw new UncheckedIOException(e); } finally { if (exists(tmpFilePath)) { try { delete(tmpFilePath); } catch (IOException e) { log.error(e, "Error deleting temporary file: %s", tmpFilePath); } } } }

Target:
private byte[] generateZeroRowFile( ConnectorSession session, HdfsContext hdfsContext, Properties properties, String serDe, String outputFormatName, HiveCompressionCodec compressionCodec) { String tmpDirectoryPath = System.getProperty("java.io.tmpdir"); String tmpFileName = format("presto-hive-zero-row-file-creator-%s-%s", session.getQueryId(), randomUUID().toString()); java.nio.file.Path tmpFilePath = Paths.get(tmpDirectoryPath, tmpFileName); try { Path target = new Path(format("file://%s/%s", tmpDirectoryPath, tmpFileName)); JobConf conf = configureCompression(hdfsEnvironment.getConfiguration(hdfsContext, target), compressionCodec); initializeSerializer(conf, properties, serDe); RecordWriter recordWriter = HiveWriteUtils.createRecordWriter( target, conf, properties, outputFormatName, session); recordWriter.close(false); return readAllBytes(tmpFilePath); } catch (IOException e) { throw new UncheckedIOException(e); } finally { try { deleteIfExists(tmpFilePath); } catch (IOException e) { log.error(e, "Error deleting temporary file: %s", tmpFilePath); } } }
Source:
private void checkRequiresCapability() throws RuntimeException { RequiresCapability rc = getClass().getAnnotation(RequiresCapability.class); if (rc != null) { CurrentUser user = currentUser.get(); CapabilityControl ctl = user.getCapabilities(); if (!ctl.canPerform(rc.value()) && !ctl.canAdministrateServer()) { String msg = String.format( "fatal: %s does not have \"%s\" capability.", user.getUserName(), rc.value()); throw new RuntimeException(msg); } } }

Target:
private void checkRequiresCapability() throws RequireCapabilityException { RequiresCapability rc = getClass().getAnnotation(RequiresCapability.class); if (rc != null) { CurrentUser user = currentUser.get(); CapabilityControl ctl = user.getCapabilities(); if (!ctl.canPerform(rc.value()) && !ctl.canAdministrateServer()) { String msg = String.format( "fatal: %s does not have \"%s\" capability.", user.getUserName(), rc.value()); throw new RequireCapabilityException(msg); } } }
Source:
public List<ConfigurationMetadataProperty> listProperties(Resource app, boolean exhaustive) { try { if (app != null) { if (isDockerSchema(app.getURI())) { String imageName = app.getURI().getSchemeSpecificPart(); Map<String, String> labels = this.containerImageMetadataResolver.getImageLabels(imageName); if (CollectionUtils.isEmpty(labels)) { return Collections.emptyList(); } String encodedMetadata = labels.get(CONTAINER_IMAGE_CONFIGURATION_METADATA_LABEL_NAME); if (!StringUtils.hasText(encodedMetadata)) { return Collections.emptyList(); } String metadataJson = new String(Base64.getDecoder().decode(encodedMetadata.getBytes())); try { ConfigurationMetadataRepository configurationMetadataRepository = ConfigurationMetadataRepositoryJsonBuilder.create().withJsonResource(new ByteArrayInputStream(metadataJson.getBytes())).build(); List<ConfigurationMetadataProperty> result = configurationMetadataRepository.getAllProperties().entrySet().stream() .map(e -> e.getValue()) .collect(Collectors.toList()); return result; } catch (Exception e) { throw new AppMetadataResolutionException("Invalid Metadata JSON format: " + metadataJson); } } else { Archive archive = resolveAsArchive(app); return listProperties(archive, exhaustive); } } } catch (Exception e) { throw new AppMetadataResolutionException("Failed to resolve application resource: " + app.getDescription(), e); } return Collections.emptyList(); }

Target:
public List<ConfigurationMetadataProperty> listProperties(Resource app, boolean exhaustive) { try { if (app != null) { if (isDockerSchema(app.getURI())) { return resolvePropertiesFromContainerImage(app.getURI()); } else { Archive archive = resolveAsArchive(app); return listProperties(archive, exhaustive); } } } catch (Exception e) { throw new AppMetadataResolutionException("Failed to resolve application resource: " + app.getDescription(), e); } return Collections.emptyList(); }
Source:
public int length() { switch (vlanIDs.size()) { case 0: return 14 + childLength(); case 1: return 14 + 4 + childLength(); default: return 14 + 8 + childLength(); } }

Target:
public int length() { int len = MIN_HEADER_LEN + vlanIDs.size() * 4 + childLength(); return pad ? Math.max(len, 60) : len; }
Source:
public static String join(String[] array) { StringBuilder sb = new StringBuilder(); boolean first = true; for (String s : array) { if (first) { first = false; } else { sb.append('.'); } sb.append(s); } return sb.toString(); }

Target:
public static String join(String[] array) { return join(Arrays.asList(array)); }
Source:
public void shouldRejectNoAlternateVariants() throws Exception { Variant input = new Variant("1", 1000, 1001, "A", "."); Variant output = processor.process(input); assertEquals(Variant.VariantType.NO_ALTERNATE, input.getType()); assertNull(output); }

Target:
public void shouldRejectNoAlternateVariants() throws Exception { Variant input = new Variant("1", 1000, 1000, "A", "."); Variant output = processor.process(input); assertEquals(Variant.VariantType.NO_ALTERNATE, input.getType()); assertNull(output); }
Source:
public void created( BoltConnection connection ) { activeConnections.put( connection.id(), connection ); }

Target:
public void created( BoltConnection connection ) { BoltConnection previous = activeConnections.put( connection.id(), connection ); assert previous == null; }
Source:
public void run() { try { int i = start; OpenTsdbClient client = null; while (i < end && !Thread.interrupted()) { if (client == null) { client = clientPool.get(); } try { String message = convert(metrics[i]); client.put(message); ++i; } catch (IOException ex) { log.error("Failed to write metric:", ex); clientPool.kill(client); client = null; } } service.incrementTotalProcessed(end - start); if (client != null) { try { client.flush(); String response = client.read(); if (response != null) { log.warn("Error detected writing metrics: {}", response); service.incrementTotalError(1); } } catch (SocketTimeoutException ex) { } catch (IOException ex) { log.error("Failed flushing or reading opentsdb response:", ex); clientPool.kill(client); client = null; } } if (client != null) clientPool.put(client); } catch (InterruptedException ignored) { } }

Target:
public void run() { try { OpenTsdbClient client = null; int i = 0; long size = metrics.size(); try { while (i < size && !Thread.interrupted()) { if (client == null) { client = clientPool.get(); } try { Metric metric = metrics.get(i); String message = convert(metric); client.put(message); ++i; } catch (IOException ex) { log.error("Failed to write metric:", ex); clientPool.kill(client); client = null; } } incrementProcessed(size, i); if (client != null) { try { client.flush(); String response = client.read(); if (response != null) { log.warn("Error detected writing metrics: {}", response); incrementError(); } } catch (SocketTimeoutException ex) { } catch (IOException ex) { log.error("Failed flushing or reading opentsdb response:", ex); clientPool.kill(client); client = null; } } } finally { if (client != null) { clientPool.put(client); client = null; } } } catch (InterruptedException ignored) { } }
Source:
public void run() { try { LOG.info("Running Chaos Agent on : " + agentName); while (!this.isConnected()) { Thread.sleep(100); } this.getTasks(); while (!stopChaosAgent.get()) { Thread.sleep(500); } } catch (InterruptedException e) { LOG.error("Error while running Chaos Agent"); } }

Target:
public void run() { try { LOG.info("Running Chaos Agent on : " + agentName); while (!this.isConnected()) { Thread.sleep(100); } this.getTasks(); while (!stopChaosAgent.get()) { Thread.sleep(500); } } catch (InterruptedException e) { LOG.error("Error while running Chaos Agent", e); } }
Source:
public void initStore(final Store<?, ?> resource) { StoreConfig storeConfig = createdStores.get(resource); if (storeConfig == null) { throw new IllegalArgumentException("Given store is not managed by this provider : " + resource); } final ClusteredStore clusteredStore = (ClusteredStore) resource; try { clusteredStore.storeProxy = clusteringService.getServerStoreProxy(storeConfig.getCacheIdentifier(), storeConfig.getStoreConfig(), storeConfig.getConsistency()); clusteredStore.storeProxy.addInvalidationListener(new ServerStoreProxy.InvalidationListener() { @Override public void onInvalidateHash(long hash) { if (clusteredStore.invalidationValve != null) { try { LOGGER.debug("CLIENT: calling invalidation valve for hash {}", hash); clusteredStore.invalidationValve.invalidateAllWithHash(hash); } catch (StoreAccessException sae) { LOGGER.error("Error invalidating hash {}", hash, sae); } } } @Override public void onInvalidateAll() { if (clusteredStore.invalidationValve != null) { try { LOGGER.debug("CLIENT: calling invalidation valve for all"); clusteredStore.invalidationValve.invalidateAll(); } catch (StoreAccessException sae) { LOGGER.error("Error invalidating all", sae); } } } }); } catch (CachePersistenceException e) { throw new RuntimeException("Unable to create server store proxy - " + storeConfig.getCacheIdentifier(), e); } }

Target:
public void initStore(final Store<?, ?> resource) { StoreConfig storeConfig = createdStores.get(resource); if (storeConfig == null) { throw new IllegalArgumentException("Given store is not managed by this provider : " + resource); } final ClusteredStore clusteredStore = (ClusteredStore) resource; try { clusteredStore.storeProxy = clusteringService.getServerStoreProxy(storeConfig.getCacheIdentifier(), storeConfig.getStoreConfig(), storeConfig.getConsistency()); } catch (CachePersistenceException e) { throw new RuntimeException("Unable to create server store proxy - " + storeConfig.getCacheIdentifier(), e); } clusteredStore.storeProxy.addInvalidationListener(new ServerStoreProxy.InvalidationListener() { @Override public void onInvalidateHash(long hash) { if (clusteredStore.invalidationValve != null) { try { LOGGER.debug("CLIENT: calling invalidation valve for hash {}", hash); clusteredStore.invalidationValve.invalidateAllWithHash(hash); } catch (StoreAccessException sae) { LOGGER.error("Error invalidating hash {}", hash, sae); } } } @Override public void onInvalidateAll() { if (clusteredStore.invalidationValve != null) { try { LOGGER.debug("CLIENT: calling invalidation valve for all"); clusteredStore.invalidationValve.invalidateAll(); } catch (StoreAccessException sae) { LOGGER.error("Error invalidating all", sae); } } } }); }
Source:
public void activate() { logger.info("active"); setProperlyConfigured(true); }

Target:
public void activate() { logger.info("active"); }
Source:
public ImmutableDruidDataSource toImmutableDruidDataSource() { return new ImmutableDruidDataSource(name, properties, partitionNames, Collections.unmodifiableSet(segmentsHolder)); }

Target:
public ImmutableDruidDataSource toImmutableDruidDataSource() { return new ImmutableDruidDataSource( name, ImmutableMap.copyOf(properties), ImmutableMap.copyOf(partitionNames), ImmutableSet.copyOf(segmentsHolder) ); }
Source:
public void shouldAllowRequestWithValidToken() throws IOException, ServletException { when(request.getHeader(eq("Authentication"))).thenReturn("Talend myToken"); filter.doFilter(request, response, filterChain); assertNotNull(capturedContext.get()); final Authentication authentication = capturedContext.get().getAuthentication(); assertNotNull(authentication); assertTrue(authentication.getAuthorities().stream().allMatch(g -> { final String authority = g.getAuthority(); return "ROLE_ACTUATOR".equals(authority) || "ROLE_VERSION".equals(authority); })); }

Target:
public void shouldAllowRequestWithValidToken() throws IOException, ServletException { when(request.getServletPath()).thenReturn("/actuator/prometheus"); when(request.getHeader(eq("Authorization"))).thenReturn("Talend myToken"); filter.doFilter(request, response, filterChain); assertNotNull(capturedAuthentication.get()); final Authentication authentication = capturedAuthentication.get(); assertTrue(authentication.getAuthorities().stream().allMatch(g -> { final String authority = g.getAuthority(); return "ROLE_ACTUATOR".equals(authority); })); }
Source:
public NextAction repeat(StateExecution execution) { System.out.println("Counter: " + execution.getVariable(VAR_COUNTER)); execution.setVariable(VAR_COUNTER, execution.getVariable(VAR_COUNTER, Integer.class) + 1); return NextAction.moveToStateAfter(State.repeat, DateTime.now().plusSeconds(10), "Next iteration"); }

Target:
public NextAction repeat(StateExecution execution) { System.out.println("Counter: " + execution.getVariable(VAR_COUNTER)); execution.setVariable(VAR_COUNTER, execution.getVariable(VAR_COUNTER, Integer.class) + 1); return moveToStateAfter(State.repeat, now().plusSeconds(10), "Next iteration"); }
Source:
private void cleanupStack() { if (!stack.empty()) { RowType stackTop = stack.peek().getType(); switch (stackTop) { case SINGLE: break; case MULTI_START: stack.peek().setRowType(RowType.SINGLE); break; case MULTI_MID: stack.peek().setRowType(RowType.MULTI_END); break; case MULTI_END: break; case FIRST_ROW: break; } stack.clear(); } }

Target:
private void cleanupStack() { if (!stack.empty()) { RowType stackTop = stack.peek().getType(); switch (stackTop) { case SINGLE: break; case MULTI_START: stack.peek().setRowType(RowType.SINGLE); break; case MULTI_MID: stack.peek().setRowType(RowType.MULTI_END); break; case MULTI_END: break; case FIRST_ROW: break; default: throw new OseeStateException("Unhandled enumeration", stackTop); } stack.clear(); } }
Source:
public Long create(Sample sample) throws IOException { loadChildEntities(sample); authorizationManager.throwIfNotWritable(sample); setChangeDetails(sample, true); if (sample.getSampleAdditionalInfo() != null) { if (sample.getSampleAdditionalInfo().getSampleClass() == null || sample.getSampleAdditionalInfo().getSampleClass().getSampleCategory() == null) { throw new IllegalArgumentException("Sample class or category missing"); } if (!Identity.CATEGORY_NAME.equals(sample.getSampleAdditionalInfo().getSampleClass().getSampleCategory())) { sample.getSampleAdditionalInfo().setParent(findOrCreateParent(sample)); validateHierarchy(sample); if (sample.getSampleAdditionalInfo().getGroupId() == null) { sample.getSampleAdditionalInfo().setGroupId(sample.getSampleAdditionalInfo().getParent().getSampleAdditionalInfo().getGroupId()); } if (sample.getSampleAdditionalInfo().getGroupDescription() == null) { sample.getSampleAdditionalInfo() .setGroupDescription(sample.getSampleAdditionalInfo().getParent().getSampleAdditionalInfo().getGroupDescription()); } } } sample.setName(generateTemporaryName()); if (isStringEmptyOrNull(sample.getAlias()) && sampleNamingScheme.hasGeneratorFor("alias")) { sample.setAlias(generateTemporaryName()); } else { validateAliasUniqueness(sample.getAlias()); } if (sample.getSampleAdditionalInfo() != null && sample.getParent() != null) { int siblingNumber = sampleDao.getNextSiblingNumber(sample.getParent(), sample.getSampleAdditionalInfo().getSampleClass()); sample.getSampleAdditionalInfo().setSiblingNumber(siblingNumber); } normalizeSample(sample); return save(sample).getId(); }

Target:
public Long create(Sample sample) throws IOException { loadChildEntities(sample); authorizationManager.throwIfNotWritable(sample); setChangeDetails(sample, true); if (sample.getSampleAdditionalInfo() != null) { if (sample.getSampleAdditionalInfo().getSampleClass() == null || sample.getSampleAdditionalInfo().getSampleClass().getSampleCategory() == null) { throw new IllegalArgumentException("Sample class or category missing"); } if (!Identity.CATEGORY_NAME.equals(sample.getSampleAdditionalInfo().getSampleClass().getSampleCategory())) { sample.getSampleAdditionalInfo().setParent(findOrCreateParent(sample)); validateHierarchy(sample); } } sample.setName(generateTemporaryName()); if (isStringEmptyOrNull(sample.getAlias()) && sampleNamingScheme.hasGeneratorFor("alias")) { sample.setAlias(generateTemporaryName()); } else { validateAliasUniqueness(sample.getAlias()); } if (sample.getSampleAdditionalInfo() != null && sample.getParent() != null) { int siblingNumber = sampleDao.getNextSiblingNumber(sample.getParent(), sample.getSampleAdditionalInfo().getSampleClass()); sample.getSampleAdditionalInfo().setSiblingNumber(siblingNumber); } normalizeSample(sample); return save(sample).getId(); }
Source:
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .subscriptionKey(Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_SUBSCRIPTION_KEY")) .endpoint(Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_ENDPOINT")) .buildClient(); String text = "Satya Nadella is the CEO of Microsoft"; client.recognizeEntities(text).getNamedEntities().forEach( entity -> System.out.printf( "Recognized NamedEntity: %s, NamedEntity Type: %s, NamedEntity Subtype: %s, Offset: %s, Length: %s, Score: %s", entity.getText(), entity.getType(), entity.getSubtype(), entity.getOffset(), entity.getLength(), entity.getScore())); }

Target:
public static void main(String[] args) { TextAnalyticsClient client = new TextAnalyticsClientBuilder() .subscriptionKey("subscription-key") .endpoint("<LINK_0>") .buildClient(); String text = "Satya Nadella is the CEO of Microsoft"; for (NamedEntity entity : client.recognizeEntities(text).getNamedEntities()) { System.out.printf( "Recognized NamedEntity: %s, NamedEntity Type: %s, NamedEntity Subtype: %s, Offset: %s, Length: %s, Score: %s.%n", entity.getText(), entity.getType(), entity.getSubtype(), entity.getOffset(), entity.getLength(), entity.getScore()); } }
Source:
URLConnection openURLConnection(URI object) throws IOException { URLConnection urlConnection = object.toURL().openConnection(); if (!"".equals(httpAuthenticationUsername) && !"".equals(httpAuthenticationPasswordProvider.getPassword())) { String userPass = httpAuthenticationUsername + ":" + httpAuthenticationPasswordProvider.getPassword(); String basicAuthString = "Basic " + Base64.getEncoder().encodeToString(StringUtils.toUtf8(userPass)); urlConnection.setRequestProperty("Authorization", basicAuthString); } return urlConnection; }

Target:
URLConnection openURLConnection(URI object) throws IOException { URLConnection urlConnection = object.toURL().openConnection(); if (!Strings.isNullOrEmpty(httpAuthenticationUsername) && httpAuthenticationPasswordProvider != null) { String userPass = httpAuthenticationUsername + ":" + httpAuthenticationPasswordProvider.getPassword(); String basicAuthString = "Basic " + Base64.getEncoder().encodeToString(StringUtils.toUtf8(userPass)); urlConnection.setRequestProperty("Authorization", basicAuthString); } return urlConnection; }
Source:
public RolledUpUsageModelDao(final UUID id, final DateTime createdDate, final DateTime updatedDate, final UUID subscriptionId, final String unitType, final LocalDate recordDate, final Long amount, final String trackingId) { super(id, createdDate, updatedDate); this.subscriptionId = subscriptionId; this.unitType = unitType; this.recordDate = recordDate; this.amount = amount; if(Strings.isNullOrEmpty(trackingId)){ this.trackingId = UUID.randomUUID().toString(); } else { this.trackingId = trackingId; } }

Target:
public RolledUpUsageModelDao(final UUID id, final DateTime createdDate, final DateTime updatedDate, final UUID subscriptionId, final String unitType, final LocalDate recordDate, final Long amount, final String trackingId) { super(id, createdDate, updatedDate); this.subscriptionId = subscriptionId; this.unitType = unitType; this.recordDate = recordDate; this.amount = amount; if(Strings.isNullOrEmpty(trackingId)){ this.trackingId = UUIDs.randomUUID().toString(); } else { this.trackingId = trackingId; } }
Source:
private String getXForwardHeader(HttpServletRequest httpRequest) { Enumeration<String> names = httpRequest.getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); Enumeration<String> values = httpRequest.getHeaders(name); String value = ""; if (values != null) { while (values.hasMoreElements()) { value = values.nextElement(); } } if (StringUtils.trimToNull(name) != null && StringUtils.trimToNull(value) != null) { if (name.equalsIgnoreCase(TRUSTED_PROXY_KNOX_HEADER)) { return value; } } } return ""; }

Target:
private String getXForwardHeader(HttpServletRequest httpRequest) { Enumeration<String> names = httpRequest.getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); Enumeration<String> values = httpRequest.getHeaders(name); String value = ""; if (values != null) { while (values.hasMoreElements()) { value = values.nextElement(); if (StringUtils.isNotBlank(value)) { break; } } } if (StringUtils.trimToNull(name) != null && StringUtils.trimToNull(value) != null) { if (name.equalsIgnoreCase(TRUSTED_PROXY_KNOX_HEADER)) { return value; } } } return ""; }
Source:
public void addEvent(IEventDeclaration event) throws ParseException { if (fEventUnsetId != null) { throw new ParseException("Event without id with multiple events in a stream"); } int id = ((EventDeclaration) event).id(); if (id == EventDeclaration.UNSET_EVENT_ID) { if (!fEvents.isEmpty()) { throw new ParseException("Event without id with multiple events in a stream"); } fEventUnsetId = event; } else { List<IEventDeclaration> eventsList = new ArrayList<>(); eventsList.addAll(fEvents); if (eventsList.size() > id && eventsList.get(id) != UNASSIGNED) { throw new ParseException("Event id already exists"); } while (eventsList.size() <= id) { eventsList.add(UNASSIGNED); } if (eventsList.get(id) == UNASSIGNED) { eventsList.set(id, event); } else { eventsList.add(event); } fEvents = ImmutableList.copyOf(eventsList); } }

Target:
public void addEvent(IEventDeclaration event) throws ParseException { if (fEventUnsetId) { throw new ParseException("Event without id with multiple events in a stream"); } int id = ((EventDeclaration) event).id(); if (id == EventDeclaration.UNSET_EVENT_ID) { if (!fEvents.isEmpty()) { throw new ParseException("Event without id with multiple events in a stream"); } fEventUnsetId = true; fEvents = ImmutableList.<IEventDeclaration>of(event); } else { List<IEventDeclaration> eventsList = new ArrayList<>(); eventsList.addAll(fEvents); if (eventsList.size() > id && eventsList.get(id) != UNASSIGNED) { throw new ParseException("Event id already exists"); } while (eventsList.size() <= id) { eventsList.add(UNASSIGNED); } if (eventsList.get(id) == UNASSIGNED) { eventsList.set(id, event); } else { eventsList.add(event); } fEvents = ImmutableList.copyOf(eventsList); } }
Source:
public void setUp() { final InMemoryStorageFactory storageFactory = InMemoryStorageFactory.getInstance(); commandStore = spy(new CommandStore(storageFactory.createCommandStorage())); scheduler = spy(new ExecutorCommandScheduler()); log = spy(new ProblemLog()); commandBus = new CommandBus(commandStore, scheduler, log); eventBus = Given.Event.newEventBus(storageFactory); commandFactory = TestCommandFactory.newInstance(CommandBusShould.class); createProjectHandler = new CreateProjectHandler(newUuid()); responseObserver = new TestResponseObserver(); }

Target:
public void setUp() { final InMemoryStorageFactory storageFactory = InMemoryStorageFactory.getInstance(); commandStore = spy(new CommandStore(storageFactory.createCommandStorage())); scheduler = spy(new ExecutorCommandScheduler()); log = spy(new ProblemLog()); commandBus = new CommandBus(commandStore, scheduler, log); eventBus = EventBusFactory.create(storageFactory); commandFactory = TestCommandFactory.newInstance(CommandBusShould.class); createProjectHandler = new CreateProjectHandler(newUuid()); responseObserver = new TestResponseObserver(); }
Source:
public void saveScreenshot() { FBO sceneFinalFbo = displayResolutionDependentFBOs.get(new ResourceUrn("engine:sceneFinal")); final ByteBuffer buffer = sceneFinalFbo.getColorBufferRawData(); if (buffer == null) { logger.error("No screenshot data available. No screenshot will be saved."); return; } int width = sceneFinalFbo.width(); int height = sceneFinalFbo.height(); Runnable task = () -> { SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"); final String format = renderingConfig.getScreenshotFormat(); final String fileName = "Terasology-" + sdf.format(new Date()) + "-" + width + "x" + height + "." + format; Path path = PathManager.getInstance().getScreenshotPath().resolve(fileName); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int i = (x + width * y) * 4; int r = buffer.get(i) & 0xFF; int g = buffer.get(i + 1) & 0xFF; int b = buffer.get(i + 2) & 0xFF; image.setRGB(x, height - (y + 1), (0xFF << 24) | (r << 16) | (g << 8) | b); } } try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(path))) { ImageIO.write(image, format, out); logger.info("Screenshot '" + fileName + "' saved! "); } catch (IOException e) { logger.warn("Failed to save screenshot!", e); } }; threadManager.submitTask("Write screenshot", task); isTakingScreenshot = false; }

Target:
public void saveScreenshot() { if (displayResolutionDependentFBOs == null) displayResolutionDependentFBOs = CoreRegistry.get(DisplayResolutionDependentFBOs.class); FBO sceneFinalFbo = displayResolutionDependentFBOs.get(FINAL_BUFFER); final ByteBuffer buffer = sceneFinalFbo.getColorBufferRawData(); if (buffer == null) { logger.error("No screenshot data available. No screenshot will be saved."); return; } int width = sceneFinalFbo.width(); int height = sceneFinalFbo.height(); Runnable task = () -> { SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"); final String format = renderingConfig.getScreenshotFormat(); final String fileName = "Terasology-" + sdf.format(new Date()) + "-" + width + "x" + height + "." + format; Path path = PathManager.getInstance().getScreenshotPath().resolve(fileName); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int i = (x + width * y) * 4; int r = buffer.get(i) & 0xFF; int g = buffer.get(i + 1) & 0xFF; int b = buffer.get(i + 2) & 0xFF; image.setRGB(x, height - (y + 1), (0xFF << 24) | (r << 16) | (g << 8) | b); } } try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(path))) { ImageIO.write(image, format, out); logger.info("Screenshot '" + fileName + "' saved! "); } catch (IOException e) { logger.warn("Failed to save screenshot!", e); } }; threadManager.submitTask("Write screenshot", task); isTakingScreenshot = false; }
Source:
public VelocityNavigateEditMode( final HttpServletRequest request, final HttpServletResponse response, final IHTMLPage htmlPage, final Host host) { super(request, response, htmlPage, host); uri = CMSUrlUtil.getCurrentURI(request); this.setMode(this.getMode()); this.user = WebAPILocator.getUserWebAPI().getUser(request); }

Target:
protected VelocityNavigateEditMode( final HttpServletRequest request, final HttpServletResponse response, final IHTMLPage htmlPage, final Host host) { super(request, response, htmlPage, host); uri = CMSUrlUtil.getCurrentURI(request); this.setMode(this.getMode()); this.user = WebAPILocator.getUserWebAPI().getUser(request); }
Source:
public void cleanupEvents(long time) { final String tableName = EventRecordContract.TABLE; final SQLiteDatabase db = getWritableDatabase(); try { int result = db.delete(EventRecordContract.TABLE, EventRecordContract.Col.POSTED_TIMESTAMP.getName() + " IS NOT NULL OR " + EventRecordContract.Col.RECORDED_TIMESTAMP.getName() + " < " + Long.toString(time) + " OR " + EventRecordContract.Col.POST_ATTEMPTS.getName() + " > 3", null); L.d("cleaned " + Integer.toString(result) + " event records"); } catch (final SQLiteException e) { L.e("Could not clean sent EventLogging records from " + tableName + ". Re-initializing database.", e); deleteDB(); } finally { db.close(); } }

Target:
public void cleanupEvents(long time) { final String tableName = EventRecordContract.TABLE; final SQLiteDatabase db = getWritableDatabase(); try { int result = db.delete(EventRecordContract.TABLE, EventRecordContract.Col.POSTED_TIMESTAMP.getName() + " IS NOT NULL OR " + EventRecordContract.Col.RECORDED_TIMESTAMP.getName() + " < " + Long.toString(time) + " OR " + EventRecordContract.Col.POST_ATTEMPTS.getName() + " > 3", null); L.d("cleaned " + Integer.toString(result) + " event records"); } catch (SQLiteException e) { L.e("Could not clean sent EventLogging records from " + tableName + ". Re-initializing database.", e); deleteDB(); } finally { db.close(); } }
Source:
public SensorPersistenceMode getPersistenceMode() { return persistence; }

Target:
public SensorPersistenceMode getPersistenceMode() { return (persistence != null) ? persistence : SensorPersistenceMode.REQUIRED; }
Source:
public void restart(String launchMode) throws CoreException { putSharedData(CURRENTLY_RESTARTING, true); }

Target:
public void restart(String launchMode) throws CoreException { putSharedData(CURRENTLY_RESTARTING, true); super.restart(launchMode); }
Source:
public void cleanup() { for (final Map.Entry<Reporter.Channel, Reporter> e : reporters.entrySet()) { final AbstractReporterImpl reporter = (AbstractReporterImpl) e.getValue(); reporter.cleanup(); } tempFileSpace.cleanup(); }

Target:
public void cleanup() { for (final Reporter.Channel channel : Reporter.Channel.values()) { final AbstractReporterImpl reporter = (AbstractReporterImpl) reporters.get(channel); try { reporter.cleanup(); } catch (Exception ex) { } } tempFileSpace.cleanup(); }
Source:
public Map<String, Ref> getPubSubRefs() throws IOException { Map<String, Ref> matches = new HashMap<String, Ref>(); RefDatabase rdb = repository.getRefDatabase(); for (RefSpec spec : getSubscribeSpecs()) { String pubsubRef = getPubSubRefFromLocal(remote, spec.getSource()); if (spec.isWildcard()) { pubsubRef = pubsubRef.substring(0, pubsubRef.length() - 1); for (Ref r : rdb.getRefs(pubsubRef).values()) { matches.put(getLocalRefFromPubSub(remote, r.getName()), r); } } else { Ref r = rdb.getRef(pubsubRef); if (r != null) matches.put(getLocalRefFromPubSub(remote, r.getName()), r); } } return matches; }

Target:
public Map<String, Ref> getPubSubRefs() throws IOException { Map<String, Ref> matches = new HashMap<String, Ref>(); RefDatabase rdb = repository.getRefDatabase(); for (RefSpec spec : getSubscribeSpecs()) { String pubsubRef = getPubSubRefFromLocal(remote, spec.getSource()); if (spec.isWildcard()) { pubsubRef = pubsubRef.substring(0, pubsubRef.length() - 1); for (Ref r : rdb.getRefs(pubsubRef).values()) matches.put(getLocalRefFromPubSub(remote, r.getName()), r); } else { Ref r = rdb.getRef(pubsubRef); if (r != null) matches.put(getLocalRefFromPubSub(remote, r.getName()), r); } } return matches; }
Source:
private void registerReceivers() { this.broadcastRegistrar = new BroadcastRegistrar(); this.broadcastRegistrar .addAction(ConnectionService.ACTION_HOST_CONNECTED, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { connectButton.setEnabled(true); Transitions.transitionToHome((CoreActivity)getActivity()); ((CoreActivity)getActivity()).enableSlidingMenu(); } }) .addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { int mode = intent.getIntExtra( BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.SCAN_MODE_NONE); if(mode == BluetoothAdapter.SCAN_MODE_NONE || mode == BluetoothAdapter.SCAN_MODE_CONNECTABLE){ Log.d(TAG, "Button Enabled"); connectButton.setEnabled(true); } else if(mode == BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){ Log.d(TAG, "Button disabled"); connectButton.setEnabled(false); } else { Log.wtf(TAG, "Recieved scan mode changed with unknown mode"); } } }) .register(this.getActivity()); }

Target:
private void registerReceivers() { this.broadcastRegistrar = new BroadcastRegistrar(); this.broadcastRegistrar .addAction(ConnectionService.ACTION_HOST_CONNECTED, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { connectButton.setEnabled(true); Transitions.transitionToHome((CoreActivity)getActivity()); ((CoreActivity)getActivity()).enableSlidingMenu(); } }) .addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { int mode = intent.getIntExtra( BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.SCAN_MODE_NONE); switch(mode){ case BluetoothAdapter.SCAN_MODE_NONE: connectButton.setEnabled(true); break; case BluetoothAdapter.SCAN_MODE_CONNECTABLE: connectButton.setEnabled(true); break; case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE: connectButton.setEnabled(false); break; default: Log.wtf(TAG, "Recieved scan mode changed with unknown mode"); break; } } }) .register(this.getActivity()); }
Source:
protected void writeString(int majorType, byte[] bytes) throws IOException { int len = (bytes == null) ? 0 : bytes.length; writeType(majorType, len); m_os.write(bytes); }

Target:
protected void writeString(int majorType, byte[] bytes) throws IOException { int len = (bytes == null) ? 0 : bytes.length; writeType(majorType, len); if (len > 0){ m_os.write(bytes); } }
Source:
public ValueHolder<V> compute(final K key, final BiFunction<? super K, ? super V, ? extends V> mappingFunction, final NullaryFunction<Boolean> replaceEqual) throws CacheAccessException { checkKey(key); final long now = timeSource.getTimeMillis(); try { OnHeapValueHolder<V> computeResult = map.compute(key, new BiFunction<K, OnHeapValueHolder<V>, OnHeapValueHolder<V>>() { @Override public OnHeapValueHolder<V> apply(K mappedKey, OnHeapValueHolder<V> mappedValue) { if (mappedValue != null && mappedValue.isExpired(now, TimeUnit.MILLISECONDS)) { onExpiration(mappedKey, mappedValue); mappedValue = null; } V existingValue = mappedValue == null ? null : mappedValue.value(); V computedValue = mappingFunction.apply(mappedKey, existingValue); if (computedValue == null) { return null; } else if ((eq(existingValue, computedValue)) && (!replaceEqual.apply())) { if (mappedValue != null) { setAccessTimeAndExpiry(key, mappedValue, now); } return mappedValue; } checkValue(computedValue); if (mappedValue != null) { long expirationTime = mappedValue.expirationTime(OnHeapValueHolder.TIME_UNIT); return newUpdateValueHolder(key, existingValue, computedValue, now, expirationTime); } else { return newCreateValueHolder(key, computedValue, now); } } }); return enforceCapacityIfValueNotNull(computeResult); } catch (CachePassThroughException cpte) { Throwable cause = cpte.getCause(); if(cause instanceof RuntimeException) { throw (RuntimeException) cause; } else { throw wrapAsCacheAccessException(cause); } } catch (RuntimeException re) { throw wrapAsCacheAccessException(re); } }

Target:
public ValueHolder<V> compute(final K key, final BiFunction<? super K, ? super V, ? extends V> mappingFunction, final NullaryFunction<Boolean> replaceEqual) throws CacheAccessException { checkKey(key); final long now = timeSource.getTimeMillis(); try { OnHeapValueHolder<V> computeResult = map.compute(key, new BiFunction<K, OnHeapValueHolder<V>, OnHeapValueHolder<V>>() { @Override public OnHeapValueHolder<V> apply(K mappedKey, OnHeapValueHolder<V> mappedValue) { if (mappedValue != null && mappedValue.isExpired(now, TimeUnit.MILLISECONDS)) { onExpiration(mappedKey, mappedValue); mappedValue = null; } V existingValue = mappedValue == null ? null : mappedValue.value(); V computedValue = mappingFunction.apply(mappedKey, existingValue); if (computedValue == null) { return null; } else if ((eq(existingValue, computedValue)) && (!replaceEqual.apply())) { if (mappedValue != null) { setAccessTimeAndExpiry(key, mappedValue, now); } return mappedValue; } checkValue(computedValue); if (mappedValue != null) { long expirationTime = mappedValue.expirationTime(OnHeapValueHolder.TIME_UNIT); return newUpdateValueHolder(key, existingValue, computedValue, now, expirationTime); } else { return newCreateValueHolder(key, computedValue, now); } } }); return enforceCapacityIfValueNotNull(computeResult); } catch (RuntimeException re) { handleRuntimeException(re); return null; } }
Source:
public void updateIdentifiersWithPhone() throws Exception { mockPlayContextWithJson(PHONE_UPDATE); doReturn(session).when(controller).getAuthenticatedAndConsentedSession(); when(mockParticipantService.updateIdentifiers(eq(study), any(), any())).thenReturn(participant); Result result = controller.updateIdentifiers(); assertResult(result, 200); JsonNode node = BridgeObjectMapper.get().readTree(Helpers.contentAsString(result)); assertEquals(ID, node.get("id").textValue()); verify(mockParticipantService).updateIdentifiers(eq(study), contextCaptor.capture(), identifierUpdateCaptor.capture()); IdentifierUpdate update = identifierUpdateCaptor.getValue(); assertEquals(EMAIL_PASSWORD_SIGN_IN_REQUEST.getEmail(), update.getSignIn().getEmail()); assertEquals(EMAIL_PASSWORD_SIGN_IN_REQUEST.getPassword(), update.getSignIn().getPassword()); assertEquals(TestConstants.PHONE, update.getPhoneUpdate()); assertNull(update.getEmailUpdate()); }

Target:
public void updateIdentifiersWithPhone() throws Exception { mockPlayContextWithJson(PHONE_UPDATE); doReturn(session).when(controller).getAuthenticatedAndConsentedSession(); when(mockParticipantService.updateIdentifiers(eq(study), any(), any())).thenReturn(participant); Result result = controller.updateIdentifiers(); assertResult(result, 200); JsonNode node = BridgeObjectMapper.get().readTree(Helpers.contentAsString(result)); assertEquals(ID, node.get("id").textValue()); verify(mockParticipantService).updateIdentifiers(eq(study), contextCaptor.capture(), identifierUpdateCaptor.capture()); verify(mockCacheProvider).setUserSession(sessionCaptor.capture()); assertEquals(participant.getId(), sessionCaptor.getValue().getId()); IdentifierUpdate update = identifierUpdateCaptor.getValue(); assertEquals(EMAIL_PASSWORD_SIGN_IN_REQUEST.getEmail(), update.getSignIn().getEmail()); assertEquals(EMAIL_PASSWORD_SIGN_IN_REQUEST.getPassword(), update.getSignIn().getPassword()); assertEquals(TestConstants.PHONE, update.getPhoneUpdate()); assertNull(update.getEmailUpdate()); }