auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void withTmpFsTest(){ try(GenericContainer container = new GenericContainer().withCommand("top") .withTmpFs(singletonMap("/testtmpfs", "rw"))) { assertFalse("Container is not started and not running", container.isRunning()); container.start(); assertTrue("Container is started and running", container.isRunning()); String path = "/testtmpfs/test.file"; Container.ExecResult execResult = container.execInContainer("ls", path); assertEquals("tmpfs inside container works fine", execResult.getStderr(), "ls: /testtmpfs/test.file: No such file or directory\n"); container.execInContainer("touch", path); execResult = container.execInContainer("ls", path); assertEquals("tmpfs inside container works fine", execResult.getStdout(), path + "\n"); } catch (InterruptedException | IOException ignored) { assertNull("Exception shouldn't be at all.", ignored); } }

Target:
public void withTmpFsTest() throws Exception { try ( GenericContainer container = new GenericContainer() .withCommand("top") .withTmpFs(singletonMap("/testtmpfs", "rw")) ) { container.start(); String path = "/testtmpfs/test.file"; Container.ExecResult execResult = container.execInContainer("ls", path); assertEquals("tmpfs inside container works fine", execResult.getStderr(), "ls: /testtmpfs/test.file: No such file or directory\n"); container.execInContainer("touch", path); execResult = container.execInContainer("ls", path); assertEquals("tmpfs inside container works fine", execResult.getStdout(), path + "\n"); } }
Source:
private void reportToElasticsearch(Metric2Registry metricRegistry, int reportingInterval, final MeasurementSession measurementSession) { if (isReportToElasticsearch()) { elasticsearchClient.sendClassPathRessourceBulkAsync("KibanaConfig.bulk"); logger.info("Sending metrics to Elasticsearch ({}) every {}s", getElasticsearchUrls(), reportingInterval); final String mappingJson = ElasticsearchClient.modifyIndexTemplate( metricsIndexTemplate.getValue(), moveToColdNodesAfterDays.getValue(), getNumberOfReplicas(), getNumberOfShards()); elasticsearchClient.sendMappingTemplateAsync(mappingJson, "stagemonitor-metrics"); final ElasticsearchReporter reporter = ElasticsearchReporter.forRegistry(metricRegistry, this) .globalTags(measurementSession.asMap()) .build(); reporter.start(reportingInterval, TimeUnit.SECONDS); reporters.add(reporter); elasticsearchClient.scheduleIndexManagement(ElasticsearchReporter.STAGEMONITOR_METRICS_INDEX_PREFIX, moveToColdNodesAfterDays.getValue(), deleteElasticsearchMetricsAfterDays.getValue()); } else if (isOnlyLogElasticsearchMetricReports()) { final ElasticsearchReporter reporter = ElasticsearchReporter.forRegistry(metricRegistry, this) .globalTags(measurementSession.asMap()) .build(); reporter.start(reportingInterval, TimeUnit.SECONDS); reporters.add(reporter); } else { logger.info("Not sending metrics to Elasticsearch (url={}, interval={}s)", getElasticsearchUrls(), reportingInterval); } }

Target:
private void reportToElasticsearch(Metric2Registry metricRegistry, int reportingInterval, final MeasurementSession measurementSession) { if (isReportToElasticsearch()) { elasticsearchClient.sendClassPathRessourceBulkAsync("KibanaConfig.bulk"); logger.info("Sending metrics to Elasticsearch ({}) every {}s", getElasticsearchUrls(), reportingInterval); final String mappingJson = ElasticsearchClient.modifyIndexTemplate( metricsIndexTemplate.getValue(), moveToColdNodesAfterDays.getValue(), getNumberOfReplicas(), getNumberOfShards()); elasticsearchClient.sendMappingTemplateAsync(mappingJson, "stagemonitor-metrics"); elasticsearchClient.scheduleIndexManagement(ElasticsearchReporter.STAGEMONITOR_METRICS_INDEX_PREFIX, moveToColdNodesAfterDays.getValue(), deleteElasticsearchMetricsAfterDays.getValue()); } if (isReportToElasticsearch() || isOnlyLogElasticsearchMetricReports()) { final ElasticsearchReporter reporter = ElasticsearchReporter.forRegistry(metricRegistry, this) .globalTags(measurementSession.asMap()) .build(); reporter.start(reportingInterval, TimeUnit.SECONDS); reporters.add(reporter); } else { logger.info("Not sending metrics to Elasticsearch (url={}, interval={}s)", getElasticsearchUrls(), reportingInterval); } }
Source:
public void advance(long lastSeqNo, long commitSeqNo, long commitSpHandle, long startTime) { m_es.execute(new Runnable() { @Override public void run() { if (exportLog.isTraceEnabled()) { exportLog.trace("AckingContainer.discard with sequence number: " + lastSeqNo); } assert(startTime != 0); long elapsedMS = System.currentTimeMillis() - startTime; m_blocksSentSinceClear += 1; m_totalLatencySinceClearInMS += elapsedMS; m_averageLatency = m_totalLatencySinceClearInMS / m_blocksSentSinceClear; if (m_averageLatency > m_maxLatency) { m_maxLatency = m_averageLatency; } try { if (!m_es.isShutdown()) { setCommittedSeqNo(commitSeqNo); ackImpl(lastSeqNo); } forwardAckToOtherReplicas(); if (m_migrateRowsDeleter != null && m_mastershipAccepted.get()) { m_migrateRowsDeleter.delete(commitSpHandle); } } catch (Exception e) { exportLog.error("Error acking export buffer", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error acking export buffer", true, e); } } }); }

Target:
public void advance(long lastSeqNo, long commitSeqNo, long commitSpHandle, long startTime) { m_es.execute(new Runnable() { @Override public void run() { if (exportLog.isTraceEnabled()) { exportLog.trace("Advance sequence number to: " + commitSeqNo); } assert(startTime != 0); long elapsedMS = System.currentTimeMillis() - startTime; m_blocksSentSinceClear += 1; m_totalLatencySinceClearInMS += elapsedMS; m_averageLatency = m_totalLatencySinceClearInMS / m_blocksSentSinceClear; if (m_averageLatency > m_maxLatency) { m_maxLatency = m_averageLatency; } try { if (!m_es.isShutdown()) { setLastCommittedSeqNo(commitSeqNo); ackImpl(commitSeqNo); } forwardAckToOtherReplicas(); if (m_migrateRowsDeleter != null && m_mastershipAccepted.get()) { m_migrateRowsDeleter.delete(commitSpHandle); } } catch (Exception e) { exportLog.error("Error acking export buffer", e); } catch (Error e) { VoltDB.crashLocalVoltDB("Error acking export buffer", true, e); } } }); }
Source:
private double updateMinFramePeriod(double tsDelta) { tsDeltaHist[tsDeltaHistIdx] = tsDelta; tsDeltaHistIdx = (tsDeltaHistIdx + 1) % tsDeltaHist.length; double min = tsDelta; for (double d : tsDeltaHist) { if (d < min) min = d; } return min; }

Target:
private double updateMinFramePeriod(double tsDelta) { tsDeltaHist[tsDeltaHistInsIdx] = tsDelta; tsDeltaHistInsIdx = (tsDeltaHistInsIdx + 1) % tsDeltaHist.length; double min = tsDelta; for (double d : tsDeltaHist) { if (d < min) min = d; } return min; }
Source:
public void verifyTemplateImage(String selectedTemplateName) { waitForElementByElement(templateImagePreview); Assert.assertTrue(templateImagePreview.getAttribute("src").endsWith(selectedTemplateName)); }

Target:
public void verifyTemplateImage(String selectedTemplateName) { waitForElementByElement(templateImagePreview); Assertion.assertTrue(templateImagePreview.getAttribute("src").endsWith(selectedTemplateName)); }
Source:
private void updateCrashReportProps() { if (!ReleaseUtil.isPreBetaRelease()) { putCrashReportProperty("locale", Locale.getDefault().toString()); if (appLanguageState != null) { putCrashReportProperty("app_primary_language", appLanguageState.getAppLanguageCode()); putCrashReportProperty("app_languages", appLanguageState.getAppLanguageCodes().toString()); putCrashReportProperty("app_install_id", getAppInstallID()); } } }

Target:
private void updateCrashReportProps() { if (!ReleaseUtil.isPreBetaRelease()) { putCrashReportProperty("locale", Locale.getDefault().toString()); if (appLanguageState != null) { putCrashReportProperty("app_primary_language", appLanguageState.getAppLanguageCode()); putCrashReportProperty("app_languages", appLanguageState.getAppLanguageCodes().toString()); putCrashReportProperty("app_install_id", getAppInstallID()); putCrashReportProperty("app_local_class_name", Prefs.getLocalClassName()); } } }
Source:
private void createNameForm(Composite composite) { Group group = createGroup(composite, Messages.SelectDiagramKindPage_diagram_name_group); nameText = new Text(group, SWT.BORDER); nameText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); nameText.setText(""); ISelection selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection(); if (selection instanceof IStructuredSelection && ((IStructuredSelection) selection).size() > 0) { IStructuredSelection sSelection = (IStructuredSelection) selection; Object selectedObject = sSelection.getFirstElement(); if (selectedObject instanceof IFile) { IFile selectedIFile = (IFile) selectedObject; ResourceSet resourceSet = new ResourceSetImpl(); Resource resource = resourceSet.getResource(URI.createURI(selectedIFile.getLocationURI().toString()), true); EObject sEObject = resource.getContents().get(0); if (sEObject != null && sEObject instanceof Profile) { Profile sProfile = (Profile) sEObject; nameText.setText(sProfile.getName()); } } } nameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { validatePage(); } }); }

Target:
private void createNameForm(Composite composite) { Group group = createGroup(composite, Messages.SelectDiagramKindPage_diagram_name_group); nameText = new Text(group, SWT.BORDER); nameText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false)); nameText.setText(Messages.SelectDiagramKindPage_default_diagram_name); ISelection selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection(); if (selection instanceof IStructuredSelection && ((IStructuredSelection) selection).size() > 0) { IStructuredSelection sSelection = (IStructuredSelection) selection; Object selectedObject = sSelection.getFirstElement(); if (selectedObject instanceof IAdaptable) { IFile selectedIFile = ((IAdaptable) selectedObject).getAdapter(IFile.class); if (selectedIFile != null) { try { ResourceSet resourceSet = new ResourceSetImpl(); Resource resource = resourceSet.getResource(URI.createURI(selectedIFile.getLocationURI().toString()), true); EObject sEObject = resource.getContents().get(0); if (sEObject != null && sEObject instanceof org.eclipse.uml2.uml.Package) { org.eclipse.uml2.uml.Package sPackage = (org.eclipse.uml2.uml.Package) sEObject; nameText.setText(sPackage.getName()); } } catch (Exception e) { Activator.log.error(e); } } } } nameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { validatePage(); } }); }
Source:
protected File createUniqueTestGitDir(boolean bare) throws IOException { String gitdirName = createUniqueTestFolderPrexif(); if (!bare) { gitdirName += "/"; } gitdirName += Constants.DOT_GIT; File gitdir = new File(trash, gitdirName); return gitdir.getCanonicalFile(); }

Target:
protected File createUniqueTestGitDir(boolean bare) throws IOException { String gitdirName = createUniqueTestFolderPrefix(); if (!bare) gitdirName += "/"; gitdirName += Constants.DOT_GIT; File gitdir = new File(trash, gitdirName); return gitdir.getCanonicalFile(); }
Source:
public void restartDevMode(final ThreadPoolExecutor executor) { executor.shutdown(); stopServer(); log.info("Restarting liberty:dev mode"); ProcessBuilder processBuilder = new ProcessBuilder(); String processCommand = "mvn liberty:dev"; String os = System.getProperty("os.name"); if (os != null && os.toLowerCase().startsWith("windows")) { processBuilder.command("CMD", "/C", processCommand); } else { processBuilder.command("bash", "-c", processCommand); } try { processBuilder.redirectOutput(Redirect.INHERIT); processBuilder.redirectError(Redirect.INHERIT); processBuilder.start(); } catch (IOException e) { log.error("Could not restart liberty:dev mode", e); } }

Target:
public void restartDevMode(final ThreadPoolExecutor executor) { executor.shutdown(); cleanUpJVMOptions(); stopServer(); log.info("Restarting liberty:dev mode"); ProcessBuilder processBuilder = new ProcessBuilder(); String processCommand = "mvn liberty:dev"; Properties props = System.getProperties(); Set<Object> keys = props.keySet(); for(Object key: keys){ processCommand += " -D" + key + "=\"" + props.get(key) + "\""; } String os = System.getProperty("os.name"); if (os != null && os.toLowerCase().startsWith("windows")) { processBuilder.command("CMD", "/C", processCommand); } else { processBuilder.command("bash", "-c", processCommand); } try { processBuilder.redirectOutput(Redirect.INHERIT); processBuilder.redirectError(Redirect.INHERIT); processBuilder.start(); } catch (IOException e) { log.error("Could not restart liberty:dev mode", e); } }
Source:
public void accept(final Dist dist) { if (visualization != null) return; final boolean ismac = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("mac"); visualization = new ClientVisualization(ismac); visualization.start(); }

Target:
public Runnable accept(final Dist dist) { visualization = dist.isClient() && Boolean.parseBoolean(System.getProperty("fml.earlyprogresswindow", "true")) ? new ClientVisualization() : new NoVisualization(); return visualization.start(); }
Source:
public StillLeadingStatus toStillLeadingStatus() { switch (this) { case QUORUM_AGREED: return StillLeadingStatus.LEADING; case SOME_DISAGREED: return StillLeadingStatus.NOT_LEADING; case NO_QUORUM: return StillLeadingStatus.NO_QUORUM; } throw new IllegalStateException("unknown status: " + this); }

Target:
public StillLeadingStatus toStillLeadingStatus() { switch (this) { case QUORUM_AGREED: return StillLeadingStatus.LEADING; case SOME_DISAGREED: return StillLeadingStatus.NOT_LEADING; case NO_QUORUM: return StillLeadingStatus.NO_QUORUM; default: throw new IllegalStateException("unknown status: " + this); } }
Source:
private BookieStatus readFromFile(File file) throws IOException, IllegalArgumentException { if (!file.exists()) { return null; } BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(file), UTF_8)); try { return parse(reader); } finally { reader.close(); } }

Target:
private BookieStatus readFromFile(File file) throws IOException, IllegalArgumentException { if (!file.exists()) { return null; } try (BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(file), UTF_8))) { return parse(reader); } }
Source:
public ReceivePack create(HttpServletRequest req, Repository db) throws ServiceNotEnabledException, ServiceNotAuthorizedException { final ProjectControl pc = getProjectControl(req); if (pc.getCurrentUser() instanceof IdentifiedUser) { final IdentifiedUser user = (IdentifiedUser) pc.getCurrentUser(); if (!pc.canPerformPackAction(receiveGroup)) { throw new ServiceNotAuthorizedException(); } final ReceiveCommits rc = factory.create(pc, db); final ReceiveCommits.Capable s = rc.canUpload(); if (s != ReceiveCommits.Capable.OK) { final String who = user.getUserName(); final String why = s.getMessage(); log.warn("Rejected push from " + who + ": " + why); throw new ServiceNotEnabledException(); } rc.getReceivePack().setRefLogIdent(user.newRefLogIdent()); return rc.getReceivePack(); } else { throw new ServiceNotAuthorizedException(); } }

Target:
public ReceivePack create(HttpServletRequest req, Repository db) throws ServiceNotEnabledException, ServiceNotAuthorizedException { final ProjectControl pc = getProjectControl(req); if (!pc.canRunReceivePack()) { throw new ServiceNotAuthorizedException(); } if (pc.getCurrentUser() instanceof IdentifiedUser) { final IdentifiedUser user = (IdentifiedUser) pc.getCurrentUser(); final ReceiveCommits rc = factory.create(pc, db); final ReceiveCommits.Capable s = rc.canUpload(); if (s != ReceiveCommits.Capable.OK) { final String who = user.getUserName(); final String why = s.getMessage(); log.warn("Rejected push from " + who + ": " + why); throw new ServiceNotEnabledException(); } rc.getReceivePack().setRefLogIdent(user.newRefLogIdent()); return rc.getReceivePack(); } else { throw new ServiceNotAuthorizedException(); } }
Source:
public final String buildFreeTextConditionSql(String tableName, String relations, String value, boolean caseSensitive) { StringBuilder sb = new StringBuilder(" ( "); boolean firstTime = true; if (!StringHelper.isNullOrEmpty(value) && !"''".equals(value)) { value = StringFormat.format(getI18NPrefix() + "'%%%1$s%%'", StringHelper.trim(value, '\'')); } if ("=".equals(relations)) { relations = getLikeSyntax(caseSensitive); } else if ("!=".equals(relations)) { relations = "NOT " + getLikeSyntax(caseSensitive); } for (String field : mColumnNameDict.keySet()) { if (mTypeDict.get(field) == String.class && !mNotFreeTextSearchableFieldsList.contains(field)) { if (firstTime) { firstTime = false; } else { sb.append(" OR "); } sb.append(StringFormat.format(" %1$s.%2$s %3$s %4$s", tableName, mColumnNameDict.get(field), relations, value)); } } sb.append(" ) "); return sb.toString(); }

Target:
public final String buildFreeTextConditionSql(String tableName, String relations, String value, boolean caseSensitive) { StringBuilder sb = new StringBuilder(" ( "); boolean firstTime = true; if (!StringHelper.isNullOrEmpty(value) && !"''".equals(value)) { value = StringFormat.format(getI18NPrefix() + "'%%%1$s%%'", StringHelper.trim(value, '\'')); } if ("=".equals(relations)) { relations = getLikeSyntax(caseSensitive); } else if ("!=".equals(relations)) { relations = "NOT " + getLikeSyntax(caseSensitive); } for (String field : columnNameDict.keySet()) { if (typeDict.get(field) == String.class && !notFreeTextSearchableFieldsList.contains(field)) { if (firstTime) { firstTime = false; } else { sb.append(" OR "); } sb.append(StringFormat.format(" %1$s.%2$s %3$s %4$s", tableName, columnNameDict.get(field), relations, value)); } } sb.append(" ) "); return sb.toString(); }
Source:
public List<Service> getServicesBlockedOnDestination(PerunSession sess, int destinationId) throws PrivilegeException, DestinationNotExistsException, FacilityNotExistsException { Destination destination = getDestinationById(sess, destinationId); List<Facility> destinationFacilities = perunBl.getFacilitiesManager().getFacilitiesByDestination(sess, destination.getDestination()); boolean isFacilityAdminAtLeastOnce = false; for (Facility facility : destinationFacilities) { if (AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facility)) { isFacilityAdminAtLeastOnce = true; } } if (!isFacilityAdminAtLeastOnce && !AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) { throw new PrivilegeException(sess, "getServicesBlockedOnDestination"); } return getServicesManagerBl().getServicesBlockedOnDestination(sess, destinationId); }

Target:
public List<Service> getServicesBlockedOnDestination(PerunSession sess, int destinationId) throws PrivilegeException, DestinationNotExistsException, FacilityNotExistsException { Destination destination = getServicesManagerBl().getDestinationById(sess, destinationId); List<Facility> destinationFacilities = perunBl.getFacilitiesManagerBl().getFacilitiesByDestination(sess, destination.getDestination()); boolean isFacilityAdminAtLeastOnce = false; for (Facility facility : destinationFacilities) { if (AuthzResolver.isAuthorized(sess, Role.FACILITYADMIN, facility)) { isFacilityAdminAtLeastOnce = true; } } if (!isFacilityAdminAtLeastOnce && !AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) { throw new PrivilegeException(sess, "getServicesBlockedOnDestination"); } return getServicesManagerBl().getServicesBlockedOnDestination(sess, destinationId); }
Source:
public PathsPromoteResult checkAnd( StoreKeyPaths k, Function<StoreKeyPaths, PathsPromoteResult> function, Function<StoreKeyPaths, PathsPromoteResult> conflictedFunction ) { Set<StoreKeyPaths> conflicts = null; boolean conflicted = false; try { logger.debug( "Check paths conflict for {}", k ); synchronized ( conflictsMap ) { conflicts = conflictsMap.get( k.getTarget() ); if ( conflicts == null ) { conflicts = new HashSet<>(); conflicts.add( k ); conflictsMap.put( k.getTarget(), conflicts ); } else { conflicted = hasConflict( k.getPaths(), conflicts ); if ( !conflicted ) { conflicts.add( k ); } } } logger.debug( "Check done, conflicted: {}", conflicted ); if ( conflicted ) { return conflictedFunction.apply( k ); } else { return function.apply( k ); } } finally { synchronized ( conflictsMap ) { conflicts.remove( k ); } } }

Target:
public PathsPromoteResult checkAnd( StoreKeyPaths k, Function<StoreKeyPaths, PathsPromoteResult> function, Function<StoreKeyPaths, PathsPromoteResult> conflictedFunction ) { Set<StoreKeyPaths> inUse = null; boolean conflicted = false; try { logger.debug( "Check paths conflict for {}", k ); synchronized ( inUseMap ) { inUse = inUseMap.get( k.getTarget() ); if ( inUse == null ) { inUse = new HashSet<>(); inUse.add( k ); inUseMap.put( k.getTarget(), inUse ); } else { conflicted = hasConflict( k.getPaths(), inUse ); if ( !conflicted ) { inUse.add( k ); } } } logger.debug( "Check done, conflicted: {}", conflicted ); if ( conflicted ) { return conflictedFunction.apply( k ); } else { return function.apply( k ); } } finally { synchronized ( inUseMap ) { inUse.remove( k ); if ( inUse.isEmpty() ) { inUseMap.remove( k.getTarget() ); } } } }
Source:
private boolean internalValidateAndSetQuota() { if (isInternalExecution()) { return true; } List<QuotaConsumptionParameter> consumptionParameters = new ArrayList<QuotaConsumptionParameter>(); try { switch (this.getActionType().getQuotaDependency()) { case NONE: return true; case STORAGE: addInternalStorageParameters(consumptionParameters); break; case VDS: addInternalVdsParameters(consumptionParameters); break; case BOTH: addInternalStorageParameters(consumptionParameters); addInternalVdsParameters(consumptionParameters); break; } } catch (ClassCastException e) { log.error("Command: " + this.getClass().getName() + ". Quota handling was expected - class does not implement the expected interface"); } QuotaConsumptionParametersWrapper quotaConsumptionParametersWrapper; if (getStoragePool() != null) { quotaConsumptionParametersWrapper = new QuotaConsumptionParametersWrapper( this.getStoragePool(), this.getReturnValue().getCanDoActionMessages(), this); quotaConsumptionParametersWrapper.setParameters(consumptionParameters); } else { quotaConsumptionParametersWrapper = new QuotaConsumptionParametersWrapper( null,this.getReturnValue().getCanDoActionMessages(), this); quotaConsumptionParametersWrapper.setParameters(consumptionParameters); log.error("Command: " + this.getClass().getName() + ". Storage pool is not available for quota calculation. "); } if (!consumptionParameters.isEmpty()) { return true; } else { return true; } }

Target:
private boolean internalValidateAndSetQuota() { if (isInternalExecution()) { return true; } List<QuotaConsumptionParameter> consumptionParameters = new ArrayList<QuotaConsumptionParameter>(); switch (this.getActionType().getQuotaDependency()) { case NONE: return true; case STORAGE: consumptionParameters.addAll(((QuotaStorageDependent) this).getQuotaStorageConsumptionParameters()); break; case VDS: consumptionParameters.addAll(((QuotaVdsDependent) this).getQuotaVdsConsumptionParameters()); break; case BOTH: consumptionParameters.addAll(((QuotaStorageDependent) this).getQuotaStorageConsumptionParameters()); consumptionParameters.addAll(((QuotaVdsDependent) this).getQuotaVdsConsumptionParameters()); break; } QuotaConsumptionParametersWrapper quotaConsumptionParametersWrapper; if (getStoragePool() != null) { quotaConsumptionParametersWrapper = new QuotaConsumptionParametersWrapper( this.getStoragePool(), this.getReturnValue().getCanDoActionMessages(), this); quotaConsumptionParametersWrapper.setParameters(consumptionParameters); } else { quotaConsumptionParametersWrapper = new QuotaConsumptionParametersWrapper( null,this.getReturnValue().getCanDoActionMessages(), this); quotaConsumptionParametersWrapper.setParameters(consumptionParameters); log.error("Command: " + this.getClass().getName() + ". Storage pool is not available for quota calculation. "); } return consumptionParameters.isEmpty() ? true: true; }
Source:
public void configure() { control("domain").set(ActiveDirectoryEnv.get().getDomain()); control("advanced-button").click(); if(ActiveDirectoryEnv.get().getController() != null) { control("server").set(ActiveDirectoryEnv.get().getController()); } if(ActiveDirectoryEnv.get().getSite() != null) { control("site").set(ActiveDirectoryEnv.get().getSite()); } control("bindPassword").set(ActiveDirectoryEnv.get().getPassword()); String bindDN = ActiveDirectoryEnv.get().getBindDN(); if(bindDN == null) { bindDN = ActiveDirectoryEnv.get().getUser()+"@"+ActiveDirectoryEnv.get().getDomain(); } control("bindName").set(bindDN); String groupLookupStrategy = ActiveDirectoryEnv.get().getGroupLookupStrategy(); if (groupLookupStrategy != null) { control("groupLookupStrategy").select(ActiveDirectoryEnv.get().getGroupLookupStrategy()); } }

Target:
public void configure() { control("domain").set(ActiveDirectoryEnv.get().getDomain()); control("advanced-button").click(); if(ActiveDirectoryEnv.get().getController() != null) { control("server").set(ActiveDirectoryEnv.get().getController()); } if(ActiveDirectoryEnv.get().getSite() != null) { control("site").set(ActiveDirectoryEnv.get().getSite()); } control("bindPassword").set(ActiveDirectoryEnv.get().getPassword()); String bindDN = ActiveDirectoryEnv.get().getBindDN(); if(bindDN == null) { bindDN = ActiveDirectoryEnv.get().getUser()+"@"+ActiveDirectoryEnv.get().getDomain(); } control("bindName").set(bindDN); String groupLookupStrategy = ActiveDirectoryEnv.get().getGroupLookupStrategy(); if (groupLookupStrategy != null) { control("groupLookupStrategy").select(groupLookupStrategy); } }
Source:
public void setContextTest() { final List<Package> packages = new ArrayList<>(); packages.add(createPackage("com")); packages.add(createPackage("com.myteam")); packages.add(createPackage("com.myteam.mymodule")); packages.add(createPackage("com.myteam.mymodule.mypackage")); final Command packagesLoadedCommand = mock(Command.class); doReturn(new HashSet<>(packages)).when(moduleService).resolvePackages(any(Module.class)); doReturn(packages.get(2)).when(moduleService).resolveDefaultWorkspacePackage(any()); packageListBox.setUp(true, packagesLoadedCommand); verify(view).setUp(eq("com.myteam.mymodule"), mapArgumentCaptor.capture()); final Map map = mapArgumentCaptor.getValue(); assertEquals(4, map.size()); assertTrue(map.keySet().contains("com")); assertTrue(map.keySet().contains("com.myteam")); assertTrue(map.keySet().contains("com.myteam.mymodule")); assertTrue(map.keySet().contains("com.myteam.mymodule.mypackage")); verify(packagesLoadedCommand).execute(); }

Target:
public void setContextTest() { setupPackageList(); final Command packagesLoadedCommand = mock(Command.class); packageListBox.setUp(true, packagesLoadedCommand); verify(view).setUp(eq("com.myteam.mymodule"), mapArgumentCaptor.capture()); final Map map = mapArgumentCaptor.getValue(); assertEquals(5, map.size()); assertTrue(map.keySet().contains("")); assertTrue(map.keySet().contains("com")); assertTrue(map.keySet().contains("com.myteam")); assertTrue(map.keySet().contains("com.myteam.mymodule")); assertTrue(map.keySet().contains("com.myteam.mymodule.mypackage")); verify(packagesLoadedCommand).execute(); }
Source:
public void run() { try { wrapped.run(); } catch (Throwable t) { LOGGER.debug("Unhandled exception while watching query response runnable.", t); queryResponse .getProcessingDetails() .add(new ProcessingDetailsImpl("unknown", new RuntimeException(t))); queryResponse.closeResultQueue(); throw t; } }

Target:
public void run() { try { wrapped.run(); } catch (Throwable t) { LOGGER.debug("Unhandled exception while watching query response runnable.", t); queryResponse .getProcessingDetails() .add( new ProcessingDetailsImpl( "unknown", new FederationException("Failed to apply federation strategy.", t))); queryResponse.closeResultQueue(); throw t; } }
Source:
public Entity<TreeReference> getEntity(TreeReference data) throws SessionUnavailableException { EvaluationContext nodeContext = new EvaluationContext(ec, data); Hashtable<String, XPathExpression> variables = getDetail().getVariableDeclarations(); for(Enumeration<String> en = variables.keys(); en.hasMoreElements();) { String key = en.nextElement(); nodeContext.setVariable(key, XPathFuncExpr.unpack(variables.get(key).eval(nodeContext))); } int length = detail.getHeaderForms().length; Object[] details = new Object[length]; String[] sortDetails = new String[length]; String[] backgroundDetails = new String[detail.getHeaderForms().length]; boolean[] relevancyDetails = new boolean[length]; int count = 0; for(DetailField f : this.getDetail().getFields()) { try { details[count] = f.getTemplate().evaluate(nodeContext); Text sortText = f.getSort(); Text backgroundText = f.getBackground(); if(sortText == null) { sortDetails[count] = null; } else { sortDetails[count] = sortText.evaluate(nodeContext); } if(backgroundText == null) { backgroundDetails[count] = "no"; } else { backgroundDetails[count] = backgroundText.evaluate(nodeContext); } relevancyDetails[count] = f.isRelevant(nodeContext); } catch(XPathException xpe) { xpe.printStackTrace(); details[count] = "<invalid xpath: " + xpe.getMessage() + ">"; } catch (XPathSyntaxException e) { e.printStackTrace(); } count++; } return new Entity<TreeReference>(details, sortDetails, backgroundDetails, relevancyDetails, data); }

Target:
public Entity<TreeReference> getEntity(TreeReference data) throws SessionUnavailableException { EvaluationContext nodeContext = new EvaluationContext(ec, data); Hashtable<String, XPathExpression> variables = getDetail().getVariableDeclarations(); for(Enumeration<String> en = variables.keys(); en.hasMoreElements();) { String key = en.nextElement(); nodeContext.setVariable(key, XPathFuncExpr.unpack(variables.get(key).eval(nodeContext))); } int length = detail.getHeaderForms().length; Object[] details = new Object[length]; String[] sortDetails = new String[length]; String[] backgroundDetails = new String[length]; boolean[] relevancyDetails = new boolean[length]; int count = 0; for(DetailField f : this.getDetail().getFields()) { try { details[count] = f.getTemplate().evaluate(nodeContext); Text sortText = f.getSort(); Text backgroundText = f.getBackground(); if(sortText == null) { sortDetails[count] = null; } else { sortDetails[count] = sortText.evaluate(nodeContext); } if(backgroundText == null) { backgroundDetails[count] = ""; } else { backgroundDetails[count] = backgroundText.evaluate(nodeContext); } relevancyDetails[count] = f.isRelevant(nodeContext); } catch(XPathException xpe) { xpe.printStackTrace(); details[count] = "<invalid xpath: " + xpe.getMessage() + ">"; } catch (XPathSyntaxException e) { e.printStackTrace(); } count++; } return new Entity<TreeReference>(details, sortDetails, backgroundDetails, relevancyDetails, data); }
Source:
public boolean equals(Object o) { if (!(o instanceof GeographyValue)) { return false; } GeographyValue that = (GeographyValue)o; if (this == that) { return true; } List<List<XYZPoint>> expectedLoops = that.m_loops; if (expectedLoops.size() != m_loops.size()) { return false; } Iterator<List<XYZPoint>> expectedLoopIt = expectedLoops.iterator(); for (List<XYZPoint> actualLoop : m_loops) { List<XYZPoint> expectedLoop = expectedLoopIt.next(); if (expectedLoop.size() != actualLoop.size()) { return false; }; Iterator<XYZPoint> expectedVertexIt = expectedLoop.iterator(); for (XYZPoint actualPt : actualLoop) { XYZPoint expectedPt = expectedVertexIt.next(); if (!expectedPt.equals(actualPt)) { return false; } } } return true; }

Target:
public boolean equals(Object o) { if (!(o instanceof GeographyValue)) { return false; } GeographyValue that = (GeographyValue)o; if (this == that) { return true; } List<List<GeographyPointValue>> expectedRings = that.getRings(); List<List<GeographyPointValue>> actualRings = getRings(); if (expectedRings.size() != actualRings.size()) { return false; } Iterator<List<GeographyPointValue>> expectedRingIt = expectedRings.iterator(); for (List<GeographyPointValue> actualRing : actualRings) { List<GeographyPointValue> expectedRing = expectedRingIt.next(); if (expectedRing.size() != actualRing.size()) { return false; }; Iterator<GeographyPointValue> expectedVertexIt = expectedRing.iterator(); for (GeographyPointValue actualPt : actualRing) { GeographyPointValue expectedPt = expectedVertexIt.next(); if (!expectedPt.equals(actualPt)) { return false; } } } return true; }
Source:
public Object getAttribute(String name) { try { switch (name) { case JAVAX_SERVLET_REQUEST_X_509_CERTIFICATE: return SecureRequestCustomizer.this.getCertChain(_request, _session); case JAVAX_SERVLET_REQUEST_CIPHER_SUITE: return _session.getCipherSuite(); case JAVAX_SERVLET_REQUEST_KEY_SIZE: return SslContextFactory.deduceKeyLength(_session.getCipherSuite()); case JAVAX_SERVLET_REQUEST_SSL_SESSION_ID: return TypeUtil.toHexString(_session.getId()); default: String sessionAttribute = getSslSessionAttribute(); if (!StringUtil.isEmpty(sessionAttribute) && sessionAttribute.equals(name)) return _session; return _attributes.getAttribute(name); } } catch (Exception e) { LOG.warn("Unable to customize request with encryption details", e); return null; } }

Target:
public Object getAttribute(String name) { Object value = _attributes.getAttribute(name); if (value != null) return value; try { switch (name) { case JAVAX_SERVLET_REQUEST_X_509_CERTIFICATE: return SecureRequestCustomizer.this.getCertChain(_request, _session); case JAVAX_SERVLET_REQUEST_CIPHER_SUITE: return _session.getCipherSuite(); case JAVAX_SERVLET_REQUEST_KEY_SIZE: return SslContextFactory.deduceKeyLength(_session.getCipherSuite()); case JAVAX_SERVLET_REQUEST_SSL_SESSION_ID: return TypeUtil.toHexString(_session.getId()); default: String sessionAttribute = getSslSessionAttribute(); if (!StringUtil.isEmpty(sessionAttribute) && sessionAttribute.equals(name)) return _session; } } catch (Exception e) { if (LOG.isDebugEnabled()) LOG.debug("Unable to get secure details ", e); } return null; }
Source:
public void setUp() { syncedPatientsPresenter = new SyncedPatientsPresenter(view, patientDAO); patientList = new ArrayList<>(); Patient patient1 = createPatient(1L); patient1.getPerson().getName().setGivenName("TEST"); Patient patient2 = createPatient(2L); patient1.getPerson().getName().setGivenName("TEST1"); Patient patient3 = createPatient(3L); patient1.getPerson().getName().setGivenName("TEST11"); patientList.add(patient1); patientList.add(patient2); patientList.add(patient3); }

Target:
public void setUp() { super.setUp(); syncedPatientsPresenter = new SyncedPatientsPresenter(view, patientDAO); patientList = new ArrayList<>(); patientList.add(createPatient(1L)); patientList.add(createPatient(2L)); patientList.add(createPatient(3L)); }
Source:
public void testConvert() { List<VariantSourceMongo> variantSourceMongos = new ArrayList<>(); String fileId = "fileId"; String fileName = "fileName"; String studyId = "studyId"; String studyName = "studyName"; StudyType type = StudyType.CONTROL; Aggregation aggregation = Aggregation.NONE; Date date = new Date(1); Map<String, Integer> samplesPosition = new HashMap<>(); Map<String, Object> metadata = new HashMap<>(); VariantGlobalStatsMongo stats = new VariantGlobalStatsMongo(1, 1, 1, 0, 0, 1, 1, 0, 1); VariantSourceMongo variantSourceMongo = new VariantSourceMongo(fileId, fileName, studyId, studyName, type, aggregation, samplesPosition, metadata, stats); VariantSource variantSource = new VariantSource(fileId, fileName, studyId, studyName, type, aggregation, date, samplesPosition, metadata, stats); variantSourceMongo.setDate(variantSource.getDate()); variantSourceMongos.add(variantSourceMongo); List<VariantSource> variantSources = service.convert(variantSourceMongos); assertEquals(variantSource, variantSources.get(0)); }

Target:
public void testConvert() { String fileId = "fileId"; String fileName = "fileName"; String studyId = "studyId"; String studyName = "studyName"; StudyType type = StudyType.CONTROL; Aggregation aggregation = Aggregation.NONE; Date date = new Date(1); Map<String, Integer> samplesPosition = new HashMap<>(); Map<String, Object> metadata = new HashMap<>(); VariantGlobalStatsMongo stats = new VariantGlobalStatsMongo(1, 1, 1, 0, 0, 1, 1, 0, 1); VariantSourceMongo variantSourceMongo = new VariantSourceMongo(fileId, fileName, studyId, studyName, type, aggregation, samplesPosition, metadata, stats); VariantSource variantSource = new VariantSource(fileId, fileName, studyId, studyName, type, aggregation, date, samplesPosition, metadata, stats); variantSourceMongo.setDate(variantSource.getDate()); List<VariantSourceMongo> variantSourceMongos = new ArrayList<>(); variantSourceMongos.add(variantSourceMongo); List<VariantSource> variantSources = service.convert(variantSourceMongos); assertEquals(variantSource, variantSources.get(0)); }
Source:
public ParameterMapping(@NotNull ParameterDefinition parameterDefinition, int index) { if (parameterDefinition == null) { throw new IllegalArgumentException("parameterDefinition is null"); } this.index = index; String parameterDefinitionName = parameterDefinition.getName(); if (parameterDefinitionName == null) { throw new IllegalStateException("parameterDefinitionName is null"); } this.name = parameterDefinitionName; this.isMultivalued = parameterDefinition.isMultiValued(); this.isMandatory = parameterDefinition.isMandatory(); }

Target:
public ParameterMapping(@NotNull ParameterDefinition parameterDefinition, int index) { if (parameterDefinition == null) { throw new IllegalArgumentException("parameterDefinition is null"); } this.index = index; String parameterDefinitionName = parameterDefinition.getName(); if (parameterDefinitionName == null) { throw new IllegalArgumentException("parameterDefinitionName is null"); } this.name = parameterDefinitionName; this.isMultivalued = parameterDefinition.isMultiValued(); this.isMandatory = parameterDefinition.isMandatory(); }
Source:
private void createBulkNewBranchMenuItem(Menu menu, final Repository[] repositories) { MenuItem newBranch = getNewBranchMenuItem(menu); newBranch.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { InputDialog dialog = new InputDialog(e.display.getActiveShell(), UIText.CreateBranchBulkDialog_Title, UIText.CreateBranchBulkDialog_Description, "", new IInputValidator() { @Override public String isValid(String newBranchName) { return validateNewBulkBranchName(newBranchName, repositories); } }); if (dialog.open() == Window.OK) { String name = dialog.getValue(); try { for (Repository repository : repositories) { Ref headRef = repository.exactRef(Constants.HEAD); if (headRef != null) { ObjectId headId = headRef.getLeaf() .getObjectId(); RevCommit head = repository.parseCommit(headId); CreateLocalBranchOperation op = new CreateLocalBranchOperation( repository, name, head); op.execute(null); } } BranchOperationUI.checkout(repositories, name).start(); } catch (Exception exception) { Activator.handleError( UIText.CreateBranchBulkDialog_Error, exception, true); } } } }); }

Target:
private void createBulkNewBranchMenuItem(Menu menu, final Repository[] repositories) { MenuItem newBranch = getNewBranchMenuItem(menu); newBranch.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { InputDialog dialog = new InputDialog(e.display.getActiveShell(), UIText.CreateBranchBulkDialog_Title, UIText.CreateBranchBulkDialog_Description, "", new IInputValidator() { @Override public String isValid(String newBranchName) { return validateNewBulkBranchName(newBranchName, repositories); } }) { @Override protected Control createDialogArea(Composite parent) { Control result = super.createDialogArea(parent); BranchNameNormalizer normalizer = new BranchNameNormalizer( getText()); normalizer.setVisible(false); return result; } }; if (dialog.open() == Window.OK) { String name = dialog.getValue(); try { for (Repository repository : repositories) { Ref headRef = repository.exactRef(Constants.HEAD); if (headRef != null) { ObjectId headId = headRef.getLeaf() .getObjectId(); RevCommit head = repository.parseCommit(headId); CreateLocalBranchOperation op = new CreateLocalBranchOperation( repository, name, head); op.execute(null); } } BranchOperationUI.checkout(repositories, name).start(); } catch (Exception exception) { Activator.handleError( UIText.CreateBranchBulkDialog_Error, exception, true); } } } }); }
Source:
public DatacenterBrokerBestFit(final CloudSim simulation) { super(simulation); setVmMapper(this::defaultVmMapper); this.vmNumberOfPesUpdated = new HashMap<>(); firstVmMapperCall = true; }

Target:
public DatacenterBrokerBestFit(final CloudSim simulation) { super(simulation); }
Source:
public <T extends BasePage> Console waitForFirstNavigationPanel(Class<T> clazz) { browser.navigate().refresh(); Graphene.goTo(HomePage.class); waitUntilLoaded(); Graphene.goTo(clazz); waitUntilLoaded().maximizeWindow(); Graphene.waitModel().until().element(By.className("navigation-column")).is().visible(); return this; }

Target:
public <T extends BasePage> Console waitForFirstNavigationPanel(Class<T> clazz) { refreshAndNavigate(clazz); Graphene.waitModel().until().element(By.className("navigation-column")).is().visible(); return this; }
Source:
private String generatejar(String pojoClassName) throws IOException, InterruptedException { String sourceDir = "src/test/resources/dynamicJar/"; String destDir = testMeta.getPath(); String version = getJavaSrcVersion(); Process p = Runtime.getRuntime() .exec(new String[] {"javac", "-source", version, "-target", version, "-d", destDir, sourceDir + pojoClassName + ".java"}, null, null); IOUtils.copy(p.getInputStream(), System.out); IOUtils.copy(p.getErrorStream(), System.err); Assert.assertEquals(0, p.waitFor()); p = Runtime.getRuntime() .exec(new String[] {"jar", "-cf", pojoClassName + ".jar", pojoClassName + ".class"}, null, new File(destDir)); IOUtils.copy(p.getInputStream(), System.out); IOUtils.copy(p.getErrorStream(), System.err); Assert.assertEquals(0, p.waitFor()); return new File(destDir, pojoClassName + ".jar").getAbsolutePath(); }

Target:
private String generatejar(String pojoClassName) throws IOException, InterruptedException { String sourceDir = "src/test/resources/dynamicJar/"; String destDir = testMeta.getPath(); String binLocation = getJavaBinLocation(); Process p = Runtime.getRuntime() .exec(new String[] {binLocation + "javac", "-d", destDir, sourceDir + pojoClassName + ".java"}, null, null); IOUtils.copy(p.getInputStream(), System.out); IOUtils.copy(p.getErrorStream(), System.err); Assert.assertEquals(0, p.waitFor()); p = Runtime.getRuntime() .exec(new String[] {binLocation + "jar", "-cf", pojoClassName + ".jar", pojoClassName + ".class"}, null, new File(destDir)); IOUtils.copy(p.getInputStream(), System.out); IOUtils.copy(p.getErrorStream(), System.err); Assert.assertEquals(0, p.waitFor()); return new File(destDir, pojoClassName + ".jar").getAbsolutePath(); }
Source:
public static ColumnValueSelector makeColumnValueSelector( ColumnSelectorFactory columnSelectorFactory, Expr expression ) { final ColumnValueSelector<ExprEval> baseSelector = makeExprEvalSelector(columnSelectorFactory, expression); return new ColumnValueSelector() { @Override public double getDouble() { return baseSelector.getDouble(); } @Override public boolean isNull() { return baseSelector.getObject().isNull(); } @Override public float getFloat() { return baseSelector.getFloat(); } @Override public long getLong() { return baseSelector.getLong(); } @Nullable @Override public Object getObject() { return baseSelector.getObject().value(); } @Override public Class classOfObject() { return Object.class; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("baseSelector", baseSelector); } }; }

Target:
public static ColumnValueSelector makeColumnValueSelector( ColumnSelectorFactory columnSelectorFactory, Expr expression ) { final ColumnValueSelector<ExprEval> baseSelector = makeExprEvalSelector(columnSelectorFactory, expression); return new ColumnValueSelector() { @Override public double getDouble() { return baseSelector.getDouble(); } @Override public float getFloat() { return baseSelector.getFloat(); } @Override public long getLong() { return baseSelector.getLong(); } @Override public boolean isNull() { return baseSelector.isNull(); } @Nullable @Override public Object getObject() { return baseSelector.getObject().value(); } @Override public Class classOfObject() { return Object.class; } @Override public void inspectRuntimeShape(RuntimeShapeInspector inspector) { inspector.visit("baseSelector", baseSelector); } }; }
Source:
private void closeNewWindows(WebDriver webDriver, String currentWindowHandle, Set<String> currentWindows) { Set<String> windowHandles = webDriver.getWindowHandles(); if (windowHandles.size() != currentWindows.size()) { Set<String> newWindows = new HashSet<>(windowHandles); newWindows.removeAll(currentWindows); log.info("File has been opened in a new window, let's close new windows", newWindows.size()); for (String newWindow : newWindows) { log.info(" Let's close {}", newWindow); try { webDriver.switchTo().window(newWindow); webDriver.close(); } catch (NoSuchWindowException windowHasBeenClosedMeanwhile) { log.info(" Failed to close {}: {}", newWindow, Cleanup.of.webdriverExceptionMessage(windowHasBeenClosedMeanwhile)); } catch (Exception e) { log.warn(" Failed to close " + newWindow + ": " + e); } } webDriver.switchTo().window(currentWindowHandle); } }

Target:
private void closeNewWindows(WebDriver webDriver, String currentWindowHandle, Set<String> currentWindows) { Set<String> windowHandles = webDriver.getWindowHandles(); if (windowHandles.size() != currentWindows.size()) { Set<String> newWindows = new HashSet<>(windowHandles); newWindows.removeAll(currentWindows); log.info("File has been opened in a new window, let's close new windows", newWindows.size()); for (String newWindow : newWindows) { log.info(" Let's close {}", newWindow); try { webDriver.switchTo().window(newWindow); webDriver.close(); } catch (NoSuchWindowException windowHasBeenClosedMeanwhile) { log.info(" Failed to close {}: {}", newWindow, Cleanup.of.webdriverExceptionMessage(windowHasBeenClosedMeanwhile)); } catch (Exception e) { log.warn(" Failed to close {}", newWindow, e); } } webDriver.switchTo().window(currentWindowHandle); } }
Source:
public RichMember call(ApiCaller ac, Deserializer params) throws PerunException { ac.stateChangingCheck(); String password = params.readString("password"); Vo vo = ac.getVoById(params.readInt("vo")); String namespace = params.readString("namespace"); User sponsor = null; if(params.contains("sponsor")) { sponsor = ac.getUserById(params.readInt("sponsor")); } Map<String, String> name = new HashMap<>(); if (params.contains("firstName")) { name.put("firstName", params.readString("firstName")); name.put("lastName", params.readString("lastName")); if (params.contains("titleBefore")) name.put("titleBefore", params.readString("titleBefore")); if (params.contains("titleAfter")) name.put("titleAfter", params.readString("titleAfter")); } else { name.put("guestName", params.readString("guestName")); } return ac.getMembersManager().createSponsoredMember(ac.getSession(), vo, namespace, name, password, sponsor); }

Target:
public RichMember call(ApiCaller ac, Deserializer params) throws PerunException { ac.stateChangingCheck(); String password = params.readString("password"); Vo vo = ac.getVoById(params.readInt("vo")); String namespace = params.readString("namespace"); User sponsor = null; if(params.contains("sponsor")) { sponsor = ac.getUserById(params.readInt("sponsor")); } Map<String, String> name = new HashMap<>(); if (params.contains("guestName")) { name.put("guestName", params.readString("guestName")); } else if (params.contains("firstName") && params.contains("lastName")) { name.put("firstName", params.readString("firstName")); name.put("lastName", params.readString("lastName")); if (params.contains("titleBefore")) name.put("titleBefore", params.readString("titleBefore")); if (params.contains("titleAfter")) name.put("titleAfter", params.readString("titleAfter")); } else { throw new RpcException(RpcException.Type.MISSING_VALUE, "Missing value. Either 'guestName' or ('firstName' and 'lastName') must be sent."); } return ac.getMembersManager().createSponsoredMember(ac.getSession(), vo, namespace, name, password, sponsor); }