auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ValidationResult validate(){ if (vmNamesList.isEmpty()) { return ValidationResult.VALID; } else if (vmNamesList.size() > 1 && removedNetworks.size() > 1) { return new ValidationResult(EngineMessage.MULTIPLE_NETWORKS_CANNOT_DETACH_NETWORKS_USED_BY_VMS, LinqUtils.concat(ReplacementUtils.replaceWith(VAR_NETWORK_NAMES, removedNetworks), ReplacementUtils.replaceWith(VAR_VM_NAMES, vmNamesList))); } else if (vmNamesList.size() > 1) { return new ValidationResult(EngineMessage.NETWORK_CANNOT_DETACH_NETWORK_USED_BY_VMS, LinqUtils.concat( ReplacementUtils.replaceWith(VAR_NETWORK_NAME, removedNetworks), ReplacementUtils.replaceWith(VAR_VM_NAMES, vmNamesList))); } else if (removedNetworks.size() > 1) { return new ValidationResult(EngineMessage.MULTIPLE_NETWORKS_CANNOT_DETACH_NETWORKS_USED_BY_SINGLE_VM, LinqUtils.concat( ReplacementUtils.replaceWith(VAR_NETWORK_NAMES, removedNetworks), ReplacementUtils.replaceWith(VAR_VM_NAME, vmNamesList))); } else { return new ValidationResult(EngineMessage.NETWORK_CANNOT_DETACH_NETWORK_USED_BY_SINGLE_VM, LinqUtils.concat( ReplacementUtils.replaceWith(VAR_NETWORK_NAME, removedNetworks), ReplacementUtils.replaceWith(VAR_VM_NAME, vmNamesList))); } }

Target:
public ValidationResult validate() { if (vmNamesList.isEmpty()) { return ValidationResult.VALID; } final int vmsAmount = vmNamesList.size(); final int removedNetworksAmount = removedNetworks.size(); if (vmsAmount > 1 && removedNetworksAmount > 1) { return new ValidationResult(EngineMessage.MULTIPLE_NETWORKS_CANNOT_DETACH_NETWORKS_USED_BY_VMS, LinqUtils.concat(ReplacementUtils.replaceWith(VAR_NETWORK_NAMES, removedNetworks), ReplacementUtils.replaceWith(VAR_VM_NAMES, vmNamesList))); } else if (vmsAmount > 1) { return new ValidationResult(EngineMessage.NETWORK_CANNOT_DETACH_NETWORK_USED_BY_VMS, LinqUtils.concat( ReplacementUtils.replaceWith(VAR_NETWORK_NAME, removedNetworks), ReplacementUtils.replaceWith(VAR_VM_NAMES, vmNamesList))); } else if (removedNetworksAmount > 1) { return new ValidationResult(EngineMessage.MULTIPLE_NETWORKS_CANNOT_DETACH_NETWORKS_USED_BY_SINGLE_VM, LinqUtils.concat( ReplacementUtils.replaceWith(VAR_NETWORK_NAMES, removedNetworks), ReplacementUtils.replaceWith(VAR_VM_NAME, vmNamesList))); } else { return new ValidationResult(EngineMessage.NETWORK_CANNOT_DETACH_NETWORK_USED_BY_SINGLE_VM, LinqUtils.concat( ReplacementUtils.replaceWith(VAR_NETWORK_NAME, removedNetworks), ReplacementUtils.replaceWith(VAR_VM_NAME, vmNamesList))); } }
Source:
public boolean delete(ModuleDefinition definition) { Assert.notNull(definition, "'definition' cannot be null."); if (!ClassUtils.isAssignable(definition.getClass(), CompositeModuleDefinition.class)) { return false; } String path = Paths.build(Paths.MODULES, definition.getType().toString(), definition.getName()); try { zooKeeperConnection.getClient().delete().deletingChildrenIfNeeded().forPath(path); List<ModuleDefinition> children = ((CompositeModuleDefinition) definition).getChildren(); for (ModuleDefinition child : children) { ModuleDefinitionRepositoryUtils.deleteDependencies(moduleDependencyRepository, child, dependencyKey(definition)); } } catch (KeeperException.NoNodeException ignore) { return false; } catch (Exception e) { throw ZooKeeperUtils.wrapThrowable(e); } return true; }

Target:
public boolean delete(ModuleDefinition definition) { Assert.notNull(definition, "'definition' cannot be null."); if (!definition.isComposed()) { return false; } String path = Paths.build(Paths.MODULES, definition.getType().toString(), definition.getName()); try { zooKeeperConnection.getClient().delete().deletingChildrenIfNeeded().forPath(path); List<ModuleDefinition> children = ((CompositeModuleDefinition) definition).getChildren(); for (ModuleDefinition child : children) { ModuleDefinitionRepositoryUtils.deleteDependencies(moduleDependencyRepository, child, dependencyKey(definition)); } } catch (KeeperException.NoNodeException ignore) { return false; } catch (Exception e) { throw ZooKeeperUtils.wrapThrowable(e); } return true; }
Source:
public void setBugPattern(String bugPattern) throws PatternSyntaxException { if (!bugPattern.matches(".*\\([^\\)]*\\).*")) { throw new PatternSyntaxException("The pattern must contain at least one group.", bugPattern, 0); } this.bugPattern = Pattern.compile(bugPattern).toString(); }

Target:
public void setBugPattern(String bugPattern) throws PatternSyntaxException { if (!bugPattern.matches(PATTERN_SINGLE_GROUP)) { throw new PatternSyntaxException(PATTERN_MUST_CONTAIN_GROUP, bugPattern, 0); } this.bugPattern = Pattern.compile(bugPattern).toString(); }
Source:
public Future<AuthenticationResult> acquireToken(final String resource, final UserAssertion userAssertion, final AsymmetricKeyCredential credential, final AuthenticationCallback callback) { this.validateInput(resource, credential, true); Map<String, String> params = new HashMap<String, String>(); params.put("resource", resource); params.put("requested_token_use", "on_behalf_of"); try { AdalOAuthAuthorizationGrant grant = new AdalOAuthAuthorizationGrant( new JWTBearerGrant( SignedJWT.parse(userAssertion.getAssertion())), params); ClientAssertion clientAssertion = JwtHelper .buildJwt(credential, this.authenticationAuthority .getSelfSignedJwtAudience()); final ClientAuthentication clientAuth = createClientAuthFromClientAssertion(clientAssertion); return this.acquireToken(grant, clientAuth, callback); } catch (final Exception e) { throw new AuthenticationException(e); } }

Target:
public Future<AuthenticationResult> acquireToken(final String resource, final UserAssertion userAssertion, final AsymmetricKeyCredential credential, final AuthenticationCallback callback) { this.validateInput(resource, userAssertion, credential); ClientAssertion clientAssertion = JwtHelper .buildJwt(credential, this.authenticationAuthority.getSelfSignedJwtAudience()); final ClientAuthentication clientAuth = createClientAuthFromClientAssertion(clientAssertion); return acquireTokenOnBehalfOf(resource, userAssertion, clientAuth, callback); }
Source:
public void destroyNode(final String id) { CloudService cloudService = api.getCloudServiceApi().get(id); String deleteDeploymentRequestId = api.getDeploymentApiForService(cloudService.name()).delete(id); String operationDescription = format("Delete deployment(%s) of cloudService(%s)", id, cloudService.name()); waitForOperationCompletion(deleteDeploymentRequestId, operationDescription); String cloudServiceDeleteRequestId = api.getCloudServiceApi().delete(cloudService.name()); operationDescription = format("Delete cloudService(%s)", cloudService.name(), Long.toString(operationTimeout)); waitForOperationCompletion(cloudServiceDeleteRequestId, operationDescription); }

Target:
public void destroyNode(final String id) { CloudService cloudService = api.getCloudServiceApi().get(id); if (cloudService != null) { final String cloudServiceName = cloudService.name(); logger.debug("Deleting deployment(%s) of cloud service (%s)", id, cloudServiceName); deleteDeployment(id, cloudServiceName); logger.debug("Deployment (%s) deleted in cloud service (%s).", id, cloudServiceName); logger.debug("Deleting cloud service (%s) ...", cloudServiceName); deleteCloudService(cloudServiceName); logger.debug("Cloud service (%s) deleted.", cloudServiceName); } }
Source:
private void executeActionInTransactionScope() { registerRollbackHandler((TransactionRollbackListener)() -> { log.error("Transaction rolled-back for command '{}'.", CommandBase.this.getClass().getName()); try { if (isQuotaDependant()) { rollbackQuota(); } } catch (NullPointerException e) { log.error("RollbackQuota: failed (may be because quota is disabled)", e); } cancelTasks(); }); if (!executeWithoutTransaction()) { if (TransactionSupport.current() == null) { cancelTasks(); } TransactionSupport.setRollbackOnly(); } }

Target:
private void executeActionInTransactionScope() { registerRollbackHandler((TransactionRollbackListener)() -> { log.error("Transaction rolled-back for command '{}'.", getClass().getName()); try { if (isQuotaDependant()) { rollbackQuota(); } } catch (NullPointerException e) { log.error("RollbackQuota: failed (may be because quota is disabled)", e); } cancelTasks(); }); if (!executeWithoutTransaction()) { if (TransactionSupport.current() == null) { cancelTasks(); } TransactionSupport.setRollbackOnly(); } }
Source:
private boolean verifyShareableDisksMoving() { HashMap<Guid, StorageDomain> targetDomains= new HashMap<>(); ArrayList<String> problematicDisks = new ArrayList<>(); for ( MoveDiskParameters param : getParameters().getParametersList() ) { DiskImage currDisk = getDiskImageDao().get(param.getImageId()); if (currDisk.isShareable()) { Guid targetDomainId = param.getStorageDomainId(); if (!targetDomains.containsKey( targetDomainId ) ) { targetDomains.put(targetDomainId, getStorageDomainDAO().get(targetDomainId)); } if (targetDomains.get(targetDomainId).getStorageType().equals(StorageType.GLUSTERFS)) { problematicDisks.add(currDisk.getDiskAlias()); } } } if (!problematicDisks.isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CANT_MOVE_SHAREABLE_DISK_TO_GLUSTERFS); addCanDoActionMessageVariable("problematicDisks", StringHelper.join(", ", problematicDisks.toArray())); return false; } else { return true; } }

Target:
private boolean verifyShareableDisksMoving() { Map<Guid, StorageDomain> targetDomains= new HashMap<>(); List<String> problematicDisks = new LinkedList<>(); for ( MoveDiskParameters param : getParameters().getParametersList() ) { DiskImage currDisk = getDiskImageDao().get(param.getImageId()); if (currDisk.isShareable()) { Guid targetDomainId = param.getStorageDomainId(); if (!targetDomains.containsKey( targetDomainId ) ) { targetDomains.put(targetDomainId, getStorageDomainDAO().get(targetDomainId)); } if (targetDomains.get(targetDomainId).getStorageType().equals(StorageType.GLUSTERFS)) { problematicDisks.add(currDisk.getDiskAlias()); } } } if (!problematicDisks.isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_CANT_MOVE_SHAREABLE_DISK_TO_GLUSTERFS); addCanDoActionMessageVariable("problematicDisks", StringHelper.join(", ", problematicDisks.toArray())); return false; } return true; }
Source:
public IConditionValueAutoCompleter getFieldValueAutoCompleter(String fieldName) { IConditionValueAutoCompleter retval = null; if (StringUtils.equals(fieldName, "TYPE")) { retval = new EnumValueAutoCompleter(VmPoolType.class); } else { } return retval; }

Target:
public IConditionValueAutoCompleter getFieldValueAutoCompleter(String fieldName) { IConditionValueAutoCompleter retval = null; if ("TYPE".equals(fieldName)) { retval = new EnumValueAutoCompleter(VmPoolType.class); } return retval; }
Source:
public Response getSamlpResponse( String relayState, AuthnRequest authnRequest, org.opensaml.saml.saml2.core.Response samlResponse, NewCookie cookie, String responseTemplate) throws WSSecurityException, SimpleSign.SignatureException { LOGGER.debug("Configuring SAML Response for POST."); Document doc = DOMUtils.createDocument(); doc.appendChild(doc.createElement("root")); org.opensaml.saml.saml2.core.Response processingResponse = processPresignPlugins(authnRequest, samlResponse); LOGGER.debug("Signing SAML POST Response."); getSimpleSign().signSamlObject(processingResponse); LOGGER.debug("Converting SAML Response to DOM"); String assertionResponse = DOM2Writer.nodeToString(OpenSAMLUtil.toDom(processingResponse, doc)); String encodedSamlResponse = Base64.getEncoder().encodeToString(assertionResponse.getBytes(StandardCharsets.UTF_8)); String assertionConsumerServiceURL = getAssertionConsumerServiceURL(authnRequest); String submitFormUpdated = responseTemplate.replace("{{" + Idp.ACS_URL + "}}", assertionConsumerServiceURL); submitFormUpdated = submitFormUpdated.replace("{{" + Idp.SAML_TYPE + "}}", "SAMLResponse"); submitFormUpdated = submitFormUpdated.replace("{{" + Idp.SAML_RESPONSE + "}}", encodedSamlResponse); submitFormUpdated = StringUtils.isNotBlank(relayState) ? submitFormUpdated.replace("{{" + Idp.RELAY_STATE + "}}", relayState) : submitFormUpdated.replace("{{" + Idp.RELAY_STATE + "}}", ""); Response.ResponseBuilder ok = Response.ok(submitFormUpdated); if (cookie != null) { ok = ok.cookie(cookie); } return ok.build(); }

Target:
public Response getSamlpResponse( String relayState, AuthnRequest authnRequest, org.opensaml.saml.saml2.core.Response samlResponse, NewCookie cookie, String responseTemplate) throws WSSecurityException, SimpleSign.SignatureException { LOGGER.debug("Configuring SAML Response for POST."); Document doc = DOMUtils.createDocument(); doc.appendChild(doc.createElement("root")); org.opensaml.saml.saml2.core.Response processingResponse = processPresignPlugins(authnRequest, samlResponse); LOGGER.debug("Signing SAML POST Response."); getSimpleSign().signSamlObject(processingResponse); LOGGER.debug("Converting SAML Response to DOM"); String assertionResponse = DOM2Writer.nodeToString(OpenSAMLUtil.toDom(processingResponse, doc)); String encodedSamlResponse = Base64.getEncoder().encodeToString(assertionResponse.getBytes(StandardCharsets.UTF_8)); String assertionConsumerServiceURL = getAssertionConsumerServiceURL(authnRequest); String submitFormUpdated = responseTemplate.replace( String.format(SURROUND_WITH_TWO_PARENTHESES, Idp.ACS_URL), assertionConsumerServiceURL); submitFormUpdated = submitFormUpdated.replace( String.format(SURROUND_WITH_TWO_PARENTHESES, Idp.SAML_TYPE), "SAMLResponse"); submitFormUpdated = submitFormUpdated.replace( String.format(SURROUND_WITH_TWO_PARENTHESES, Idp.SAML_RESPONSE), encodedSamlResponse); submitFormUpdated = submitFormUpdated.replace( String.format(SURROUND_WITH_TWO_PARENTHESES, Idp.RELAY_STATE), relayState != null ? relayState : ""); Response.ResponseBuilder ok = Response.ok(submitFormUpdated); if (cookie != null) { ok = ok.cookie(cookie); } return ok.build(); }
Source:
public void run() { while (!stop) { try { synchronized (taskCountLock) { if (executor.isShutdown()) { break; } int maxAcquire = Math.min(executor.getMaximumPoolSize() - activeTaskCount, 10); if (maxAcquire > 0) { List<TaskRequest> reqs = taskServer.lockSharedAgentTasks(maxAcquire, agentId, config.getLockRetentionTime(), 1000); for (TaskRequest req : reqs) { executor.submit(() -> { try { runner.run(req); } catch (Throwable t) { logger.error("Uncaught exception. Task queue will detect this failure and this task will be retried later.", t); errorReporter.reportUncaughtError(t); } finally { synchronized (taskCountLock) { activeTaskCount--; } } }); activeTaskCount++; } } else { taskCountLock.wait(500); } } } catch (Throwable t) { logger.error("Uncaught exception during acquiring tasks from a server. Ignoring. Agent thread will be retried.", t); errorReporter.reportUncaughtError(t); try { Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } }

Target:
public void run() { while (!stop) { try { synchronized (addActiveTaskLock) { if (executor.isShutdown()) { break; } int maximumActiveTasks = activeTaskCount.get(); int guaranteedAvaialbleThreads = executor.getMaximumPoolSize() - maximumActiveTasks; int maxAcquire = Math.min(guaranteedAvaialbleThreads, 10); if (maxAcquire > 0) { List<TaskRequest> reqs = taskServer.lockSharedAgentTasks(maxAcquire, agentId, config.getLockRetentionTime(), 1000); for (TaskRequest req : reqs) { executor.submit(() -> { try { runner.run(req); } catch (Throwable t) { logger.error("Uncaught exception. Task queue will detect this failure and this task will be retried later.", t); errorReporter.reportUncaughtError(t); } finally { activeTaskCount.decrementAndGet(); } }); activeTaskCount.incrementAndGet(); } } else { addActiveTaskLock.wait(500); } } } catch (Throwable t) { logger.error("Uncaught exception during acquiring tasks from a server. Ignoring. Agent thread will be retried.", t); errorReporter.reportUncaughtError(t); try { Thread.sleep(1000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } }
Source:
public void printFailuresTo(PrintWriter writer, int maxStackTraceLines) { Preconditions.notNull(writer, "Writer must not be null"); Preconditions.condition(maxStackTraceLines >= 0, "Invalid negative value for maxStackTraceLines"); if (getTotalFailureCount() > 0) { writer.printf("%nFailures (%d):%n", getTotalFailureCount()); this.failures.forEach(failure -> { writer.printf("%s%s%n", TAB, describeTest(failure.getTestIdentifier())); printSource(writer, failure.getTestIdentifier()); writer.printf("%s=> %s%n", DOUBLE_TAB, failure.getException()); printStackTrace(writer, failure.getException(), maxStackTraceLines); }); writer.flush(); } }

Target:
public void printFailuresTo(PrintWriter writer, int maxStackTraceLines) { Preconditions.notNull(writer, "Writer must not be null"); Preconditions.condition(maxStackTraceLines >= 0, "maxStackTraceLines must be a positive number"); if (getTotalFailureCount() > 0) { writer.printf("%nFailures (%d):%n", getTotalFailureCount()); this.failures.forEach(failure -> { writer.printf("%s%s%n", TAB, describeTest(failure.getTestIdentifier())); printSource(writer, failure.getTestIdentifier()); writer.printf("%s=> %s%n", DOUBLE_TAB, failure.getException()); printStackTrace(writer, failure.getException(), maxStackTraceLines); }); writer.flush(); } }
Source:
public InvalidMessageError(Message message) { super(message, "It sent but is should not have:"); }

Target:
public InvalidMessageError(Message message) { super(message, "It sent but it should not have:"); }
Source:
public void edit(final GridBodyCellEditContext context) { final int uiRowIndex = context.getRowIndex(); final int uiColumnIndex = context.getColumnIndex(); final double absoluteCellX = context.getAbsoluteCellX(); final double absoluteCellY = context.getAbsoluteCellY(); editor.bind(gridWidget, uiRowIndex, uiColumnIndex); final double[] dxy = {0.0, 0.0}; final Optional<Point2D> rx = context.getRelativeLocation(); rx.ifPresent(r -> { final double headerRowHeight = context.getCellHeight(); dxy[1] = r.getY() - headerRowHeight * uiRowIndex; dxy[0] = r.getX(); }); cellEditorControls.show(editor, (int) (absoluteCellX + dxy[0]), (int) (absoluteCellY + dxy[1])); }

Target:
public void edit(final GridBodyCellEditContext context) { final int uiRowIndex = context.getRowIndex(); final int uiColumnIndex = context.getColumnIndex(); final double absoluteCellX = context.getAbsoluteCellX(); final double absoluteCellY = context.getAbsoluteCellY(); editor.bind(gridWidget, uiRowIndex, uiColumnIndex); final double[] dxy = {0.0, 0.0}; final double headerRowHeight = context.getCellHeight(); final Optional<Point2D> rx = context.getRelativeLocation(); rx.ifPresent(r -> { dxy[0] = r.getX(); dxy[1] = r.getY() - headerRowHeight * uiRowIndex; }); cellEditorControls.show(editor, (int) (absoluteCellX + dxy[0]), (int) (absoluteCellY + dxy[1])); }
Source:
public PatientData<String> load(Patient patient) { String affected = "affected"; try { XWikiDocument doc = (XWikiDocument) this.documentAccessBridge.getDocument(patient.getDocument()); BaseObject data = doc.getXObject(Patient.CLASS_REFERENCE); if (data == null) { return null; } int isNormal = data.getIntValue(UNAFFECTED); if (isNormal == 0) { return new SimpleValuePatientData<String>(getName(), affected); } else if (isNormal == 1) { return new SimpleValuePatientData<String>(getName(), UNAFFECTED); } } catch (Exception e) { this.logger.error("Could not find requested document or some unforeseen" + " error has occurred during controller loading ", e.getMessage()); } return null; }

Target:
public PatientData<String> load(Patient patient) { try { XWikiDocument doc = (XWikiDocument) this.documentAccessBridge.getDocument(patient.getDocument()); BaseObject data = doc.getXObject(Patient.CLASS_REFERENCE); if (data == null) { return null; } int isNormal = data.getIntValue(UNAFFECTED); if (isNormal == 0) { return new SimpleValuePatientData<String>(getName(), AFFECTED); } else if (isNormal == 1) { return new SimpleValuePatientData<String>(getName(), UNAFFECTED); } } catch (Exception e) { this.logger.error("Could not find requested document or some unforeseen" + " error has occurred during controller loading ", e.getMessage()); } return null; }
Source:
public void connect(ITerminalControl control) { if (control == null) { throw new IllegalArgumentException("Invalid ITerminalControl"); } fControl = control; fControl.setState(TerminalState.CONNECTED); fGdbTerminalCtrlMngr.addPageTerminalControl(fControl); }

Target:
public void connect(ITerminalControl control) { if (control == null) { throw new IllegalArgumentException("Invalid ITerminalControl"); } fControl = control; fGdbTerminalCtrlConnector.addPageTerminalControl(fControl); fControl.setState(TerminalState.CONNECTED); }
Source:
public ExtMap queryUsers(ExtMap input, ExtMap output, long pageSize) { LdapQueryData queryData = new LdapQueryDataImpl(); queryData.setLdapQueryType(LdapQueryType.searchUsers); queryData.setDomain(getDirectoryName()); queryData.setFilterParameters(new Object[] { generateQueryString(input) }); LdapReturnValueBase ldapResult = broker.runAdAction( AdActionType.SearchUserByQuery, new LdapSearchByQueryParameters(configuration, null, getDirectoryName(), queryData, (input.<Integer> get(Authz.InvokeKeys.QUERY_FLAGS, Authz.QueryFlags.RESOLVE_GROUPS_NONE) & Authz.QueryFlags.RESOLVE_GROUPS) !=0 ) ); List<LdapUser> ldapUsers = (List<LdapUser>) ldapResult.getReturnValue(); List<ExtMap> results = new ArrayList<>(); int addedUsers = 0; for (LdapUser ldapUser : ldapUsers) { if (addedUsers++ < pageSize) { results.add(mapLdapUser(ldapUser)); } } return output.mput(Authz.InvokeKeys.QUERY_RESULT, results); }

Target:
public ExtMap queryUsers(ExtMap input, ExtMap output, long pageSize) { LdapQueryData queryData = new LdapQueryDataImpl(); queryData.setLdapQueryType(LdapQueryType.searchUsers); queryData.setDomain(getDirectoryName()); queryData.setFilterParameters(new Object[] { generateQueryString(input) }); LdapReturnValueBase ldapResult = broker.runAdAction( AdActionType.SearchUserByQuery, new LdapSearchByQueryParameters(configuration, null, getDirectoryName(), queryData, (input.<Integer> get(Authz.InvokeKeys.QUERY_FLAGS, 0) & Authz.QueryFlags.RESOLVE_GROUPS) != 0 ) ); List<LdapUser> ldapUsers = (List<LdapUser>) ldapResult.getReturnValue(); List<ExtMap> results = new ArrayList<>(); int addedUsers = 0; for (LdapUser ldapUser : ldapUsers) { if (addedUsers++ < pageSize) { results.add(mapLdapUser(ldapUser)); } } return output.mput(Authz.InvokeKeys.QUERY_RESULT, results); }
Source:
public String buildKeyName(long keynum) { if (!orderedinserts) { keynum = Utils.hash(keynum); } return "user"+String.format("%0"+zeropadding+"d",keynum); }

Target:
public String buildKeyName(long keynum) { if (!orderedinserts) { keynum = Utils.hash(keynum); } String value = Long.toString(keynum); int fill = zeropadding - value.length(); String prekey = "user"; for(int i=0; i<fill; i++) { prekey += '0'; } return prekey + value; }
Source:
private void handleMap(MemberStateImpl memberState, Config config, Map<String, LocalMapStats> maps) { Set<String> queuesWithStats = createHashSet(maps.size()); for (String name : maps.keySet()) { if (config.findMapConfig(name).isStatisticsEnabled()) { queuesWithStats.add(name); } } memberState.setMapsWithStats(queuesWithStats); }

Target:
private void handleMap(MemberStateImpl memberState, Config config, Map<String, LocalMapStats> maps) { Set<String> mapsWithStats = createHashSet(maps.size()); for (String name : maps.keySet()) { if (config.findMapConfig(name).isStatisticsEnabled()) { mapsWithStats.add(name); } } memberState.setMapsWithStats(mapsWithStats); }
Source:
public String toString() { return "Check "+position+" in scope "+scope; }

Target:
public String toString() { return "check "+position+" in scope "+scope; }
Source:
public Map<String, Serializable> getScopeVariables(TaskContext taskContext) { Map<String, Serializable> variables = new HashMap<>(); Map<String, Serializable> inherited = new HashMap<>(); Map<String, Serializable> dictionary = new HashMap<>(); try { inherited.putAll(extractSystemVariables(taskContext, "")); inherited.putAll(extractJobVariables(taskContext)); inherited.putAll(extractInheritedVariables(taskContext)); for (TaskVariable taskVariable : taskContext.getInitializer().getTaskVariables().values()) { if (!taskVariable.isJobInherited()) { variables.put(taskVariable.getName(), taskVariable.getValue()); } else if (!inherited.containsKey(taskVariable.getName())) { variables.put(taskVariable.getName(), taskVariable.getValue()); } } dictionary = extractAllVariables(taskContext, null, ""); } catch (IOException | ClassNotFoundException e) { logger.error("Error reading variables from task context!"); } return resolveVariables(variables, dictionary); }

Target:
public Map<String, Serializable> getScopeVariables(TaskContext taskContext) { Map<String, Serializable> variables = new HashMap<>(); Map<String, Serializable> inherited = new HashMap<>(); Map<String, Serializable> dictionary = new HashMap<>(); try { inherited.putAll(extractSystemVariables(taskContext, "")); inherited.putAll(extractJobVariables(taskContext)); inherited.putAll(extractInheritedVariables(taskContext)); for (TaskVariable taskVariable : taskContext.getInitializer().getTaskVariables().values()) { if (!taskVariable.isJobInherited()) { variables.put(taskVariable.getName(), taskVariable.getValue()); } else if (!inherited.containsKey(taskVariable.getName())) { variables.put(taskVariable.getName(), taskVariable.getValue()); } } dictionary = extractAllVariables(taskContext, null, ""); } catch (IOException | ClassNotFoundException e) { logger.error(ERROR_READING_VARIABLES, e); } return resolveVariables(variables, dictionary); }
Source:
public void testCorrectNumOfCollectedRecordsAndUpdatedStateWithAdaptiveReads() { Properties consumerProperties = new Properties(); consumerProperties.setProperty("flink.shard.adaptivereads", "true"); KinesisProxyInterface kinesis = FakeKinesisBehavioursFactory.initialNumOfRecordsAfterNumOfGetRecordsCallsWithAdaptiveReads(10, 2, 500L); assertNumberOfMessagesReceivedFromKinesis(50, kinesis, fakeSequenceNumber(), consumerProperties); }

Target:
public void testCorrectNumOfCollectedRecordsAndUpdatedStateWithAdaptiveReads() { Properties consumerProperties = new Properties(); consumerProperties.setProperty(SHARD_USE_ADAPTIVE_READS, "true"); KinesisProxyInterface kinesis = FakeKinesisBehavioursFactory.initialNumOfRecordsAfterNumOfGetRecordsCallsWithAdaptiveReads(10, 2, 500L); assertNumberOfMessagesReceivedFromKinesis(50, kinesis, fakeSequenceNumber(), consumerProperties); }
Source:
private String getContextPath(ServletContext servletContext) { String contextPath = ""; try { contextPath = servletContext.getContextPath(); } catch (NoSuchMethodError ex) { try { String path = servletContext.getResource("/").getPath(); contextPath = path.substring(0, path.lastIndexOf("/")); contextPath = contextPath.substring(contextPath.lastIndexOf("/")); } catch (Exception e) { log.error("Failed to get construct context path", e); } } catch (Exception e) { log.error("Failed to get context path", e); } if (contextPath.indexOf("/") != -1) { contextPath = contextPath.substring(1); } return contextPath; }

Target:
private String getContextPath(ServletContext servletContext) { String contextPath = ""; try { contextPath = servletContext.getContextPath(); } catch (NoSuchMethodError ex) { try { String path = servletContext.getResource("/").getPath(); contextPath = path.substring(0, path.lastIndexOf("/")); contextPath = contextPath.substring(contextPath.lastIndexOf("/")); } catch (Exception e) { log.error("Failed to get construct context path", e); } } catch (Exception e) { log.error("Failed to get context path", e); } if (contextPath.contains("/")) { contextPath = contextPath.substring(1); } return contextPath; }
Source:
public void addListener_shouldBeCalledToReturnTheQueryResults() { final SharedRealm sharedRealm = getSharedRealm(); Table table = sharedRealm.getTable("test_table"); final Collection collection = new Collection(sharedRealm, table.where()); looperThread.keepStrongReference(collection); collection.addListener(collection, new RealmChangeListener<Collection>() { @Override public void onChange(@Nonnull Collection collection1) { assertEquals(collection, collection1); assertEquals(4, collection1.size()); sharedRealm.close(); looperThread.testComplete(); } }); }

Target:
public void addListener_shouldBeCalledToReturnTheQueryResults() { final SharedRealm sharedRealm = getSharedRealm(); Table table = sharedRealm.getTable("test_table"); final Collection collection = new Collection(sharedRealm, table.where()); looperThread.keepStrongReference(collection); collection.addListener(collection, new RealmChangeListener<Collection>() { @Override public void onChange(Collection collection1) { assertEquals(collection, collection1); assertEquals(4, collection1.size()); sharedRealm.close(); looperThread.testComplete(); } }); }
Source:
private String replace(String string, String oldString, String newString) { if (string == null) { return null; } if (newString == null) { return string; } int i = 0; if ((i = string.indexOf(oldString, i)) >= 0) { char[] string2 = string.toCharArray(); char[] newString2 = newString.toCharArray(); int oLength = oldString.length(); StringBuilder buf = new StringBuilder(string2.length); buf.append(string2, 0, i).append(newString2); i += oLength; int j = i; while ((i = string.indexOf(oldString, i)) > 0) { buf.append(string2, j, i - j).append(newString2); i += oLength; j = i; } buf.append(string2, j, string2.length - j); return buf.toString(); } return string; }

Target:
private static final String replace(String string, String oldString, String newString) { if (string == null) { return null; } if (newString == null) { return string; } int i = 0; if ((i = string.indexOf(oldString, i)) >= 0) { char[] string2 = string.toCharArray(); char[] newString2 = newString.toCharArray(); int oLength = oldString.length(); StringBuilder buf = new StringBuilder(string2.length); buf.append(string2, 0, i).append(newString2); i += oLength; int j = i; while ((i = string.indexOf(oldString, i)) > 0) { buf.append(string2, j, i - j).append(newString2); i += oLength; j = i; } buf.append(string2, j, string2.length - j); return buf.toString(); } return string; }
Source:
public void readFromNBT(NBTTagCompound data) { super.readFromNBT(data); if (data.hasKey("profile")) profile = LockingProfileType.fromOrdinal(data.getByte("profile")); profileInstance = profile.create(this); profileInstance.readFromNBT(data); redstone = data.getBoolean("powered"); if(data.hasKey("locked")) locked = data.getBoolean("locked"); if(data.hasKey("trainLeaving")) trainLeaving = data.getBoolean("trainLeaving"); if(data.hasKey("trainDelay")) trainDelay = data.getInteger("trainDelay"); prevCartUUID = readUUID("prevCart", data); currentCartUUID = readUUID("currentCart", data); uuid = readUUID("uuid", data); justLoaded = true; System.out.println("Read from NBT"); }

Target:
public void readFromNBT(NBTTagCompound data) { super.readFromNBT(data); if (data.hasKey("profile")) profile = LockingProfileType.fromOrdinal(data.getByte("profile")); profileInstance = profile.create(this); profileInstance.readFromNBT(data); redstone = data.getBoolean("powered"); if(data.hasKey("locked")) locked = data.getBoolean("locked"); if(data.hasKey("trainLeaving")) trainLeaving = data.getBoolean("trainLeaving"); if(data.hasKey("trainDelay")) trainDelay = data.getInteger("trainDelay"); prevCartUUID = readUUID("prevCart", data); currentCartUUID = readUUID("currentCart", data); uuid = readUUID("uuid", data); justLoaded = true; }
Source:
public void setUp() { jedis = new Jedis("localhost", getPort(), 10000000); }

Target:
public void setUp() { jedis = new Jedis("localhost", getPort(), JEDIS_TIMEOUT); }
Source:
public void setClosestMatch(String text) { System.out.println("matching text " + text); final boolean matchFound = ComboUtil.setClosestMatch(getCCombo(), text); if (!matchFound) { reset(); } }

Target:
public void setClosestMatch(String text) { final boolean matchFound = ComboUtil.setClosestMatch(getCCombo(), text); if (!matchFound) { reset(); } }
Source:
public boolean isEventProvidedBy(ITmfEvent event) { if ((event.getTrace() == this)) { return true; } if (hasChildren()) { synchronized (fLock) { List <TmfEventProvider> children = getChildren(TmfEventProvider.class); for (TmfEventProvider child : children) { if (child.isEventProvidedBy(event)) { return true; } } } } return false; }

Target:
public boolean isEventProvidedBy(ITmfEvent event) { ITmfTrace trace = event.getTrace(); if ((trace == this)) { return true; } return getAncestySet().contains(trace); }
Source:
private void validate() { ArgChecker.inOrderNotEqual(startDate, endDate, "startDate", "endDate"); ArgChecker.inOrderNotEqual(unadjustedStartDate, unadjustedEndDate, "unadjustedStartDate", "unadjustedEndDate"); Currency payCcy = payment.getCurrency(); Currency notionalCcy = notionalAmount.getCurrency(); if (fxResetObservation != null) { if (notionalCcy.equals(payCcy)) { throw new IllegalArgumentException(Messages.format( "Payment currency must not equal notional currency when FX reset applies", payCcy, notionalCcy)); } if (!fxResetObservation.getIndex().getCurrencyPair().contains(payCcy)) { throw new IllegalArgumentException(Messages.format( "Payment currency must be one of those in the FxReset index {}", payCcy, fxResetObservation.getIndex())); } if (!fxResetObservation.getIndex().getCurrencyPair().contains(notionalCcy)) { throw new IllegalArgumentException(Messages.format( "Notional currency must be one of those in the FxReset index {}", payCcy, fxResetObservation.getIndex())); } } else { if (!notionalCcy.equals(payCcy)) { throw new IllegalArgumentException(Messages.format( "Payment currency must equal notional currency {}", payCcy, notionalCcy)); } } }

Target:
private void validate() { ArgChecker.inOrderNotEqual(startDate, endDate, "startDate", "endDate"); ArgChecker.inOrderNotEqual(unadjustedStartDate, unadjustedEndDate, "unadjustedStartDate", "unadjustedEndDate"); Currency payCcy = payment.getCurrency(); Currency notionalCcy = notionalAmount.getCurrency(); if (fxResetObservation != null) { if (notionalCcy.equals(payCcy)) { throw new IllegalArgumentException(Messages.format( "Payment currency must not equal notional currency when FX reset applies", payCcy, notionalCcy)); } if (!fxResetObservation.getIndex().getCurrencyPair().contains(payCcy)) { throw new IllegalArgumentException(Messages.format( "Payment currency must be one of those in the FxReset index {}", payCcy, fxResetObservation.getIndex())); } if (!fxResetObservation.getIndex().getCurrencyPair().contains(notionalCcy)) { throw new IllegalArgumentException(Messages.format( "Notional currency must be one of those in the FxReset index {}", notionalCcy, fxResetObservation.getIndex())); } } else { if (!notionalCcy.equals(payCcy)) { throw new IllegalArgumentException(Messages.format( "Payment currency must equal notional currency {}", payCcy, notionalCcy)); } } }
Source:
public static IArtifactComparator getArtifactComparator(String comparatorID) throws IllegalArgumentException { List<IConfigurationElement> extensions = Stream.of(RegistryFactory.getRegistry().getConfigurationElementsFor(COMPARATOR_POINT)) .collect(Collectors.toList()); extensions.removeIf(extension -> extension.getAttribute(ATTR_ID).equals(ArtifactChecksumComparator.COMPARATOR_ID)); Optional<IArtifactComparator> artifactComparator = findComparatorConfiguration(comparatorID, extensions) .map(ArtifactComparatorFactory::createArtifactComparator); if (artifactComparator.isPresent()) return artifactComparator.get(); if (comparatorID != null && comparatorID.startsWith(ArtifactChecksumComparator.COMPARATOR_ID)) { Optional<ArtifactChecksumComparator> checksumComparator = getChecksumComparator(comparatorID); if (checksumComparator.isPresent()) return checksumComparator.get(); } if (comparatorID != null) { Stream<String> checksumComparators = Stream.of(ChecksumUtilities.getChecksumComparatorConfigurations()) .map(element -> element.getAttribute(CHECKSUM_ID)) .map(checksumId -> ArtifactChecksumComparator.COMPARATOR_ID.concat(".").concat(checksumId)); Stream<String> comparators = extensions.stream() .map(extension -> extension.getAttribute(ATTR_ID)); String availableComparators = Stream.concat(comparators, checksumComparators).collect(Collectors.joining(", ")); throw new IllegalArgumentException(NLS.bind(Messages.exception_comparatorNotFound, comparatorID, availableComparators)); } throw new IllegalArgumentException(Messages.exception_noComparators); }

Target:
public static IArtifactComparator getArtifactComparator(String comparatorID) { List<IConfigurationElement> extensions = Stream.of(RegistryFactory.getRegistry().getConfigurationElementsFor(COMPARATOR_POINT)) .collect(Collectors.toList()); extensions.removeIf(extension -> extension.getAttribute(ATTR_ID).equals(ArtifactChecksumComparator.COMPARATOR_ID)); Optional<IArtifactComparator> artifactComparator = findComparatorConfiguration(comparatorID, extensions) .map(ArtifactComparatorFactory::createArtifactComparator); if (artifactComparator.isPresent()) return artifactComparator.get(); if (comparatorID != null && comparatorID.startsWith(ArtifactChecksumComparator.COMPARATOR_ID)) { Optional<ArtifactChecksumComparator> checksumComparator = getChecksumComparator(comparatorID); if (checksumComparator.isPresent()) return checksumComparator.get(); } if (comparatorID != null) { Stream<String> checksumComparators = Stream.of(ChecksumUtilities.getChecksumComparatorConfigurations()) .map(element -> element.getAttribute(CHECKSUM_ID)) .map(checksumId -> ArtifactChecksumComparator.COMPARATOR_ID.concat(".").concat(checksumId)); Stream<String> comparators = extensions.stream() .map(extension -> extension.getAttribute(ATTR_ID)); String availableComparators = Stream.concat(comparators, checksumComparators).collect(Collectors.joining(", ")); throw new IllegalArgumentException(NLS.bind(Messages.exception_comparatorNotFound, comparatorID, availableComparators)); } throw new IllegalArgumentException(Messages.exception_noComparators); }
Source:
public Integer index() { try { if (!documents.isEmpty()) { Integer waitSeconds = 0; while (!index.hasStarted() && waitSeconds < 121) { waitSeconds += INDEX_CREATION_DELAY/1000; LOGGER.warn("Index is not ready, has been waiting for seconds", waitSeconds); try { Thread.sleep(INDEX_CREATION_DELAY); } catch (InterruptedException e) { LOGGER.error("interrupted"); } } if (waitSeconds == 121) { LOGGER.error("Stop waiting on index creation. Opting out"); System.exit(1); } index.addDocuments(ImmutableList.copyOf(documents)); final Integer count = documents.size(); LOGGER.info("Indexed documents", count); documents.clear(); return count; } } catch (IndexDoesNotExistException e) { LOGGER.error("Index does not exist: {}", e.getMessage()); System.exit(1); } catch (IOException e) { LOGGER.error("Failed connecting to searchify: {}", e.getMessage()); } catch(IndexOutOfBoundsException e) { LOGGER.error("Searchify client error: {}", e.getMessage()); } catch (UnexpectedCodeException e) { LOGGER.error("Unexpected: {}", e.getMessage()); } return 0; }

Target:
public Integer index() { try { if (!documents.isEmpty()) { index.addDocuments(ImmutableList.copyOf(documents)); final Integer count = documents.size(); LOGGER.info("Indexed documents", count); documents.clear(); return count; } } catch (IndexDoesNotExistException e) { LOGGER.error("Index does not exist: {}", e.getMessage()); System.exit(1); } catch (IOException e) { LOGGER.error("Failed connecting to searchify: {}", e.getMessage()); } catch(IndexOutOfBoundsException e) { LOGGER.error("Searchify client error: {}", e.getMessage()); } catch (UnexpectedCodeException e) { LOGGER.error("Unexpected: {}", e.getMessage()); } return 0; }
Source:
private Mono<Object> authenticate(ServiceMessage message) { return Mono.defer( () -> { if (!methodInfo.isAuth()) { return Mono.empty(); } Object credentials = message.credentials(); if (credentials == null) { throw new UnauthorizedException("Credentials not found"); } if (authenticator == null) { throw new UnauthorizedException("Authenticator not found"); } return authenticator.authenticate(credentials); }) .defaultIfEmpty(NO_PRINCIPAL); }

Target:
private Mono<Object> authenticate(ServiceMessage message) { return Mono.defer( () -> { if (!methodInfo.isAuth()) { return Mono.empty(); } if (authenticator == null) { throw new UnauthorizedException("Authenticator not found"); } return authenticator.authenticate(message).onErrorMap(this::toUnauthorizedException); }) .defaultIfEmpty(NO_PRINCIPAL); }
Source:
protected void addVmPayload() { VmPayload payload = getParameters().getVmPayload(); if (payload != null) { VmDeviceUtils.addManagedDevice(new VmDeviceId(Guid.NewGuid(), getParameters().getVmId()), VmDeviceType.DISK, payload.getType(), payload.getSpecParams(), true, true, ""); } }

Target:
protected void addVmPayload() { VmPayload payload = getParameters().getVmPayload(); if (payload != null) { VmDeviceUtils.addManagedDevice(new VmDeviceId(Guid.NewGuid(), getParameters().getVmId()), VmDeviceType.DISK, payload.getType(), payload.getSpecParams(), true, true); } }
Source:
public void testCollectionIsNotArray() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class A {\n"); buf.append(" public void foo() {\n"); buf.append(" java.util.List list = new ArrayList();\n"); buf.append(" list.add(null);\n"); buf.append(" for (int i = 0; i < list.size(); i++) {\n"); buf.append(" System.out.println(list.get(i));\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("A.java", buf.toString(), false, null); List<IJavaCompletionProposal> proposals= fetchConvertingProposal(buf, cu); assertNotNull(fConvertLoopProposal); String preview1= getPreviewContent(fConvertLoopProposal); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class A {\n"); buf.append(" public void foo() {\n"); buf.append(" java.util.List list = new ArrayList();\n"); buf.append(" list.add(null);\n"); buf.append(" for (Object element : list) {\n"); buf.append(" System.out.println(element);\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected= buf.toString(); assertEqualString(preview1, expected); assertCorrectLabels(proposals); assertCorrectLabels(proposals); }

Target:
public void testCollectionIsNotArray() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuilder buf= new StringBuilder(); buf.append("package test1;\n"); buf.append("public class A {\n"); buf.append(" public void foo() {\n"); buf.append(" java.util.List list = new ArrayList();\n"); buf.append(" list.add(null);\n"); buf.append(" for (int i = 0; i < list.size(); i++) {\n"); buf.append(" System.out.println(list.get(i));\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("A.java", buf.toString(), false, null); List<IJavaCompletionProposal> proposals= fetchConvertingProposal(buf, cu); assertNotNull(fConvertLoopProposal); String preview1= getPreviewContent(fConvertLoopProposal); buf= new StringBuilder(); buf.append("package test1;\n"); buf.append("public class A {\n"); buf.append(" public void foo() {\n"); buf.append(" java.util.List list = new ArrayList();\n"); buf.append(" list.add(null);\n"); buf.append(" for (Object element : list) {\n"); buf.append(" System.out.println(element);\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected= buf.toString(); assertEqualString(preview1, expected); assertCorrectLabels(proposals); assertCorrectLabels(proposals); }
Source:
void addResource(int id, String type, String name) { ResName resName = new ResName(packageName, type, name); int resIdPackageIdentifier = ResourceIds.getPackageIdentifier(id); if (getPackageIdentifier() == 0) { this.packageIdentifier = resIdPackageIdentifier; } else if (getPackageIdentifier() != resIdPackageIdentifier) { throw new IllegalArgumentException("Attempted to add resId " + resIdPackageIdentifier + " to PackageResourceIndex with packageIdentifier " + getPackageIdentifier()); } ResName existingEntry = resourceTable.put(id, resName); if (existingEntry != null && !existingEntry.equals(resName)) { throw new IllegalArgumentException("ResId " + Integer.toHexString(id) + " mapped to both " + resName + " and " + existingEntry); } }

Target:
synchronized void addResource(int id, String type, String name) { if (ResourceIds.isFrameworkResource(id)) { androidResourceIdGenerator.record(id, type, name); } ResName resName = new ResName(packageName, type, name); int resIdPackageIdentifier = ResourceIds.getPackageIdentifier(id); if (getPackageIdentifier() == 0) { this.packageIdentifier = resIdPackageIdentifier; } else if (getPackageIdentifier() != resIdPackageIdentifier) { throw new IllegalArgumentException("Attempted to add resId " + resIdPackageIdentifier + " to PackageResourceIndex with packageIdentifier " + getPackageIdentifier()); } ResName existingEntry = resourceTable.put(id, resName); if (existingEntry != null && !existingEntry.equals(resName)) { throw new IllegalArgumentException("ResId " + Integer.toHexString(id) + " mapped to both " + resName + " and " + existingEntry); } }
Source:
private void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { if (messageProcessor.get() != null && messageProcessor.get().isDisposed()) { logger.error("[{}]: Can not receive messaged because client is closed.", asyncClient.getEntityPath()); return; } if (messageProcessor.get() == null) { EmitterProcessor<ServiceBusReceivedMessageContext> processor = asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(false)); if (!messageProcessor.compareAndSet(null, processor)) { processor.dispose(); } logger.info("[{}]: Started ContinuesMessageSubscriber message subscriber for entity.", asyncClient.getEntityPath()); } Disposable newSubscription = messageProcessor.get() .take(maximumMessageCount) .timeout(maxWaitTime) .doOnNext(messageContext -> { emitter.next(messageContext); }) .doOnError(throwable -> { emitter.error(throwable); }) .doOnComplete(emitter::complete) .subscribe(); Disposable oldSubscription = messageProcessorSubscription.getAndSet(newSubscription); if (oldSubscription != null) { oldSubscription.dispose(); } }

Target:
private void queueWork(int maximumMessageCount, Duration maxWaitTime, FluxSink<ServiceBusReceivedMessageContext> emitter) { synchronized (lock) { final long id = idGenerator.getAndIncrement(); EmitterProcessor<ServiceBusReceivedMessageContext> emitterProcessor = messageProcessor.get(); final SynchronousReceiveWork work = new SynchronousReceiveWork(id, maximumMessageCount, maxWaitTime, emitter); final SynchronousMessageSubscriber syncSubscriber = new SynchronousMessageSubscriber(work); logger.info("[{}]: Started synchronous message subscriber.", id); if (emitterProcessor == null) { emitterProcessor = this.asyncClient.receive(DEFAULT_RECEIVE_OPTIONS) .subscribeWith(EmitterProcessor.create(asyncClient.getReceiverOptions().getPrefetchCount(), false)); messageProcessor.set(emitterProcessor); } emitterProcessor.subscribe(syncSubscriber); } }