auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public HttpResponse getTierPermissionsPage() throws APIManagerIntegrationTestException { try { checkAuthentication(); return HttpRequestUtil.doGet(backEndUrl + "/publisher/site/pages/tiers.jag", requestHeaders); } catch (Exception e) { throw new APIManagerIntegrationTestException("Exception when retrieving the Tier Permissions page", e); } }

Target:
public HttpResponse getTierPermissionsPage() throws APIManagerIntegrationTestException { try { checkAuthentication(); return HttpRequestUtil.doGet(backendURL + "/publisher/site/pages/tiers.jag", requestHeaders); } catch (Exception e) { throw new APIManagerIntegrationTestException("Exception when retrieving the Tier Permissions page", e); } }
Source:
public void log(final Long accountId, final DateTime lastSleepCycleEnd, final DateTime now, final DateTime nextRingTime, final DateTime nextRegularRingTime){ final Map<String, AttributeValue> items = new HashMap<>(); items.put(ACCOUNT_ID_ATTRIBUTE_NAME, new AttributeValue().withN(accountId.toString())); items.put(CURRENT_TIME_ATTRIBUTE_NAME, new AttributeValue().withS(now.toString(DATETIME_FORMAT))); items.put(EXPECTED_RING_TIME_ATTRIBUTE_NAME, new AttributeValue().withS(nextRegularRingTime.toString(DATETIME_FORMAT))); items.put(SMART_RING_TIME_ATTRIBUTE_NAME, new AttributeValue().withS(nextRingTime.toString(DATETIME_FORMAT))); items.put(LAST_SLEEP_CYCLE_ATTRIBUTE_NAME, new AttributeValue().withS(lastSleepCycleEnd.toString(DATETIME_FORMAT))); final PutItemRequest putItemRequest = new PutItemRequest(this.tableName, items); try { final PutItemResult result = this.dynamoDBClient.putItem(putItemRequest); }catch (AmazonServiceException awsEx){ LOGGER.error("Log smart alarm for account failed, client error", accountId); }catch (AmazonClientException awcEx){ LOGGER.error("Log smart alarm for account failed, client error.", accountId); } }

Target:
public void log(final Long accountId, final DateTime lastSleepCycleEnd, final DateTime now, final DateTime nextRingTime, final DateTime nextRegularRingTime){ final Map<String, AttributeValue> items = new HashMap<>(); items.put(ACCOUNT_ID_ATTRIBUTE_NAME, new AttributeValue().withN(accountId.toString())); items.put(CURRENT_TIME_ATTRIBUTE_NAME, new AttributeValue().withS(now.toString(DATETIME_FORMAT))); items.put(EXPECTED_RING_TIME_ATTRIBUTE_NAME, new AttributeValue().withS(nextRegularRingTime.toString(DATETIME_FORMAT))); items.put(SMART_RING_TIME_ATTRIBUTE_NAME, new AttributeValue().withS(nextRingTime.toString(DATETIME_FORMAT))); items.put(LAST_SLEEP_CYCLE_ATTRIBUTE_NAME, new AttributeValue().withS(lastSleepCycleEnd.toString(DATETIME_FORMAT))); final PutItemRequest putItemRequest = new PutItemRequest(this.tableName, items); try { final PutItemResult result = this.dynamoDBClient.putItem(putItemRequest); }catch (AmazonServiceException awsEx){ LOGGER.error("Log smart alarm for account failed, aws service error {}", accountId, awsEx.getMessage()); }catch (AmazonClientException awcEx){ LOGGER.error("Log smart alarm for account failed, client error.", accountId, awcEx.getMessage()); } }
Source:
protected void updateTriggerName(NotificationContext context) { String newTriggerName = context.getTrigger().getName(); Metric triggeredMetric = context.getTriggeredMetric(); newTriggerName = newTriggerName.replaceAll("\\$\\{scope\\}", triggeredMetric.getScope()); newTriggerName = newTriggerName.replaceAll("\\$\\{metric\\}", triggeredMetric.getMetric()); Map<String, String> tags = triggeredMetric.getTags(); Matcher m = Pattern.compile("\\$\\{.*?\\}").matcher(newTriggerName); while (m.find()) { String currentRegex = m.group(), currentTagKey = currentRegex.substring(2, currentRegex.length()-1); if (tags.containsKey(currentTagKey)) newTriggerName = newTriggerName.replace(currentRegex, tags.get(currentTagKey)); } context.getTrigger().setName(newTriggerName); }

Target:
protected void updateTriggerName(NotificationContext context) { String newTriggerName = context.getTrigger().getName(); Metric triggeredMetric = context.getTriggeredMetric(); newTriggerName = newTriggerName.replaceAll("(?i)\\$\\{scope\\}", triggeredMetric.getScope()); newTriggerName = newTriggerName.replaceAll("(?i)\\$\\{metric\\}", triggeredMetric.getMetric()); Map<String, String> tags = triggeredMetric.getTags(); Map<String, String> lowerCaseTagMap = getLowerCaseTagMap(tags); Matcher m = Pattern.compile("(?i)\\$\\{.*?\\}").matcher(newTriggerName); while (m.find()) { String currentRegex = m.group(), currentTagKey = currentRegex.substring(2, currentRegex.length()-1).toLowerCase(); if (lowerCaseTagMap.containsKey(currentTagKey)) newTriggerName = newTriggerName.replace(currentRegex, lowerCaseTagMap.get(currentTagKey)); } context.getTrigger().setName(newTriggerName); }
Source:
public Tag saveIfDoesntExists(Tag newTag) { Tag existingTag = findBySluggedName(newTag.getUriName()); if (existingTag == null){ session.save(newTag); return newTag; } return existingTag; }

Target:
public Tag saveIfDoesntExists(Tag newTag) { Tag existingTag = findByUriName(newTag.getUriName()); if (existingTag == null){ session.save(newTag); return newTag; } return existingTag; }
Source:
protected void doSetValue(T value) { if (this.value != value) { fireValueChange(Diffs.createValueDiff(this.value, this.value = value)); } }

Target:
protected final void doSetValue(T value) { if (this.value != value) { fireValueChange(Diffs.createValueDiff(this.value, this.value = value)); } }
Source:
private Folder createExtension(final IConfigurationElement element, final String classAttribute) throws Exception { Folder folder = null; try { Bundle extensionBundle = Platform.getBundle(element.getDeclaringExtension().getNamespaceIdentifier()); URL url = extensionBundle.getResource(classAttribute); if (null != url) { URI uri = URI.createURI(url.toURI().toASCIIString()); String creationMenuId = getCreationMenuId(uri); folder = getCreationMenuModel(uri); defaultValues.put(creationMenuId, folder.isVisible()); String visible = preferences.get(creationMenuId, "true"); folder.setVisible(Boolean.valueOf(visible)); rootFolders.put(creationMenuId, folder); } } catch (URISyntaxException e) { throw new Exception(Messages.CreationMenuRegistry_Error_UnableToCreateExtension + e); } return folder; }

Target:
private Folder createExtension(final IConfigurationElement element, final String classAttribute) throws Exception { Folder folder = null; try { Bundle extensionBundle = Platform.getBundle(element.getDeclaringExtension().getNamespaceIdentifier()); URL url = extensionBundle.getResource(classAttribute); if (null != url) { URI uri = URI.createPlatformPluginURI(element.getContributor().getName() + File.separator + classAttribute, false); String creationMenuId = getCreationMenuId(uri); folder = getCreationMenuModel(uri); defaultValues.put(creationMenuId, folder.isVisible()); String visible = preferences.get(creationMenuId, "true"); folder.setVisible(Boolean.valueOf(visible)); rootFolders.put(creationMenuId, folder); } } catch (URISyntaxException e) { throw new Exception(Messages.CreationMenuRegistry_Error_UnableToCreateExtension + e); } return folder; }
Source:
protected void setAttachments(SQLDatabase db,BasicDocumentRevision rev, PreparedAndSavedAttachments preparedAndSavedAttachments) throws AttachmentNotSavedException, AttachmentException { if (preparedAndSavedAttachments == null || preparedAndSavedAttachments.isEmpty()) { return; } try { for (PreparedAttachment a : preparedAndSavedAttachments.preparedAttachments) { this.addAttachment(db,a, rev); } for (SavedAttachment a : preparedAndSavedAttachments.savedAttachments) { long parentSequence = ((SavedAttachment) a).seq; long newSequence = rev.getSequence(); this.copyAttachment(db,parentSequence, newSequence, a.name); } } catch (SQLException sqe) { throw new AttachmentException("SQLException setting attachment for rev"+rev, sqe); } }

Target:
protected void setAttachments(SQLDatabase db,BasicDocumentRevision rev, PreparedAndSavedAttachments preparedAndSavedAttachments) throws AttachmentNotSavedException, DatastoreException { if (preparedAndSavedAttachments == null || preparedAndSavedAttachments.isEmpty()) { return; } try { for (PreparedAttachment a : preparedAndSavedAttachments.preparedAttachments) { this.addAttachment(db,a, rev); } for (SavedAttachment a : preparedAndSavedAttachments.savedAttachments) { long parentSequence = ((SavedAttachment) a).seq; long newSequence = rev.getSequence(); this.copyAttachment(db,parentSequence, newSequence, a.name); } } catch (SQLException sqe) { throw new DatastoreException("SQLException setting attachment for rev"+rev, sqe); } }
Source:
private void deleteRepositoryPath(Repository repository, Path path) throws IOException { String url = getContextBaseUrl() + "/delete"; RepositoryPath repositoryPath = (RepositoryPath) path.toRealPath(); String repositoryPathStr = RepositoryFiles.relativizePath(repositoryPath); PathForm pathForm = buildPathForm(repository.getStorage().getId(), repository.getId(), repositoryPathStr, false); givenCustom().contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE) .body(pathForm) .when() .delete(url) .prettyPeek() .then() .body(containsString(SUCCESSFUL_PATH_REMOVAL)); }

Target:
private void deleteRepositoryPath(Repository repository, Path path) throws IOException { String url = getContextBaseUrl() + "/delete"; assertThat(Files.exists(path)) .as("Failed to locate repository path '" + path + "'!") .isTrue(); RepositoryPath repositoryPath = (RepositoryPath) path.toRealPath(); String repositoryPathStr = RepositoryFiles.relativizePath(repositoryPath); PathForm pathForm = buildPathForm(repository.getStorage().getId(), repository.getId(), repositoryPathStr, false); givenCustom().contentType(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_VALUE) .body(pathForm) .when() .delete(url) .prettyPeek() .then() .body(containsString(SUCCESSFUL_REPOSITORY_PATH_REMOVAL)); assertThat(Files.notExists(path)) .as("Failed to delete repository path '" + path + "'!") .isTrue(); }
Source:
public static String removeUnwantedCharacters(String key, String unwantedCharacters) { List<Character> unwantedChars = new ArrayList<>(); for (char ch : unwantedCharacters.toCharArray()) { unwantedChars.add(ch); } String newKey = key.chars() .filter(c -> unwantedCharacters.indexOf(c) == -1) .filter(c -> !DISALLOWED_CHARACTERS.contains((char) c)) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); return StringUtil.replaceSpecialCharacters(newKey); }

Target:
public static String removeUnwantedCharacters(String key, String unwantedCharacters) { String newKey = key.chars() .filter(c -> unwantedCharacters.indexOf(c) == -1) .filter(c -> !DISALLOWED_CHARACTERS.contains((char) c)) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); return StringUtil.replaceSpecialCharacters(newKey); }
Source:
public void markDiskDown() { }

Target:
public void markDiskDown() { throw new UnsupportedOperationException("markDiskDown() is not supported."); }
Source:
public void resumeAnsSuspendParallel() throws Exception { brothers = new Brother[4]; prism.getClusterHelper().submitEntity(URLS.SUBMIT_URL, bundles[0].getClusters().get(0)); prism.getFeedHelper().submitEntity(URLS.SUBMIT_URL, bundles[0].getDataSets().get(0)); prism.getFeedHelper().schedule(URLS.SCHEDULE_URL, bundles[0].getDataSets().get(0)); Thread.sleep(15000); prism.getFeedHelper().suspend(URLS.SUSPEND_URL, bundles[0].getDataSets().get(0)); Thread.sleep(15000); for (int i = 1; i <= 2; i++) { brothers[i - 1] = new Brother("brother" + i, "resume", ENTITY_TYPE.DATA, brotherGrimm, bundles[0], prism, URLS.RESUME_URL); } for (int i = 3; i <= 4; i++) { brothers[i - 1] = new Brother("brother" + i, "suspend", ENTITY_TYPE.DATA, brotherGrimm, bundles[0], prism, URLS.SUSPEND_URL); } for (Brother brother : brothers) { brother.start(); } for (Brother brother : brothers) { brother.join(); } for (Brother brother : brothers) { logger.info(brother.getName() + " output: \n" + Util.prettyPrintXml(brother.getOutput().getMessage())); AssertUtil.assertSucceeded(brother.getOutput()); } }

Target:
public void resumeAnsSuspendParallel() throws Exception { brothers = new Brother[4]; prism.getClusterHelper().submitEntity(URLS.SUBMIT_URL, bundles[0].getClusters().get(0)); prism.getFeedHelper().submitEntity(URLS.SUBMIT_URL, bundles[0].getDataSets().get(0)); AssertUtil.assertSucceeded(prism.getFeedHelper().schedule(URLS.SCHEDULE_URL, bundles[0].getDataSets().get(0))); Thread.sleep(15000); prism.getFeedHelper().suspend(URLS.SUSPEND_URL, bundles[0].getDataSets().get(0)); Thread.sleep(15000); for (int i = 1; i <= 2; i++) { brothers[i - 1] = new Brother("brother" + i, "resume", ENTITY_TYPE.DATA, brotherGrimm, bundles[0], prism, URLS.RESUME_URL); } for (int i = 3; i <= 4; i++) { brothers[i - 1] = new Brother("brother" + i, "suspend", ENTITY_TYPE.DATA, brotherGrimm, bundles[0], prism, URLS.SUSPEND_URL); } for (Brother brother : brothers) { brother.start(); } for (Brother brother : brothers) { brother.join(); } for (Brother brother : brothers) { logger.info(brother.getName() + " output: \n" + Util.prettyPrintXml(brother.getOutput().getMessage())); AssertUtil.assertSucceeded(brother.getOutput()); } }
Source:
public synchronized StreamBuildListener createEventsListener() { File eventsFile = getEventsFile(); if (!eventsFile.getParentFile().isDirectory() && !eventsFile.getParentFile().mkdirs()) { LOGGER.log(Level.WARNING, "Could not create directory {0} for {1}", new Object[]{eventsFile.getParentFile(), folder.getFullName()}); } if (eventStreams == null || !eventsFile.equals(eventStreams.getFile())) { eventStreams = new EventOutputStreams(eventsFile, 250, TimeUnit.MILLISECONDS, 1024, true, EVENT_LOG_MAX_SIZE * 1024, BACKUP_LOG_COUNT == null ? 0 : Math.max(0, BACKUP_LOG_COUNT) ); } return new StreamBuildListener(eventStreams.get(), Charsets.UTF_8); }

Target:
public synchronized StreamTaskListener createEventsListener() { File eventsFile = getEventsFile(); if (!eventsFile.getParentFile().isDirectory() && !eventsFile.getParentFile().mkdirs()) { LOGGER.log(Level.WARNING, "Could not create directory {0} for {1}", new Object[]{eventsFile.getParentFile(), folder.getFullName()}); } if (eventStreams == null) { eventStreams = new EventOutputStreams(new EventOutputStreams.OutputFile() { @NonNull @Override public File get() { return getEventsFile(); } @Override public boolean canWriteNow() { GregorianCalendar timestamp = new GregorianCalendar(); timestamp.setTimeInMillis(System.currentTimeMillis() - 10000L); Queue.Item probe = new Queue.WaitingItem(timestamp, folder, Collections.<Action>emptyList()); for (QueueTaskDispatcher d: QueueTaskDispatcher.all()) { if (d.canRun(probe) != null) { return false; } } return true; } }, 250, TimeUnit.MILLISECONDS, 1024, true, EVENT_LOG_MAX_SIZE * 1024, BACKUP_LOG_COUNT == null ? 0 : Math.max(0, BACKUP_LOG_COUNT) ); } return new StreamTaskListener(eventStreams.get(), Charsets.UTF_8); }
Source:
public void setup() { System.out.println("AbstractRepositorySettingsPageTest.setup()"); TasksUiTestUtil.ensureTasksUiInitialization(); System.out.println("called ensureTasksUiInitialization"); TasksUiPlugin.getRepositoryManager().addRepositoryConnector(new BugzillaRestConnector()); TasksUiPlugin.getDefault().addRepositoryConnectorUi(new BugzillaRestRepositoryConnectorUi()); }

Target:
public void setup() { TasksUiPlugin.getDefault().addRepositoryConnectorUi(new BugzillaRestRepositoryConnectorUi()); }
Source:
protected void handleResult(InvocationResult resultArg, Message request, Channel channel, Object source) { if (channel != null) { if (resultArg.getReturnValue() instanceof ListenableFuture) { ((ListenableFuture<?>) resultArg.getReturnValue()).addCallback( r -> asyncSuccess(resultArg, request, channel, source, r), t -> asyncFailure(request, channel, t)); } else if (resultArg.getReturnValue() instanceof Mono) { ((Mono<?>) resultArg.getReturnValue()).subscribe( r -> asyncSuccess(resultArg, request, channel, source, r), t -> asyncFailure(request, channel, t)); } else { doHandleResult(resultArg, request, channel, source); } } else if (this.logger.isWarnEnabled()) { this.logger.warn("Listener method returned result [" + resultArg + "]: not generating response message for it because no Rabbit Channel given"); } }

Target:
protected void handleResult(InvocationResult resultArg, Message request, Channel channel, Object source) { if (channel != null) { if (resultArg.getReturnValue() instanceof ListenableFuture) { ((ListenableFuture<?>) resultArg.getReturnValue()).addCallback( r -> asyncSuccess(resultArg, request, channel, source, r), t -> asyncFailure(request, channel, t)); } else if (monoPresent && MonoHandler.isMono(resultArg.getReturnValue())) { MonoHandler.subscribe(resultArg.getReturnValue(), r -> asyncSuccess(resultArg, request, channel, source, r), t -> asyncFailure(request, channel, t)); } else { doHandleResult(resultArg, request, channel, source); } } else if (this.logger.isWarnEnabled()) { this.logger.warn("Listener method returned result [" + resultArg + "]: not generating response message for it because no Rabbit Channel given"); } }
Source:
public void testInvalidXsdTargetNamespace() { final String drl1 = "package org.drools.compiler\n" + "rule R1 when\n" + " $m : Message()\n" + "then\n" + "end\n"; final String kmodule = "<kmodule xmlns:xsi=\"<LINK_1>\" \n" + " xmlns=\"<LINK_0>\">\n" + " <kbase name=\"kbase1\">\n" + " <ksession name=\"ksession1\" default=\"true\"/>\n" + " </kbase>\n" + "</kmodule>"; final KieServices ks = KieServices.Factory.get(); final ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-kie-builder", "1.0.0" ); final Resource r1 = ResourceFactory.newByteArrayResource( drl1.getBytes() ).setResourceType( ResourceType.DRL ).setSourcePath( "kbase1/drl1.drl" ); try { final KieModule km = createAndDeployJar(ks, kmodule, releaseId1, r1); Assertions.fail("Test should throw a validation exception!"); } catch (IllegalStateException ex) { Assertions.assertThat(ex).hasMessageContaining("XSD validation failed"); } }

Target:
public void testInvalidXsdTargetNamespace() { final String drl1 = "package org.drools.compiler\n" + "rule R1 when\n" + " $m : Message()\n" + "then\n" + "end\n"; final String kmodule = "<kmodule xmlns:xsi=\"<LINK_1>\" \n" + " xmlns=\"<LINK_0>\">\n" + " <kbase name=\"kbase1\">\n" + " <ksession name=\"ksession1\" default=\"true\"/>\n" + " </kbase>\n" + "</kmodule>"; final KieServices ks = KieServices.Factory.get(); final ReleaseId releaseId1 = ks.newReleaseId( "org.kie", "test-kie-builder", "1.0.0" ); final Resource r1 = ResourceFactory.newByteArrayResource( drl1.getBytes() ).setResourceType( ResourceType.DRL ).setSourcePath( "kbase1/drl1.drl" ); Assertions.assertThatThrownBy(() -> createAndDeployJar(ks, kmodule, releaseId1, r1)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("XSD validation failed"); }
Source:
public boolean isBalanced(ClusterCacheStatus cacheStatus) { if(cacheStatus == null){ return true; } synchronized(cacheStatus){ CacheTopology cacheTopology = cacheStatus.getCacheTopology(); ConsistentHashFactory chFactory = cacheStatus.getJoinInfo().getConsistentHashFactory(); ConsistentHash currentCH = cacheTopology.getCurrentCH(); ConsistentHash updatedMembersCH = chFactory.updateMembers(currentCH, cacheStatus.getMembers()); ConsistentHash balancedCH = chFactory.rebalance(updatedMembersCH); if (currentCH == null || balancedCH.equals(currentCH)) { return true; } return false; } }

Target:
public boolean isBalanced(ClusterCacheStatus cacheStatus) { if(cacheStatus == null){ return true; } synchronized(cacheStatus){ CacheTopology cacheTopology = cacheStatus.getCacheTopology(); ConsistentHashFactory chFactory = cacheStatus.getJoinInfo().getConsistentHashFactory(); ConsistentHash currentCH = cacheTopology.getCurrentCH(); ConsistentHash updatedMembersCH = chFactory.updateMembers(currentCH, cacheStatus.getMembers()); ConsistentHash balancedCH = chFactory.rebalance(updatedMembersCH); if (balancedCH.equals(currentCH)) { return true; } return false; } }
Source:
public void testManualRegistrationId() throws InterruptedException, JSONException { SwrveConfig config = new SwrveConfig(); initLocalHttpServer(activity, config); config.setSenderId("12345"); config.setObtainRegistrationIdEnabled(false); Swrve swrve = (Swrve) SwrveSDK.createInstance(activity, 1, "apiKey", config); swrve.onCreate(activity); swrve.setRegistrationId("manual_reg_id"); boolean foundPost = false; int retries = 10; while(!foundPost && (retries--) > 0) { Iterator<TestHttpServer.TestHttpPostRequest> it = httpEventServer.postRequests.iterator(); while(it.hasNext()) { TestHttpServer.TestHttpPostRequest request = it.next(); if (request.body.contains("swrve.gcm_token")) { JSONArray jsonEvents = request.getEventsJSON(); if (jsonEvents != null && jsonEvents.length() > 0) { for (int i = 0; i < jsonEvents.length() && !foundPost; i++) { JSONObject jsonEvent = jsonEvents.getJSONObject(i); if (jsonEvent.get("type").equals("user")) { JSONObject jsonAttributes = jsonEvent.getJSONObject("attributes"); if (jsonAttributes.has("swrve.gcm_token")) { foundPost = jsonAttributes.get("swrve.gcm_token").equals("manual_reg_id"); } } } } } } if (!foundPost) { Thread.sleep(1000); } } assertTrue(foundPost); swrve.onDestroy(activity); }

Target:
public void testManualRegistrationId() throws InterruptedException, JSONException { SwrveConfig config = new SwrveConfig(); config.setSenderId("12345"); config.setPushRegistrationAutomatic(false); Swrve swrve = (Swrve) SwrveSDK.createInstance(activity, 1, "apiKey", config); swrve.onCreate(activity); swrve.setRegistrationId("manual_reg_id"); JSONObject deviceValuesToSend = swrve.getDeviceInfo(); assertEquals("manual_reg_id", deviceValuesToSend.get("swrve.gcm_token")); swrve.onDestroy(activity); }
Source:
public void testRepartitionedJoin() { JoinNode join = join("join", tableScan("ts1", "orderkey"), tableScan("ts2", "orderkey_0"), JoinNode.DistributionType.PARTITIONED, "orderkey", "orderkey_0"); Map<String, PlanNodeCostEstimate> costs = ImmutableMap.of( "ts1", cpuCost(6000), "ts2", cpuCost(1000)); Map<String, PlanNodeStatsEstimate> stats = ImmutableMap.of( "join", statsEstimate(12000), "ts1", statsEstimate(6000), "ts2", statsEstimate(1000)); assertCost( join, costs, stats) .cpu(12000 + 6000 + 1000 + 6000 + 1000); assertCostEstimatedExchanges( join, costs, stats) .cpu(12000 + 6000 + 1000 + 6000 + 1000 + 6000 + 1000 + 1000); assertCostHasUnknownComponentsForUnknownStats(join); }

Target:
public void testRepartitionedJoin() { TableScanNode ts1 = tableScan("ts1", "orderkey"); TableScanNode ts2 = tableScan("ts2", "orderkey_0"); JoinNode join = join("join", ts1, ts2, JoinNode.DistributionType.PARTITIONED, "orderkey", "orderkey_0"); Map<String, PlanNodeCostEstimate> costs = ImmutableMap.of( "ts1", cpuCost(6000), "ts2", cpuCost(1000)); Map<String, PlanNodeStatsEstimate> stats = ImmutableMap.of( "join", statsEstimate(join, 12000), "ts1", statsEstimate(ts1, 6000), "ts2", statsEstimate(ts2, 1000)); assertCost(join, costs, stats) .cpu(12000 + 6000 + 1000 + 6000 + 1000) .memory(1000) .network(0); assertCostEstimatedExchanges(join, costs, stats) .cpu(12000 + 6000 + 1000 + 6000 + 1000 + 6000 + 1000 + 1000) .memory(1000) .network(6000 + 1000); assertCostHasUnknownComponentsForUnknownStats(join); }
Source:
protected Control createDialogArea(Composite parent) { Composite control = (Composite)super.createDialogArea(parent); Text text = null; for (Control c: control.getChildren()) { if(c instanceof Text) { text = (Text)c; break; } } if(text != null) { IObservableValue modelObservable = BeanProperties.value(InputModel.VALUE).observe(model); IObservableValue textObservable = WidgetProperties.text(SWT.Modify).observe(text); ValueBindingBuilder.bind(textObservable).to(modelObservable).in(dbc); ValidationStatusProvider validator = new ValidationStatusProvider(textObservable); getValidator().setProvider(validator); dbc.addValidationStatusProvider(validator); ControlDecorationSupport.create(validator, SWT.LEFT | SWT.TOP); setErrorMessage(getValidator().isValid(initialValue)); } else { OpenShiftUIActivator.getDefault().getLogger().logError(new NullPointerException("Cannot find text widget.")); } return control; }

Target:
protected Control createDialogArea(Composite parent) { Composite control = (Composite)super.createDialogArea(parent); Text text = getFirstTextControl(control.getChildren()); if(text != null) { IObservableValue modelObservable = BeanProperties.value(InputModel.VALUE).observe(model); IObservableValue textObservable = WidgetProperties.text(SWT.Modify).observe(text); ValueBindingBuilder.bind(textObservable).to(modelObservable).in(dbc); ValidationStatusProvider validator = new ValidationStatusProvider(textObservable); getValidator().setProvider(validator); dbc.addValidationStatusProvider(validator); ControlDecorationSupport.create(validator, SWT.LEFT | SWT.TOP); setErrorMessage(getValidator().isValid(initialValue)); } else { OpenShiftUIActivator.getDefault().getLogger().logError(new NullPointerException("Cannot find text widget.")); } return control; }
Source:
public App(String name, String contextPath, Set<Component> components, Set<Theme> themes, Configuration configuration, Bindings bindings, I18nResources i18nResources, SessionManager sessionManager) { this.name = name; this.contextPath = contextPath; this.components = components.stream().collect(Collectors.toMap(Component::getContextPath, cmp -> cmp)); this.rootComponent = this.components.get(Component.ROOT_COMPONENT_CONTEXT_PATH); this.themes = themes.stream().collect(Collectors.toMap(Theme::getName, theme -> theme)); this.defaultTheme = configuration.getThemeName() .map(configuredThemeName -> { Theme configuredTheme = App.this.themes.get(configuredThemeName); if (configuredTheme == null) { throw new IllegalArgumentException( "Theme '" + configuredThemeName + "' which is configured for app '" + name + "' does not exists. Available themes: " + themes); } return configuredTheme; }).orElse(null); this.lookup = new Lookup(components, configuration, bindings, i18nResources); this.configuration = configuration; this.sessionManager = sessionManager; this.sessionManager.init(configuration); }

Target:
public App(String name, String contextPath, Set<Component> components, Set<Theme> themes, Configuration configuration, Bindings bindings, I18nResources i18nResources, SessionManager sessionManager) { this.name = name; this.contextPath = contextPath; this.components = components.stream().collect(Collectors.toMap(Component::getContextPath, cmp -> cmp)); this.rootComponent = this.components.get(Component.ROOT_COMPONENT_CONTEXT_PATH); this.themes = themes.stream().collect(Collectors.toMap(Theme::getName, theme -> theme)); this.defaultTheme = configuration.getThemeName() .map(configuredThemeName -> { Theme configuredTheme = App.this.themes.get(configuredThemeName); if (configuredTheme == null) { throw new IllegalArgumentException( "Theme '" + configuredThemeName + "' which is configured for app '" + name + "' does not exists. Available themes: " + themes); } return configuredTheme; }).orElse(null); this.lookup = new Lookup(components, configuration, bindings, i18nResources); this.configuration = configuration; this.sessionManager = sessionManager; }
Source:
public ModelAndView pluginStatusReport(Request request, Response response) { String pluginId = request.params("plugin_id"); try { String pluginStatusReport = elasticAgentPluginService.getPluginStatusReport(pluginId); Map<Object, Object> object = new HashMap<>() {{ put("viewTitle", "Plugin Status Report"); put("viewFromPlugin", pluginStatusReport); }}; return new ModelAndView(object, "status_reports/index.ftlh"); } catch (RecordNotFoundException e) { return errorPage(response, 404, "Plugin Status Report", e.getMessage()); } catch (UnsupportedOperationException e) { String message = String.format("Status Report for plugin with id: '%s' is not found.", pluginId); return errorPage(response, 404, "Plugin Status Report", message); } catch (RulesViolationException | SecretResolutionFailureException e) { LOGGER.error(e.getMessage(), e); return errorPage(response, 422, "Plugin Status Report", e.getMessage()); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return errorPage(response, 500, "Plugin Status Report", UNKNOWN_ERROR_MESSAGE); } }

Target:
public ModelAndView pluginStatusReport(Request request, Response response) { String pluginId = request.params("plugin_id"); try { String pluginStatusReport = elasticAgentPluginService.getPluginStatusReport(pluginId); Map<Object, Object> object = new HashMap<>() {{ put("viewTitle", "Plugin Status Report"); put("viewFromPlugin", pluginStatusReport); }}; return new ModelAndView(object, "status_reports/index.ftlh"); } catch (RecordNotFoundException e) { return errorPage(response, 404, "Plugin Status Report", e.getMessage()); } catch (UnsupportedOperationException e) { String message = String.format("Status Report for plugin with id: '%s' is not found.", pluginId); return errorPage(response, 404, "Plugin Status Report", message); } catch (RulesViolationException | SecretResolutionFailureException e) { LOGGER.error(e.getMessage(), e); return errorPage(response, 500, "Plugin Status Report", e.getMessage()); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return errorPage(response, 500, "Plugin Status Report", UNKNOWN_ERROR_MESSAGE); } }
Source:
private VmStatic getVmStatic() { VmStatic vmStatic = new VmStatic(); vmStatic.setOs(0); vmStatic.setMemSizeMb(300); vmStatic.setStateless(false); vmStatic.setVmtGuid(vmTemplateId); return vmStatic; }

Target:
private VmStatic getVmStatic() { VmStatic vmStatic = new VmStatic(); vmStatic.setOs(OsRepository.DEFAULT_OS); vmStatic.setMemSizeMb(300); vmStatic.setStateless(false); vmStatic.setVmtGuid(vmTemplateId); return vmStatic; }
Source:
public static UserNameAndPassword getBasicAuthenticationCredentials(HttpServletRequest httpRequest) { String header = httpRequest.getHeader(AuthorizationConstants.AUTHORIZATION_HEADER_NAME); if (StringUtils.isBlank(header) || !header.startsWith(AuthorizationConstants.BASIC_PREFIX)) { return null; } String base64EncodedCredentials = header.substring(AuthorizationConstants.BASIC_PREFIX.length()).trim(); String basicCredentials = null; try { basicCredentials = new String(BASE64_DECODER.decode(base64EncodedCredentials), StandardCharsets.UTF_8); } catch(IllegalArgumentException e) { return null; } int colon = basicCredentials.indexOf(":"); if (colon>0 && colon<basicCredentials.length()-1) { String name = basicCredentials.substring(0, colon); String password = basicCredentials.substring(colon+1); return new UserNameAndPassword(name, password); } return null; }

Target:
public static Optional<UserNameAndPassword> getBasicAuthenticationCredentials(HttpServletRequest httpRequest) throws IllegalArgumentException { String header = httpRequest.getHeader(AuthorizationConstants.AUTHORIZATION_HEADER_NAME); if (StringUtils.isBlank(header)) { return Optional.empty(); } if (!header.startsWith(AuthorizationConstants.BASIC_PREFIX)) { throw new IllegalArgumentException(String.format(INVALID_AUTH_MSG_FORMAT, "Missing \"" + AuthorizationConstants.BASIC_PREFIX + "\" prefix")); } String base64EncodedCredentials = header.substring(AuthorizationConstants.BASIC_PREFIX.length()).trim(); String basicCredentials = null; try { basicCredentials = new String(BASE64_DECODER.decode(base64EncodedCredentials), StandardCharsets.UTF_8); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( String.format(INVALID_AUTH_MSG_FORMAT, "Malformed Base64 encoding: " + e.getMessage()), e); } int colon = basicCredentials.indexOf(":"); if (colon > 0 && colon < basicCredentials.length() - 1) { String name = basicCredentials.substring(0, colon); String password = basicCredentials.substring(colon + 1); return Optional.of(new UserNameAndPassword(name, password)); } throw new IllegalArgumentException( String.format(INVALID_AUTH_MSG_FORMAT, "Decoded credentials should be colon separated")); }
Source:
private static com.netflix.genie.proto.JobSpecification toProtoJobSpecification( final JobSpecification jobSpecification ) { final com.netflix.genie.proto.JobSpecification.Builder builder = com.netflix.genie.proto.JobSpecification.newBuilder(); builder.addAllCommandArgs(jobSpecification.getCommandArgs()); builder.setJob(toProtoExecutionResource(jobSpecification.getJob())); builder.setCluster(toProtoExecutionResource(jobSpecification.getCluster())); builder.setCommand(toProtoExecutionResource(jobSpecification.getCommand())); builder.addAllApplications( jobSpecification .getApplications() .stream() .map(JobServiceProtoConverter::toProtoExecutionResource) .collect(Collectors.toList()) ); builder.putAllEnvironmentVariables(jobSpecification.getEnvironmentVariables()); builder.setIsInteractive(jobSpecification.isInteractive()); builder.setJobDirectoryLocation(jobSpecification.getJobDirectoryLocation().getAbsolutePath()); builder.setArchiveLocation(jobSpecification.getArchiveLocation()); return builder.build(); }

Target:
private static com.netflix.genie.proto.JobSpecification toProtoJobSpecification( final JobSpecification jobSpecification ) { final com.netflix.genie.proto.JobSpecification.Builder builder = com.netflix.genie.proto.JobSpecification.newBuilder(); builder.addAllCommandArgs(jobSpecification.getCommandArgs()); builder.setJob(toProtoExecutionResource(jobSpecification.getJob())); builder.setCluster(toProtoExecutionResource(jobSpecification.getCluster())); builder.setCommand(toProtoExecutionResource(jobSpecification.getCommand())); builder.addAllApplications( jobSpecification .getApplications() .stream() .map(JobServiceProtoConverter::toProtoExecutionResource) .collect(Collectors.toList()) ); builder.putAllEnvironmentVariables(jobSpecification.getEnvironmentVariables()); builder.setIsInteractive(jobSpecification.isInteractive()); builder.setJobDirectoryLocation(jobSpecification.getJobDirectoryLocation().getAbsolutePath()); jobSpecification.getArchiveLocation().ifPresent( archiveLocation -> builder.setArchiveLocation(archiveLocation) ); return builder.build(); }
Source:
private boolean setupNoUpstreamNotification() { final Resources res = getResourcesForSubId(mContext, mActiveDataSubId); final int timeToShowUpstreamNotification = res.getInteger(R.integer.time_to_show_no_upstream_after_no_backhaul); if (timeToShowUpstreamNotification <= 0) return NO_NOTIFY; final TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); final String mccmnc = tm.getSimOperator(); final String gid1 = tm.getGroupIdLevel1(); if (mccmnc.equals("20404") && !gid1.equals("BAE0000000000000")) return NO_NOTIFY; mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_SHOW_NO_UPSTREAM), timeToShowUpstreamNotification); return NOTIFY_DONE; }

Target:
private boolean setupNoUpstreamNotification() { final Resources res = getResourcesForSubId(mContext, mActiveDataSubId); final int delayToShowUpstreamNotification = res.getInteger(R.integer.delay_to_show_no_upstream_after_no_backhaul); if (delayToShowUpstreamNotification <= 0) return NO_NOTIFY; final TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); final String mccmnc = tm.getSimOperator(); final String gid1 = tm.getGroupIdLevel1(); if (mccmnc.equals("20404") && !gid1.equals("BAE0000000000000")) return NO_NOTIFY; getHandler().sendMessageDelayed(getHandler().obtainMessage(EVENT_SHOW_NO_UPSTREAM), delayToShowUpstreamNotification); return NOTIFY_DONE; }
Source:
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { this.viewer = (TreeViewer) viewer; this.info = (LSPDocumentInfo) newInput; info.getDocument().addDocumentListener(this); resource = LSPEclipseUtils.findResourceFor(info.getFileUri().toString()); resource.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); refreshTreeContentFromLS(); preferences = InstanceScope.INSTANCE.getNode(outlineID+'.'+info.getFileUri()); IEditorPart editorPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor(); if(editorPart instanceof AbstractTextEditor) { AbstractTextEditor editor = (AbstractTextEditor)editorPart; ((StyledText)editor.getAdapter(Control.class)).addCaretListener(selectByEditorCaretListener); } }

Target:
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { this.viewer = (TreeViewer) viewer; this.info = (LSPDocumentInfo) newInput; info.getDocument().addDocumentListener(this); resource = LSPEclipseUtils.findResourceFor(info.getFileUri().toString()); resource.getWorkspace().addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); refreshTreeContentFromLS(); }
Source:
private String getMergeResolveMessage(Repository mergeRepository) { File mergeMsg = new File(mergeRepository.getDirectory(), Constants.MERGE_MSG); FileReader reader; try { reader = new FileReader(mergeMsg); BufferedReader br = new BufferedReader(reader); try { StringBuilder message = new StringBuilder(); String s; String newLine = newLine(); while ((s = br.readLine()) != null) { message.append(s).append(newLine); } return message.toString(); } catch (IOException e) { throw new IllegalStateException(e); } finally { try { br.close(); } catch (IOException e) { } } } catch (FileNotFoundException e) { throw new IllegalStateException(e); } }

Target:
private String getMergeResolveMessage(Repository mergeRepository) { File mergeMsg = new File(mergeRepository.getDirectory(), Constants.MERGE_MSG); FileReader reader; try { reader = new FileReader(mergeMsg); BufferedReader br = new BufferedReader(reader); try { StringBuilder message = new StringBuilder(); String s; String newLine = newLine(); while ((s = br.readLine()) != null) message.append(s).append(newLine); return message.toString(); } catch (IOException e) { throw new IllegalStateException(e); } finally { try { br.close(); } catch (IOException e) { } } } catch (FileNotFoundException e) { throw new IllegalStateException(e); } }
Source:
Hit<String> bestMatchingSynonym(OntologyTerm ontologyTerm, Set<String> searchTerms) { Optional<Hit<String>> bestSynonym = ontologyTerm .getSynonyms() .stream() .map(synonym -> Hit.create(synonym, distanceFrom(synonym, searchTerms))) .max(Comparator.naturalOrder()); if (bestSynonym.isPresent()) { return bestSynonym.get(); } else { throw new IllegalStateException("ontologyTerm.getSynonyms() shouldn't return an empty list"); } }

Target:
Hit<String> bestMatchingSynonym(OntologyTerm ontologyTerm, Set<String> searchTerms) { Optional<Hit<String>> bestSynonym = ontologyTerm .getSynonyms() .stream() .map(synonym -> Hit.create(synonym, distanceFrom(synonym, searchTerms))) .max(Comparator.naturalOrder()); return bestSynonym.orElseThrow( () -> new IllegalStateException("ontologyTerm.getSynonyms() shouldn't return an empty list")); }
Source:
public Object deserialize(Object object) { if (object instanceof byte[]) { return new AdaptiveCounting((byte[])object); } else if (object instanceof ByteBuffer) { ByteBuffer buf = (ByteBuffer)object; int size = buf.capacity(); byte[] bytes = new byte[size]; buf.get(bytes); return new AdaptiveCounting(bytes); } return object; }

Target:
public Object deserialize(Object object) { if (object instanceof byte[]) { return new AdaptiveCounting((byte[])object); } else if (object instanceof ByteBuffer) { ByteBuffer buf = (ByteBuffer)object; int size = buf.remaining(); byte[] bytes = new byte[size]; buf.get(bytes); return new AdaptiveCounting(bytes); } return object; }
Source:
protected LinkedList<TransactionOutput> calculateAllSpendCandidatesFromUTXOProvider(boolean excludeImmatureCoinbases){ LinkedList<TransactionOutput> candidates = Lists.newLinkedList(); try { int chainHeight = utxoProvider.getChainHeadHeight(); for (StoredTransactionOutput output : getStoredOutputsFromUTXOProvider()) { boolean coinbase = output.isCoinbase(); int depth = chainHeight - output.getHeight(); if (!excludeImmatureCoinbases || !coinbase || depth >= params.getSpendableCoinbaseDepth()) { candidates.add(new FreeStandingTransactionOutput(params, output, chainHeight)); } } } catch (UTXOProviderException e) { throw new RuntimeException("UTXO provider error", e); } for (Transaction tx : Iterables.concat(pending.values())) { for(TransactionInput input : tx.getInputs()) { if (input.getConnectedOutput().isMine(this)) { candidates.remove(input.getConnectedOutput()); } } if (!excludeImmatureCoinbases || tx.isMature()) { for (TransactionOutput output : tx.getOutputs()) { if (output.isAvailableForSpending() && output.isMine(this)) { candidates.add(output); } } } } return candidates; }

Target:
protected LinkedList<TransactionOutput> calculateAllSpendCandidatesFromUTXOProvider(boolean excludeImmatureCoinbases){ checkState(lock.isHeldByCurrentThread()); LinkedList<TransactionOutput> candidates = Lists.newLinkedList(); try { int chainHeight = vUTXOProvider.getChainHeadHeight(); for (UTXO output : getStoredOutputsFromUTXOProvider()) { boolean coinbase = output.isCoinbase(); int depth = chainHeight - output.getHeight() + 1; if (!excludeImmatureCoinbases || !coinbase || depth >= params.getSpendableCoinbaseDepth()) { candidates.add(new FreeStandingTransactionOutput(params, output, chainHeight)); } } } catch (UTXOProviderException e) { throw new RuntimeException("UTXO provider error", e); } for (Transaction tx : Iterables.concat(pending.values())) { for(TransactionInput input : tx.getInputs()) { if (input.getConnectedOutput().isMine(this)) { candidates.remove(input.getConnectedOutput()); } } if (!excludeImmatureCoinbases || tx.isMature()) { for (TransactionOutput output : tx.getOutputs()) { if (output.isAvailableForSpending() && output.isMine(this)) { candidates.add(output); } } } } return candidates; }
Source:
public void setNextRingTime(final String deviceId, final RingTime ringTime){ final HashMap<String, AttributeValue> items = new HashMap<String, AttributeValue>(); items.put(MORPHEUS_ID_ATTRIBUTE_NAME, new AttributeValue().withS(deviceId)); final ObjectMapper mapper = new ObjectMapper(); try { final String ringTimeJSON = mapper.writeValueAsString(ringTime); items.put(CREATED_AT_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(DateTime.now().getMillis()))); items.put(RING_TIME_ATTRIBUTE_NAME, new AttributeValue().withS(ringTimeJSON)); final PutItemRequest putItemRequest = new PutItemRequest(this.tableName, items); final PutItemResult result = this.dynamoDBClient.putItem(putItemRequest); } catch (JsonProcessingException ex) { LOGGER.error("Set ring time for device failed, error: {}", deviceId, ex.getMessage()); } }

Target:
public void setNextRingTime(final String deviceId, final RingTime ringTime){ this.setNextRingTime(deviceId, ringTime, DateTime.now()); }
Source:
private PeriodicNotificationClient getPeriodicNotificationClient(String topic, String brokers) throws MalformedQueryException { return new KafkaNotificationRegistrationClient(topic, getProducer(brokers)); }

Target:
private static PeriodicNotificationClient getPeriodicNotificationClient(String topic, String brokers) throws MalformedQueryException { return new KafkaNotificationRegistrationClient(topic, createProducer(brokers)); }
Source:
public boolean isComputeResourceExists(String resourceId) throws AppCatalogException { if(isExists(resourceId)){ ComputeResourceDescription computeResourceDescription = getComputeResource(resourceId); if(computeResourceDescription.isDeleted()){ return false; } else{ return true; } } return true; }

Target:
public boolean isComputeResourceExists(String resourceId) throws AppCatalogException { if(isExists(resourceId)){ ComputeResourceDescription computeResourceDescription = getComputeResource(resourceId); if(computeResourceDescription.isDeleted()){ return false; } else{ return true; } } return false; }
Source:
public void call(final Subscriber<? super T> subscriber) { source.subscribe(new Subscriber<T>(subscriber) { private int currentIndex = 0; @Override public void onNext(T value) { if (currentIndex == index) { subscriber.onNext(value); subscriber.onCompleted(); } currentIndex++; } @Override public void onError(Throwable e) { subscriber.onError(e); } @Override public void onCompleted() { if (currentIndex <= index) { if (hasDefault) { subscriber.onNext(defaultValue); subscriber.onCompleted(); } else { subscriber.onError(new IndexOutOfBoundsException(index + " is out of bounds")); } } } }); }

Target:
public Subscriber<? super T> call(final Subscriber<? super T> subscriber) { return new Subscriber<T>(subscriber) { private int currentIndex = 0; @Override public void onNext(T value) { if (currentIndex == index) { subscriber.onNext(value); subscriber.onCompleted(); } currentIndex++; } @Override public void onError(Throwable e) { subscriber.onError(e); } @Override public void onCompleted() { if (currentIndex <= index) { if (hasDefault) { subscriber.onNext(defaultValue); subscriber.onCompleted(); } else { subscriber.onError(new IndexOutOfBoundsException(index + " is out of bounds")); } } } }; }
Source:
public void writeJSON(Patient patient, JSONObject json, Collection<String> selectedFieldNames) { if (selectedFieldNames != null) { boolean hasAny = false; for (String selectedFieldName : selectedFieldNames) { if (StringUtils.startsWithIgnoreCase(selectedFieldName, this.getName())) { hasAny = true; break; } } if (!hasAny) { return; } } PatientData<Integer> data = patient.getData(getName()); if (data == null || !data.isNamed()) { return; } Iterator<Entry<String, Integer>> iterator = data.dictionaryIterator(); if (!iterator.hasNext()) { return; } JSONObject container = json.getJSONObject(DATA_NAME); if (container == null || container.isNullObject()) { json.put(DATA_NAME, new JSONObject()); container = json.getJSONObject(DATA_NAME); } while (iterator.hasNext()) { Entry<String, Integer> item = iterator.next(); if (selectedFieldNames == null || selectedFieldNames.contains(item.getKey())) { container.put(item.getKey(), item.getValue()); } } }

Target:
public void writeJSON(Patient patient, JSONObject json, Collection<String> selectedFieldNames) { if (selectedFieldNames != null && !hasAnySelected(selectedFieldNames)) { return; } PatientData<Integer> data = patient.getData(getName()); if (data == null || !data.isNamed()) { return; } Iterator<Entry<String, Integer>> iterator = data.dictionaryIterator(); if (!iterator.hasNext()) { return; } JSONObject container = json.getJSONObject(DATA_NAME); if (container == null || container.isNullObject()) { json.put(DATA_NAME, new JSONObject()); container = json.getJSONObject(DATA_NAME); } while (iterator.hasNext()) { Entry<String, Integer> item = iterator.next(); container.put(item.getKey(), item.getValue()); } }