auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void handleIssue(int severity, String message, Throwable throwable, boolean show) { IStatus status = new Status(severity, getPluginId(), message, throwable); int style = StatusManager.LOG; if (show) style |= StatusManager.SHOW; StatusManager.getManager().handle(status, style); }

Target:
public static void handleIssue(int severity, String message, Throwable throwable, boolean show) { IStatus status = new Status(severity, getPluginId(), message, throwable); int style = StatusManager.LOG; if (show) { style |= StatusManager.SHOW; } StatusManager.getManager().handle(status, style); }
Source:
public void shouldSerializeCalendarLikeISO8601() { List<JsonSerializer> adapters = new ArrayList<JsonSerializer>(); adapters.add(new br.com.caelum.vraptor.serialization.iso8601.gson.CalendarISO8601Serializer(new ISO8601Util())); GsonJSONSerialization serialization = new GsonJSONSerialization(response, extractor, initializer, createBuilder(adapters), serializee); Client c = new Client("Rafael"); c.included = new GregorianCalendar(2013, 6, 27, 9, 52, 38); c.included.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo")); serialization.from(c).serialize(); String result = result(); String expectedResult = "{\"client\":{\"name\":\"Rafael\",\"included\":\"2013-07-27T09:52:38.000-0300\"}}"; assertThat(result, is(equalTo(expectedResult))); }

Target:
public void shouldSerializeCalendarLikeISO8601() { GsonJSONSerialization serialization = serializationWithAdapter(new CalendarISO8601Serializer(new ISO8601Util())); Client c = new Client("Rafael"); c.included = new GregorianCalendar(2013, 6, 27, 9, 52, 38); c.included.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo")); serialization.from(c).serialize(); String result = result(); String expectedResult = "{\"client\":{\"name\":\"Rafael\",\"included\":\"2013-07-27T09:52:38.000-0300\"}}"; assertThat(result, is(equalTo(expectedResult))); }
Source:
public BlobProperties getBlobProperties(String blobIdString) throws CoordinatorException { try { logger.trace("getBlobProperties. " + blobIdString); long startTimeInMs = System.currentTimeMillis(); BlobId blobId = getBlobIdFromString(blobIdString); GetBlobPropertiesOperation gbpo = new GetBlobPropertiesOperation(datacenterName, connectionPool, requesterPool, getOperationContext(), blobId, operationTimeoutMs, clusterMap); gbpo.execute(); coordinatorMetrics.getBlobPropertiesOperationRate.mark(); coordinatorMetrics.getBlobPropertiesOperationLatencyInMs.update(System.currentTimeMillis() - startTimeInMs); return gbpo.getBlobProperties(); } catch (CoordinatorException e) { logger.error("getBlobProperties re-throwing CoordinatorException" + e); coordinatorMetrics.countError(CoordinatorMetrics.CoordinatorOperationType.GetBlobProperties, e.getErrorCode()); throw e; } }

Target:
public BlobProperties getBlobProperties(String blobIdString) throws CoordinatorException { try { logger.trace("getBlobProperties. " + blobIdString); long startTimeInMs = System.currentTimeMillis(); BlobId blobId = getBlobIdFromString(blobIdString); GetBlobPropertiesOperation gbpo = new GetBlobPropertiesOperation(datacenterName, connectionPool, requesterPool, getOperationContext(), blobId, operationTimeoutMs, clusterMap); gbpo.execute(); coordinatorMetrics.getBlobPropertiesOperationRate.mark(); coordinatorMetrics.getBlobPropertiesOperationLatencyInMs.update(System.currentTimeMillis() - startTimeInMs); return gbpo.getBlobProperties(); } catch (CoordinatorException e) { logger.trace("getBlobProperties re-throwing CoordinatorException", e); coordinatorMetrics.countError(CoordinatorMetrics.CoordinatorOperationType.GetBlobProperties, e.getErrorCode()); throw e; } }
Source:
void handleRevocation(final Collection<TopicPartition> revokedPartitions) { final Set<TaskId> revokedTasks = new HashSet<>(); final Set<TopicPartition> remainingPartitions = new HashSet<>(revokedPartitions); for (final Task task : tasks.values()) { for (final TopicPartition topicPartition : task.inputPartitions()) { if (remainingPartitions.contains(topicPartition)) { revokedTasks.add(task.id()); remainingPartitions.remove(topicPartition); } } } if (!remainingPartitions.isEmpty()) { throw new IllegalStateException("Some revoked partitions that do not belong " + "to any tasks remain: " + remainingPartitions); } for (final TaskId taskId : revokedTasks) { final Task task = tasks.get(taskId); task.suspend(); } }

Target:
void handleRevocation(final Collection<TopicPartition> revokedPartitions) { final Set<TaskId> revokedTasks = new HashSet<>(); final Set<TopicPartition> remainingPartitions = new HashSet<>(revokedPartitions); for (final Task task : tasks.values()) { if (remainingPartitions.containsAll(task.inputPartitions())) { revokedTasks.add(task.id()); } remainingPartitions.removeAll(task.inputPartitions()); } if (!remainingPartitions.isEmpty()) { throw new IllegalStateException("Some revoked partitions that do not belong " + "to any tasks remain: " + remainingPartitions); } for (final TaskId taskId : revokedTasks) { final Task task = tasks.get(taskId); task.suspend(); } }
Source:
public void PacketExceptionTest() throws BadPacketException, IOException, BadPcapFileException { PcapTestTrace trace = PcapTestTrace.MOSTLY_TCP; assumeTrue(trace.exists()); PcapFile dummy = trace.getTrace(); ByteBuffer packet = fEthernetPacket; if (packet != null) { new EthernetIIPacket(dummy, null, packet); } fail("PacketExceptionTest has failed!"); }

Target:
public void PacketExceptionTest() throws BadPacketException, IOException, BadPcapFileException { PcapTestTrace trace = PcapTestTrace.MOSTLY_TCP; assumeTrue(trace.exists()); try (PcapFile dummy = trace.getTrace();) { ByteBuffer packet = fEthernetPacket; if (packet != null) { new EthernetIIPacket(dummy, null, packet); } fail("PacketExceptionTest has failed!"); } }
Source:
public void beforeClass(@Optional Boolean usingEncryption, @Optional String testType) throws IOException { ConfigContext config = new IntegrationTestConfigContext(usingEncryption); String testName = this.getClass().getSimpleName(); mantaClient = new MantaClient(config); if(testType != null && testType.equals("buckets")) { if(IntegrationTestHelper.verifyBucketsSupport(config, mantaClient)) { bucketsEnabled = true; bucketsTestPathPrefix = IntegrationTestHelper.setupBucketsPath(config, testName); testPathPrefix = IntegrationTestHelper.setupBucketObjectBasePath(bucketsTestPathPrefix); } else { throw new SkipException("Buckets operations not supported by the server"); } } else { testPathPrefix = IntegrationTestConfigContext.generateBasePath(config, testName); mantaClient.putDirectory(testPathPrefix, true); } }

Target:
public void beforeClass(@Optional Boolean usingEncryption, @Optional String testType) throws IOException { ConfigContext config = new IntegrationTestConfigContext(usingEncryption); String testName = this.getClass().getSimpleName(); mantaClient = new MantaClient(config); testPathPrefix = IntegrationTestHelper.setupTestPath(config, mantaClient, testName, testType); IntegrationTestHelper.createTestBucketOrDirectory(mantaClient, testPathPrefix, testType); }
Source:
private CompletionStage<RestResponse> createScriptTask(RestRequest request) { NettyRestResponse.Builder builder = new NettyRestResponse.Builder(); String taskName = request.variables().get("taskName"); if (taskName == null || taskName.isEmpty() || taskName.startsWith("@@")) { builder.status(HttpResponseStatus.BAD_REQUEST).entity("Task name must be provided and cannot start with '@@'"); } EmbeddedCacheManager cacheManager = invocationHelper.getRestCacheManager().getInstance(); ScriptingManager scriptingManager = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(ScriptingManager.class); ContentSource contents = request.contents(); byte[] bytes = contents.rawContent(); MediaType sourceType = request.contentType() == null ? APPLICATION_JAVASCRIPT : request.contentType(); String script = StandardConversions.convertTextToObject(bytes, sourceType); scriptingManager.addScript(taskName, script); return completedFuture(builder.build()); }

Target:
private CompletionStage<RestResponse> createScriptTask(RestRequest request) { String taskName = request.variables().get("taskName"); EmbeddedCacheManager cacheManager = invocationHelper.getRestCacheManager().getInstance(); ScriptingManager scriptingManager = SecurityActions.getGlobalComponentRegistry(cacheManager).getComponent(ScriptingManager.class); NettyRestResponse.Builder builder = new NettyRestResponse.Builder(); ContentSource contents = request.contents(); byte[] bytes = contents.rawContent(); MediaType sourceType = request.contentType() == null ? APPLICATION_JAVASCRIPT : request.contentType(); String script = StandardConversions.convertTextToObject(bytes, sourceType); scriptingManager.addScript(taskName, script); return completedFuture(builder.build()); }
Source:
public void testWithDisabledInstancesLimit() throws Exception { MaintenanceSignal maintenanceSignal = _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); Assert.assertNull(maintenanceSignal); checkForRebalanceError(false); HelixAdmin admin = new ZKHelixAdmin(_gZkClient); int i; for (i = 2; i < 2 + _maxOfflineInstancesAllowed; i++) { String instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, false); } boolean result = TestHelper.verify(() -> { MaintenanceSignal ms = _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); return ms == null; }, TestHelper.WAIT_DURATION); Assert.assertTrue(result); String instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, false); ZkHelixClusterVerifier clusterVerifier1 = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .build(); Assert.assertTrue(clusterVerifier1.verifyByPolling()); result = TestHelper.verify(() -> { MaintenanceSignal ms =_dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); return ms != null && ms.getReason() != null; }, TestHelper.WAIT_DURATION); checkForRebalanceError(true); for (i = 2; i < 2 + _maxOfflineInstancesAllowed + 1; i++) { instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, true); } admin.enableMaintenanceMode(CLUSTER_NAME, false); }

Target:
public void testWithDisabledInstancesLimit() throws Exception { MaintenanceSignal maintenanceSignal = _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); Assert.assertNull(maintenanceSignal); checkForRebalanceError(false); HelixAdmin admin = new ZKHelixAdmin(_gZkClient); int i; for (i = 2; i < 2 + _maxOfflineInstancesAllowed; i++) { String instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, false); } boolean result = TestHelper.verify(() -> { MaintenanceSignal ms = _dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); return ms == null; }, TestHelper.WAIT_DURATION); Assert.assertTrue(result); String instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, false); ZkHelixClusterVerifier clusterVerifier = new BestPossibleExternalViewVerifier.Builder(CLUSTER_NAME).setZkClient(_gZkClient) .setWaitTillVerify(TestHelper.DEFAULT_REBALANCE_PROCESSING_WAIT_TIME) .build(); Assert.assertTrue(clusterVerifier.verifyByPolling()); result = TestHelper.verify(() -> { MaintenanceSignal ms =_dataAccessor.getProperty(_dataAccessor.keyBuilder().maintenance()); return ms != null && ms.getReason() != null; }, TestHelper.WAIT_DURATION); Assert.assertTrue(result); checkForRebalanceError(true); for (i = 2; i < 2 + _maxOfflineInstancesAllowed + 1; i++) { instance = _participants.get(i).getInstanceName(); admin.enableInstance(CLUSTER_NAME, instance, true); } admin.enableMaintenanceMode(CLUSTER_NAME, false); Assert.assertTrue(clusterVerifier.verifyByPolling()); }
Source:
public RecordWriter<Long, SinkRecord> getRecordWriter(Configuration conf, String fileName, SinkRecord record) throws IOException{ DatumWriter<Object> datumWriter = new GenericDatumWriter<Object>(); final DataFileWriter<Object> writer = new DataFileWriter<Object>(datumWriter); Path path = new Path(fileName); Object value = AvroData.convertToAvro(record.getValue()); writer.create(((GenericRecord) value).getSchema(), path.getFileSystem(conf).create(path)); return new RecordWriter<Long, SinkRecord>(){ @Override public void write(Long key, SinkRecord record) throws IOException{ Object value = AvroData.convertToAvro(record.getValue()); writer.append(value); } @Override public void close() throws IOException{ writer.close(); } @Override public void flush() throws IOException{ writer.flush(); } }; }

Target:
public RecordWriter<Long, SinkRecord> getRecordWriter(Configuration conf, String fileName, SinkRecord record) throws IOException{ DatumWriter<Object> datumWriter = new GenericDatumWriter<Object>(); final DataFileWriter<Object> writer = new DataFileWriter<Object>(datumWriter); Path path = new Path(fileName); Schema schema = ((GenericRecord) record.getValue()).getSchema(); writer.create(AvroData.asAvroSchema(schema), path.getFileSystem(conf).create(path)); return new RecordWriter<Long, SinkRecord>(){ @Override public void write(Long key, SinkRecord record) throws IOException{ Object value = AvroData.convertToAvro(record.getValue()); writer.append(value); } @Override public void close() throws IOException{ writer.close(); } }; }
Source:
public VdcActionParametersBase getParameters(VM incoming, org.ovirt.engine.core.common.businessentities.VM entity) { VmStatic updated = getMapper(modelType, VmStatic.class).map(incoming, entity.getStaticData()); updated.setUsbPolicy(VmMapper.getUsbPolicyOnUpdate(incoming.getUsb(), entity.getUsbPolicy(), lookupCluster(updated.getVdsGroupId()))); VmManagementParametersBase params = new VmManagementParametersBase(updated); if (incoming.isSetPayloads()) { if (incoming.isSetPayloads() && incoming.getPayloads().isSetPayload()) { params.setVmPayload(parent.getPayload(incoming)); } else { params.setClearPayload(true); } } if (incoming.isSetMemoryPolicy() && incoming.getMemoryPolicy().isSetBallooning()) { params.setBalloonEnabled(incoming.getMemoryPolicy().isBallooning()); } if (incoming.isSetConsoleDeviceEnabled()) { params.setConsoleEnabled(incoming.isConsoleDeviceEnabled()); } return params; }

Target:
public VdcActionParametersBase getParameters(VM incoming, org.ovirt.engine.core.common.businessentities.VM entity) { VmStatic updated = getMapper(modelType, VmStatic.class).map(incoming, entity.getStaticData()); updated.setUsbPolicy(VmMapper.getUsbPolicyOnUpdate(incoming.getUsb(), entity.getUsbPolicy(), lookupCluster(updated.getVdsGroupId()))); VmManagementParametersBase params = new VmManagementParametersBase(updated); if (incoming.isSetPayloads()) { if (incoming.isSetPayloads() && incoming.getPayloads().isSetPayload()) { params.setVmPayload(parent.getPayload(incoming)); } else { params.setClearPayload(true); } } if (incoming.isSetMemoryPolicy() && incoming.getMemoryPolicy().isSetBallooning()) { params.setBalloonEnabled(incoming.getMemoryPolicy().isBallooning()); } if (incoming.isSetConsole() && incoming.getConsole().isSetEnabled()) { params.setConsoleEnabled(incoming.getConsole().isEnabled()); } return params; }
Source:
public static ViewerSorter createProjectTreeSorter(final ILabelProvider labelProvider) { final ProjectViewerComparator projectComparator = new ProjectViewerComparator(labelProvider); return new ViewerSorter() { @SuppressWarnings("unchecked") @Override public int compare(Viewer viewer, Object e1, Object e2) { if(e1 instanceof ObservableTreeItem && e2 instanceof ObservableTreeItem) { Object o1 = ((ObservableTreeItem) e1).getModel(); Object o2 = ((ObservableTreeItem) e2).getModel(); if(o1 instanceof IProject && o2 instanceof IProject) { return projectComparator.compare(viewer, e1, e2); } else if(labelProvider != null) { return labelProvider.getText(o1).compareTo(labelProvider.getText(o2)); } else if(o1 instanceof IResource && o2 instanceof IResource) { String name1 = ((IResource) o1).getName(); String name2 = ((IResource) o2).getName(); return getComparator().compare(name1, name2); } } return super.compare(viewer, e1, e2); } }; }

Target:
public static ViewerComparator createProjectTreeSorter(final ILabelProvider labelProvider) { final ProjectViewerComparator projectComparator = new ProjectViewerComparator(labelProvider); return new ViewerComparator() { @SuppressWarnings("unchecked") @Override public int compare(Viewer viewer, Object e1, Object e2) { if(e1 instanceof ObservableTreeItem && e2 instanceof ObservableTreeItem) { Object o1 = ((ObservableTreeItem) e1).getModel(); Object o2 = ((ObservableTreeItem) e2).getModel(); if(o1 instanceof IProject && o2 instanceof IProject) { return projectComparator.compare(viewer, o1, o2); } else if(labelProvider != null) { return labelProvider.getText(o1).compareTo(labelProvider.getText(o2)); } else if(o1 instanceof IResource && o2 instanceof IResource) { String name1 = ((IResource) o1).getName(); String name2 = ((IResource) o2).getName(); return getComparator().compare(name1, name2); } } return super.compare(viewer, e1, e2); } }; }
Source:
public void testResourceTextSearch() throws InterruptedException { Observation obs1 = new Observation(); obs1.getCode().setText("Systolic Blood Pressure"); obs1.setStatus(Observation.ObservationStatus.FINAL); obs1.setValue(new Quantity(123)); obs1.getNoteFirstRep().setText("obs1"); IIdType id1 = myObservationDao.create(obs1, mySrd).getId().toUnqualifiedVersionless(); Observation obs2 = new Observation(); obs2.getCode().setText("Diastolic Blood Pressure"); obs2.setStatus(Observation.ObservationStatus.FINAL); obs2.setValue(new Quantity(81)); IIdType id2 = myObservationDao.create(obs2, mySrd).getId().toUnqualifiedVersionless(); waitForElasticToCatchUp(); SearchParameterMap map; map = new SearchParameterMap(); map.add(ca.uhn.fhir.rest.api.Constants.PARAM_CONTENT, new StringParam("systolic")); assertThat(toUnqualifiedVersionlessIdValues(myObservationDao.search(map)), containsInAnyOrder(toValues(id1))); map = new SearchParameterMap(); map.add(Constants.PARAM_CONTENT, new StringParam("blood")); assertThat(toUnqualifiedVersionlessIdValues(myObservationDao.search(map)), containsInAnyOrder(toValues(id1, id2))); }

Target:
public void testResourceTextSearch() throws InterruptedException { Observation obs1 = new Observation(); obs1.getCode().setText("Systolic Blood Pressure"); obs1.setStatus(Observation.ObservationStatus.FINAL); obs1.setValue(new Quantity(123)); obs1.getNoteFirstRep().setText("obs1"); IIdType id1 = myObservationDao.create(obs1, mySrd).getId().toUnqualifiedVersionless(); Observation obs2 = new Observation(); obs2.getCode().setText("Diastolic Blood Pressure"); obs2.setStatus(Observation.ObservationStatus.FINAL); obs2.setValue(new Quantity(81)); IIdType id2 = myObservationDao.create(obs2, mySrd).getId().toUnqualifiedVersionless(); SearchParameterMap map; map = new SearchParameterMap(); map.add(ca.uhn.fhir.rest.api.Constants.PARAM_CONTENT, new StringParam("systolic")); assertThat(toUnqualifiedVersionlessIdValues(myObservationDao.search(map)), containsInAnyOrder(toValues(id1))); map = new SearchParameterMap(); map.add(Constants.PARAM_CONTENT, new StringParam("blood")); assertThat(toUnqualifiedVersionlessIdValues(myObservationDao.search(map)), containsInAnyOrder(toValues(id1, id2))); }
Source:
protected void resetInvoiceColumn(ResultRow row, Column invoiceColumn) { String link = parseHrefLinkFromAnchorTag(row.getActionUrls()); AnchorHtmlData anchorHtmlData = new AnchorHtmlData(link, KFSConstants.SEARCH_METHOD, VIEW_INVOICES_LINK_VALUE); anchorHtmlData.setTarget(KFSConstants.NEW_WINDOW_URL_TARGET); invoiceColumn.setColumnAnchor(anchorHtmlData); invoiceColumn.setPropertyValue(VIEW_INVOICES_LINK_VALUE); }

Target:
protected void resetInvoiceColumn(ResultRow row, Column invoiceColumn) { String hrefLink = parseHrefLinkFromAnchorTag(row.getActionUrls()); if (StringUtils.isNotBlank(hrefLink)) { AnchorHtmlData anchorHtmlData = new AnchorHtmlData(hrefLink, KFSConstants.SEARCH_METHOD, VIEW_INVOICES_LINK_VALUE); anchorHtmlData.setTarget(KFSConstants.NEW_WINDOW_URL_TARGET); invoiceColumn.setColumnAnchor(anchorHtmlData); invoiceColumn.setPropertyValue(VIEW_INVOICES_LINK_VALUE); } }
Source:
public static BillingInfo createRandomBillingInfo(final int seed) { final BillingInfo info = new BillingInfo(); info.setAccount(createRandomAccount(seed)); info.setFirstName(randomAlphaNumericString(5, seed)); info.setLastName(randomAlphaNumericString(6, seed)); info.setCompany(randomAlphaNumericString(10, seed)); info.setAddress1(randomAlphaNumericString(10, seed)); info.setAddress2(randomAlphaNumericString(10, seed)); info.setCity(randomAlphaNumericString(10, seed)); info.setState("CA"); info.setZip("94110"); info.setCountry("US"); info.setPhone(randomInteger(8, seed)); info.setVatNumber(randomNumericString(8, seed)); info.setYear(createTestCCYear()); info.setMonth(createTestCCMonth()); info.setNumber(createTestCCNumber()); info.setVerificationValue(createTestCCVerificationNumber()); info.setGatewayToken(randomAlphaNumericString(10, seed)); info.setGatewayCode(randomAlphaNumericString(10, seed)); return info; }

Target:
public static BillingInfo createRandomBillingInfo(final int seed) { final BillingInfo info = new BillingInfo(); info.setAccount(createRandomAccount(seed)); info.setFirstName(randomAlphaNumericString(5, seed)); info.setLastName(randomAlphaNumericString(6, seed)); info.setCompany(randomAlphaNumericString(10, seed)); info.setAddress1(randomAlphaNumericString(10, seed)); info.setAddress2(randomAlphaNumericString(10, seed)); info.setCity(randomAlphaNumericString(10, seed)); info.setState("CA"); info.setZip("94110"); info.setCountry("US"); info.setPhone(randomInteger(8, seed)); info.setVatNumber(randomNumericString(8, seed)); info.setYear(createTestCCYear()); info.setMonth(createTestCCMonth()); info.setNumber(createTestCCNumber()); info.setVerificationValue(createTestCCVerificationNumber()); return info; }
Source:
public List<OnmsNode> findNodeWithMetaData(final String context, final String key, final String value) { return getHibernateTemplate().execute(session -> (List<OnmsNode>) session.createSQLQuery("SELECT n.nodeid FROM node n, node_metadata m WHERE m.id = n.nodeid AND context = '" + StringEscapeUtils.escapeSql(context) + "' AND key = '" + StringEscapeUtils.escapeSql(key) + "' AND value = '" + StringEscapeUtils.escapeSql(value) + "'") .setResultTransformer(new ResultTransformer() { @Override public Object transformTuple(Object[] tuple, String[] aliases) { return get((Integer) tuple[0]); } @SuppressWarnings("rawtypes") @Override public List transformList(List collection) { return collection; } }).list()); }

Target:
public List<OnmsNode> findNodeWithMetaData(final String context, final String key, final String value) { return getHibernateTemplate().execute(session -> (List<OnmsNode>) session.createSQLQuery("SELECT n.nodeid FROM node n, node_metadata m WHERE m.id = n.nodeid AND context = :context AND key = :key AND value = :value ORDER BY n.nodeid") .setString("context", context) .setString("key", key) .setString("value", value) .setResultTransformer(new ResultTransformer() { @Override public Object transformTuple(Object[] tuple, String[] aliases) { return get((Integer) tuple[0]); } @SuppressWarnings("rawtypes") @Override public List transformList(List collection) { return collection; } }).list()); }
Source:
public String getOpenAPIDefinition(Identifier apiId) throws APIManagementException { String apiTenantDomain = getTenantDomain(apiId); String swaggerDoc = null; boolean tenantFlowStarted = false; try { Registry registryType; if (this.tenantDomain == null || isTenantDomainNotMatching(apiTenantDomain)) { startTenantFlow(apiTenantDomain); tenantFlowStarted = true; int tenantId = getTenantManager().getTenantId( apiTenantDomain); registryType = getRegistryService().getGovernanceUserRegistry( CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId); } else { registryType = registry; } swaggerDoc = OASParserUtil.getAPIDefinition(apiId, registryType); } catch (org.wso2.carbon.user.api.UserStoreException e) { String msg = "Failed to get swagger documentation of API : " + apiId; log.error(msg, e); throw new APIManagementException(msg, e); } catch (RegistryException e) { String msg = "Failed to get swagger documentation of API : " + apiId; log.error(msg, e); throw new APIManagementException(msg, e); } finally { if (tenantFlowStarted) { endTenantFlow(); } } return swaggerDoc; }

Target:
public String getOpenAPIDefinition(Identifier apiId) throws APIManagementException { String apiTenantDomain = getTenantDomain(apiId); String swaggerDoc = null; boolean tenantFlowStarted = false; try { Registry registryType; if (this.tenantDomain == null || isTenantDomainNotMatching(apiTenantDomain)) { if (apiTenantDomain != null) { startTenantFlow(apiTenantDomain); tenantFlowStarted = true; } int tenantId = getTenantManager().getTenantId( apiTenantDomain); registryType = getRegistryService().getGovernanceUserRegistry( CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId); } else { registryType = registry; } swaggerDoc = OASParserUtil.getAPIDefinition(apiId, registryType); } catch (org.wso2.carbon.user.api.UserStoreException e) { String msg = "Failed to get swagger documentation of API : " + apiId; log.error(msg, e); throw new APIManagementException(msg, e); } catch (RegistryException e) { String msg = "Failed to get swagger documentation of API : " + apiId; log.error(msg, e); throw new APIManagementException(msg, e); } finally { if (tenantFlowStarted) { endTenantFlow(); } } return swaggerDoc; }
Source:
public void addBase(final SamLocusIterator.RecordAndOffset recordAndOffset, final SamLocusAndReferenceIterator.SAMLocusAndReference locusAndRef) { if (recordAndOffset.getAlignmentType() == AbstractRecordAndOffset.AlignmentType.Match) { if (!SequenceUtil.isNoCall(recordAndOffset.getReadBase())) { nBases++; } } else if (recordAndOffset.getAlignmentType() == AbstractRecordAndOffset.AlignmentType.Insertion) { CigarElement cigarElement = ReadBaseStratification.getIndelElement(recordAndOffset); if (cigarElement != null) { nBases += cigarElement.getLength(); } } }

Target:
public void addBase(final SamLocusIterator.RecordAndOffset recordAndOffset, final SamLocusAndReferenceIterator.SAMLocusAndReference locusAndRef) { if (recordAndOffset.getAlignmentType() == AbstractRecordAndOffset.AlignmentType.Match) { if (!SequenceUtil.isNoCall(recordAndOffset.getReadBase())) { nBases++; } } else if (recordAndOffset.getAlignmentType() == AbstractRecordAndOffset.AlignmentType.Insertion) { final CigarElement cigarElement = ReadBaseStratification.getIndelElement(recordAndOffset); if (cigarElement != null) { nBases += cigarElement.getLength(); } } }
Source:
private void showRelatedPosts(@NonNull ReaderRelatedPostList relatedPosts, final boolean isGlobal) { int id = isGlobal ? R.id.related_posts_view_global : R.id.related_posts_view_local; ReaderRelatedPostsView relatedPostsView = isGlobal ? mLocalRelatedPostsView : mGlobalRelatedPostsView; relatedPostsView.showRelatedPosts(relatedPosts, mPost.getBlogName(), isGlobal); relatedPostsView.setOnRelatedPostClickListener(new ReaderRelatedPostsView.OnRelatedPostClickListener() { @Override public void onRelatedPostClick(View v, long siteId, long postId) { showRelatedPostDetail(siteId, postId, isGlobal); } }); if (relatedPostsView.getVisibility() != View.VISIBLE) { AniUtils.fadeIn(relatedPostsView, AniUtils.Duration.MEDIUM); } trackRelatedPostsIfShowing(); }

Target:
private void showRelatedPosts(@NonNull ReaderRelatedPostList relatedPosts, final boolean isGlobal) { ReaderRelatedPostsView relatedPostsView = isGlobal ? mGlobalRelatedPostsView : mLocalRelatedPostsView; relatedPostsView.showRelatedPosts(relatedPosts, mPost.getBlogName(), isGlobal); relatedPostsView.setOnRelatedPostClickListener(new ReaderRelatedPostsView.OnRelatedPostClickListener() { @Override public void onRelatedPostClick(View v, long siteId, long postId) { showRelatedPostDetail(siteId, postId, isGlobal); } }); if (relatedPostsView.getVisibility() != View.VISIBLE) { AniUtils.fadeIn(relatedPostsView, AniUtils.Duration.MEDIUM); } trackRelatedPostsIfShowing(); }
Source:
public int isApplicable(VElement vElement, ViewModelContext viewModelContext) { if (!VControl.class.isInstance(vElement)) { return NOT_APPLICABLE; } final VControl control = (VControl) vElement; final IObservableValue observableValue = Activator.getDefault().getEMFFormsDatabinding() .getObservableValue(control.getDomainModelReference(), viewModelContext.getDomainModel()); final EStructuralFeature feature = (EStructuralFeature) observableValue.getValueType(); final EObject eObject = (EObject) ((IObserving) observableValue).getObserved(); if (VIndexDomainModelReference.class.isInstance(eObject) && VIndexdmrPackage.eINSTANCE.getIndexDomainModelReference_TargetDMR() == feature) { return 6; } return NOT_APPLICABLE; }

Target:
public int isApplicable(VElement vElement, ViewModelContext viewModelContext) { if (!VControl.class.isInstance(vElement)) { return NOT_APPLICABLE; } final VControl control = (VControl) vElement; final IValueProperty valueProperty = Activator.getDefault().getEMFFormsDatabinding() .getValueProperty(control.getDomainModelReference()); final EStructuralFeature feature = (EStructuralFeature) valueProperty.getValueType(); if (VIndexdmrPackage.eINSTANCE.getIndexDomainModelReference_TargetDMR() == feature) { return 6; } return NOT_APPLICABLE; }
Source:
public void changePassword_shouldChangePasswordForGivenUserIfOldPasswordIsNullAndChangingUserHavePrivileges() throws Exception { executeDataSet(XML_FILENAME_WITH_DATA_FOR_CHANGE_PASSWORD_ACTION); final UserService userService = Context.getUserService(); User user6001 = userService.getUser(6001); String oldPassword = null; String newPassword = "newPasswordString123"; userService.changePassword(user6001, oldPassword, newPassword); Context.authenticate(user6001.getUsername(), newPassword); }

Target:
public void changePassword_shouldChangePasswordForGivenUserIfOldPasswordIsNullAndChangingUserHavePrivileges() throws Exception { executeDataSet(XML_FILENAME_WITH_DATA_FOR_CHANGE_PASSWORD_ACTION); final UserService userService = Context.getUserService(); User user6001 = userService.getUser(6001); String oldPassword = null; String newPassword = "newPasswordString123"; userService.changePassword(user6001, oldPassword, newPassword); User previouslyLogged = Context.getAuthenticatedUser(); Context.authenticate(user6001.getUsername(), newPassword); Context.logout(); Context.authenticate("admin", "test"); }
Source:
public HCatClient getHCatClient() { HCatClient hcatClient = null; int retryCount = 0; while (retryCount < numOfRetries) { try { hcatClient = hcatUtil.getHCatClient(); } catch (InterruptedException e) { retryCount++; e.printStackTrace(); } if (hcatClient != null) { break; } } return hcatClient; }

Target:
protected HCatClient getHCatClient() throws InterruptedException { return hcatUtil.getHCatClient(); }
Source:
public static Optional<InsightCard> processCaffeineAlarm(final Long accountId, final List<Integer> sleepTimeList) { if (sleepTimeList.isEmpty()) { LOGGER.debug("Got nothing in sleepTimeList"); return Optional.absent(); } else if (sleepTimeList.size() <= 2) { LOGGER.debug("Size of sleepTimeList is less than 2 for accountId {}", accountId); return Optional.absent(); } final DescriptiveStatistics stats = new DescriptiveStatistics(); for (final int sleepTime : sleepTimeList) { if (sleepTime < SIX_AM_MINUTES) { stats.addValue(sleepTime + InsightUtils.DAY_MINUTES); } else { stats.addValue(sleepTime); } } final Boolean passSafeGuards = checkSafeGuards(stats); if (!passSafeGuards) { return Optional.absent(); } final Double sleepAvgDouble = stats.getMean(); final int sleepAvg = (int) Math.round(sleepAvgDouble); final int recommendedCoffeeMinutesTime = getRecommendedCoffeeMinutesTime(sleepAvg); final String sleepTime = InsightUtils.timeConvert(sleepAvg); final String coffeeTime = InsightUtils.timeConvert(recommendedCoffeeMinutesTime); final Text text = CaffeineAlarmMsgEN.getCaffeineAlarmMessage(sleepTime, coffeeTime); return Optional.of(new InsightCard(accountId, text.title, text.message, InsightCard.Category.CAFFEINE, InsightCard.TimePeriod.MONTHLY, DateTime.now(DateTimeZone.UTC), InsightCard.InsightType.DEFAULT)); }

Target:
public static Optional<InsightCard> processCaffeineAlarm(final Long accountId, final List<Integer> sleepTimeList) { if (sleepTimeList.isEmpty()) { LOGGER.info("account_id={}-insight=caffeine_alarm-action=sleep_time_list_empty", accountId); return processCaffeineAlarmFallBack(accountId); } else if (sleepTimeList.size() <= 2) { LOGGER.info("account_id={}-insight=caffeine_alarm-action=sleep_time_list_too_small", accountId); return processCaffeineAlarmFallBack(accountId); } final DescriptiveStatistics stats = new DescriptiveStatistics(); for (final int sleepTime : sleepTimeList) { if (sleepTime < SIX_AM_MINUTES) { stats.addValue(sleepTime + InsightUtils.DAY_MINUTES); } else { stats.addValue(sleepTime); } } final Boolean passSafeGuards = checkSafeGuards(stats); if (!passSafeGuards) { LOGGER.info("insight=caffeine_alarm-account_id={}-action=fail_safe_guard"); return processCaffeineAlarmFallBack(accountId); } final Double sleepAvgDouble = stats.getMean(); final int sleepAvg = (int) Math.round(sleepAvgDouble); final int recommendedCoffeeMinutesTime = getRecommendedCoffeeMinutesTime(sleepAvg); final String sleepTime = InsightUtils.timeConvert(sleepAvg); final String coffeeTime = InsightUtils.timeConvert(recommendedCoffeeMinutesTime); final Text text = CaffeineAlarmMsgEN.getCaffeineAlarmMessage(sleepTime, coffeeTime); return Optional.of(new InsightCard(accountId, text.title, text.message, InsightCard.Category.CAFFEINE, InsightCard.TimePeriod.MONTHLY, DateTime.now(DateTimeZone.UTC), InsightCard.InsightType.DEFAULT)); }
Source:
private TestSplit(int id, OptionalInt bucketNumber) { super( "path", 0, 100, 100, ImmutableList.of(new InternalHiveBlock(100, ImmutableList.of())), bucketNumber, bucketNumber, true, false, NodeSelectionStrategy.NO_PREFERENCE, false, new HiveSplitPartitionInfo( new Storage( StorageFormat.create("serde", "input", "output"), "location", Optional.empty(), false, ImmutableMap.of()), new Path("path").toUri(), ImmutableList.of(), "partition-name", id, ImmutableMap.of(), Optional.empty()), Optional.empty()); }

Target:
private TestSplit(int id, OptionalInt bucketNumber) { super( "path", 0, 100, 100, ImmutableList.of(new InternalHiveBlock(100, ImmutableList.of())), bucketNumber, bucketNumber, true, false, NO_PREFERENCE, false, new HiveSplitPartitionInfo( new Storage( StorageFormat.create("serde", "input", "output"), "location", Optional.empty(), false, ImmutableMap.of()), new Path("path").toUri(), ImmutableList.of(), "partition-name", id, ImmutableMap.of(), Optional.empty()), Optional.empty()); }
Source:
public MultiSourceTrackingToken createTailToken() { Map<String, TrackingToken> tokenMap = new HashMap<>(); eventStreams.forEach((k, v) -> tokenMap.put(k, v.createTailToken())); return new MultiSourceTrackingToken(tokenMap); }

Target:
public MultiSourceTrackingToken createTailToken() { Map<String, TrackingToken> tokenMap = new HashMap<>(); eventStreams.forEach(streamableMessageSource -> tokenMap.put(streamableMessageSource.sourceId(), streamableMessageSource.createTailToken())); return new MultiSourceTrackingToken(tokenMap); }
Source:
public @Nonnull ILogData read(long address) { if (!runtime.getParameters().isCacheDisabled()) { try { ILogData data = readCache.getIfPresent(address); if (data == null) { final ILogData loadedVal = fetch(address); data = readCache.get(address, () -> loadedVal); return data; } } catch (ExecutionException | UncheckedExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else { throw new RuntimeException(cause); } } } return fetch(address); }

Target:
ILogData read(long address) { if (!runtime.getParameters().isCacheDisabled()) { ILogData data = readCache.getIfPresent(address); if (data == null) { final ILogData loadedVal = fetch(address); data = readCache.asMap().computeIfAbsent(address, (k) -> loadedVal); return data; } else { return data; } } else { return fetch(address); } }
Source:
public List<ValidationResult> getWarnings() { List<ValidationResult> warnings = new ArrayList<>(); for (ValidationResult vr: validationResults.values()) { if (ValidationResult.Result.WARNING == vr.getStatus()) { warnings.add(vr); } } return warnings; }

Target:
public Map<String, ValidationResult> getWarnings() { return filterResultsByStatus(Result.WARNING); }
Source:
public static Geopoint parse(@NonNull final String text) { try { final String[] parts = StringUtils.split(StringUtils.trim(text)); if (parts.length == 2) { final double lat = Double.parseDouble(StringUtils.strip(parts[0], " \t\u00a0")); final double lon = Double.parseDouble(StringUtils.strip(parts[1], " \t\u00a0")); return new Geopoint(lat, lon); } } catch (final NumberFormatException e) { } try { final UTMPoint utmPoint = new UTMPoint(text); return utmPoint.toLatLong(); } catch (final Exception e) { } final ResultWrapper latitudeWrapper = parseHelper(text, LatLon.LAT); final ResultWrapper longitudeWrapper = parseHelper(text.substring(latitudeWrapper.matcherPos + latitudeWrapper.matcherLength), LatLon.LON); if (longitudeWrapper.matcherPos - (latitudeWrapper.matcherPos + latitudeWrapper.matcherLength) >= 10) { throw new Geopoint.ParseException("Distance between latitude and longitude text is to large.", LatLon.LON); } final double lat = latitudeWrapper.result; if (!Geopoint.isValidLatitude(lat)) { throw new Geopoint.ParseException(text, LatLon.LAT); } final double lon = longitudeWrapper.result; if (!Geopoint.isValidLongitude(lon)) { throw new Geopoint.ParseException(text, LatLon.LON); } return new Geopoint(lat, lon); }

Target:
public static Geopoint parse(@NonNull final String text) { try { final String[] parts = StringUtils.split(StringUtils.trim(text)); if (parts.length == 2) { final double lat = Double.parseDouble(StringUtils.strip(parts[0], " \t\u00a0")); final double lon = Double.parseDouble(StringUtils.strip(parts[1], " \t\u00a0")); return new Geopoint(lat, lon); } } catch (final NumberFormatException ignored) { } try { final UTMPoint utmPoint = new UTMPoint(text); return utmPoint.toLatLong(); } catch (final Exception ignored) { } final ResultWrapper latitudeWrapper = parseHelper(text, LatLon.LAT); final ResultWrapper longitudeWrapper = parseHelper(text.substring(latitudeWrapper.matcherPos + latitudeWrapper.matcherLength), LatLon.LON); if (longitudeWrapper.matcherPos - (latitudeWrapper.matcherPos + latitudeWrapper.matcherLength) >= 10) { throw new Geopoint.ParseException("Distance between latitude and longitude text is to large.", LatLon.LON); } final double lat = latitudeWrapper.result; if (!Geopoint.isValidLatitude(lat)) { throw new Geopoint.ParseException(text, LatLon.LAT); } final double lon = longitudeWrapper.result; if (!Geopoint.isValidLongitude(lon)) { throw new Geopoint.ParseException(text, LatLon.LON); } return new Geopoint(lat, lon); }
Source:
public void visitAssignmentExpression(AssignmentExpressionTree tree) { if (!is(tree.expression(), "this")) { return; } ExpressionTree variable = tree.variable(); MemberSelectExpressionTree memberSelect; if (variable.is(Tree.Kind.MEMBER_SELECT)) { memberSelect = (MemberSelectExpressionTree) variable; if (memberSelect.expression().symbolType().symbol().equals(this.owner) && memberSelect.identifier().symbol().isStatic()) { return; } } if (variable.is(Tree.Kind.IDENTIFIER) && isStaticField((IdentifierTree) variable)) { return; } reportIssue(tree, REPORT); }

Target:
public void visitAssignmentExpression(AssignmentExpressionTree tree) { if (!isThis(tree.expression())) { return; } ExpressionTree variable = tree.variable(); if (variable.is(Tree.Kind.MEMBER_SELECT)) { MemberSelectExpressionTree memberSelect = (MemberSelectExpressionTree) variable; if (memberSelect.expression().symbolType().symbol().equals(this.owner) && memberSelect.identifier().symbol().isStatic()) { return; } } else if (variable.is(Tree.Kind.IDENTIFIER) && (((IdentifierTree) variable).symbol().isStatic())) { return; } report(tree); }
Source:
public void testConvertToLong() { final Set<AmrProfileStatusCodeFlag> amrStatusses = new HashSet<>(); amrStatusses.add(AmrProfileStatusCodeFlag.DATA_NOT_VALID); amrStatusses.add(AmrProfileStatusCodeFlag.POWER_DOWN); assertEquals((short) 132, (short) this.helperService.toValue(amrStatusses)); }

Target:
public void testConvertToLong() { final Set<AmrProfileStatusCodeFlag> amrStatusCodeFlags = new HashSet<>(); amrStatusCodeFlags.add(AmrProfileStatusCodeFlag.DATA_NOT_VALID); amrStatusCodeFlags.add(AmrProfileStatusCodeFlag.POWER_DOWN); assertEquals((short) 132, (short) this.helperService.toValue(amrStatusCodeFlags)); }
Source:
public void startElement(TagNode node) { if (node.getNodeName().equalsIgnoreCase(SLY_TAG)) { node.getAttributes().stream() .filter(this::containsRedundantUnwrapAttr) .findFirst() .ifPresent(attribute -> createViolation(node.getStartLinePosition(), VIOLATION_MESSAGE)); } }

Target:
public void startElement(TagNode node) { if (SLY_TAG.equalsIgnoreCase(node.getNodeName())) { node.getAttributes().stream() .filter(this::containsRedundantUnwrapAttr) .findFirst() .ifPresent(attribute -> createViolation(node.getStartLinePosition(), VIOLATION_MESSAGE)); } }
Source:
public void parseUnknownRules() { String rulesString = "{\n" + " \"schemas\": [\n" + " {\n" + " \"user\": \"(alice|bob)\",\n" + " \"schema\": \"(default|pv)\",\n" + " \"owner\": true\n" + " }" + " ]" + "}"; try { FileBasedSystemAccessControl.parse(rulesString.getBytes(US_ASCII)); fail("expected failure"); } catch (RuntimeException e) { assertContains(e.getMessage(), "Invalid JSON"); } }

Target:
public void parseUnknownRules() { assertThatThrownBy(() -> parse("src/test/resources/security-config-file-with-unknown-rules.json")) .hasMessageContaining("Invalid JSON"); }
Source:
private void loadSettingsFile(File file) { if (file == null) { firmwareSettingsFile = null; } else { try { firmwareSettingsFile = FirmwareSettingUtils.readSettings(file); } catch (IOException e) { JOptionPane.showMessageDialog(this.getComponent(), "Couldn't read settings file: " + e.getMessage(), "Error while reading settings file", JOptionPane.ERROR_MESSAGE); firmwareSettingsFile = null; } } showSettingsInformation(); }

Target:
private void loadSettingsFile(File file) { if (file == null) { firmwareSettingsFile = null; } else { try { firmwareSettingsFile = FirmwareSettingUtils.readSettings(file); } catch (IOException e) { GUIHelpers.displayErrorDialog("Couldn't read settings file: " + e.getMessage(), true); firmwareSettingsFile = null; } } showSettingsInformation(); }
Source:
public IStatus runInternal(final IProgressMonitor monitor) { try { if (!resource.isLoaded()) return Status.CANCEL_STATUS; if (resource instanceof AbstractSCTResource) { relinkModel(monitor, (AbstractSCTResource) resource); } if (monitor.isCanceled()) return Status.CANCEL_STATUS; TransactionalValidationRunner runner = new TransactionalValidationRunner(validator, resource, CheckMode.FAST_ONLY, new CancelIndicator() { public boolean isCanceled() { return monitor.isCanceled(); } }); TransactionalEditingDomain editingDomain = TransactionUtil.getEditingDomain(resource); if (editingDomain == null) return Status.CANCEL_STATUS; try { editingDomain.runExclusive(runner); } catch (Throwable ex) { return Status.CANCEL_STATUS; } final List<Issue> issues = runner.getResult(); if (issues == null) return Status.CANCEL_STATUS; validationIssueProcessor.processIssues(issues, monitor); } catch (Exception ex) { ex.printStackTrace(); return new Status(IStatus.ERROR, DiagramActivator.PLUGIN_ID, ex.getMessage()); } return Status.OK_STATUS; }

Target:
protected IStatus runInternal(final IProgressMonitor monitor) { try { if (!resource.isLoaded()) return Status.CANCEL_STATUS; if (resource instanceof AbstractSCTResource) { relinkModel(monitor, (AbstractSCTResource) resource); } if (monitor.isCanceled()) return Status.CANCEL_STATUS; TransactionalValidationRunner runner = new TransactionalValidationRunner(validator, resource, CheckMode.FAST_ONLY, new CancelIndicator() { public boolean isCanceled() { return monitor.isCanceled(); } }); TransactionalEditingDomain editingDomain = TransactionUtil.getEditingDomain(resource); if (editingDomain == null) return Status.CANCEL_STATUS; try { editingDomain.runExclusive(runner); } catch (Throwable ex) { return Status.CANCEL_STATUS; } final List<Issue> issues = runner.getResult(); if (issues == null) return Status.CANCEL_STATUS; validationIssueProcessor.processIssues(issues, monitor); } catch (Exception ex) { ex.printStackTrace(); return new Status(IStatus.ERROR, DiagramActivator.PLUGIN_ID, ex.getMessage()); } return Status.OK_STATUS; }
Source:
private void createProfiles() throws ConfigurationException { for (ExtensionEntry authnExtension : ConfigurationLoader.getInstance().getExtensionsByService(AUTHN_SERVICE)) { registerProfile( new AuthenticationProfile( (Authenticator) authnExtension.getExtension(), (Directory) ConfigurationLoader.getInstance().getExtensionByName( authnExtension.getConfig().getString(AUTHN_AUTHZ_PLUGIN) ).getExtension() ) ); } }

Target:
private void createProfiles() throws ConfigurationException { for (ExtensionEntry authnExtension : ExtensionLoader.getInstance().getProvidedExtensions(AUTHN_SERVICE)) { registerProfile( new AuthenticationProfile( (Authenticator) authnExtension.getExtension(), (Directory) ExtensionLoader.getInstance().getExtensionByName( authnExtension.getConfig().getString(AUTHN_AUTHZ_PLUGIN) ).getExtension() ) ); } }
Source:
static synchronized void release(BaseRealm realm) { String canonicalPath = realm.getPath(); RealmCache cache = cachesMap.get(canonicalPath); Integer refCount = null; RefAndCount refAndCount = null; if (cache != null) { refAndCount = cache.refAndCountMap.get(RealmCacheType.valueOf(realm.getClass())); refCount = refAndCount.localCount.get(); } if (refCount == null) { refCount = 0; } if (refCount <= 0) { RealmLog.w("Realm " + canonicalPath + " has been closed already."); return; } realm.tidyPerformedTransactions(); if (!realm.asyncTransactions.isEmpty() || !realm.asyncTransactionCallbacks.isEmpty()) { RealmLog.w("Realm " + canonicalPath + " will be closed with pending async transactions or callbacks."); } refCount -= 1; if (refCount == 0) { refAndCount.localCount.set(null); refAndCount.localRealm.set(null); refAndCount.globalCount--; if (refAndCount.globalCount < 0) { throw new IllegalStateException("Global reference counter of Realm" + canonicalPath + " got corrupted."); } if (realm instanceof Realm && refAndCount.globalCount == 0) { cache.typedColumnIndices = null; } int totalRefCount = 0; for (RealmCacheType type : RealmCacheType.values()) { totalRefCount += cache.refAndCountMap.get(type).globalCount; } if (totalRefCount == 0) { cachesMap.remove(canonicalPath); } realm.doClose(); } else { refAndCount.localCount.set(refCount); } }

Target:
static synchronized void release(BaseRealm realm) { String canonicalPath = realm.getPath(); RealmCache cache = cachesMap.get(canonicalPath); Integer refCount = null; RefAndCount refAndCount = null; if (cache != null) { refAndCount = cache.refAndCountMap.get(RealmCacheType.valueOf(realm.getClass())); refCount = refAndCount.localCount.get(); } if (refCount == null) { refCount = 0; } if (refCount <= 0) { RealmLog.w("Realm " + canonicalPath + " has been closed already."); return; } refCount -= 1; if (refCount == 0) { refAndCount.localCount.set(null); refAndCount.localRealm.set(null); refAndCount.globalCount--; if (refAndCount.globalCount < 0) { throw new IllegalStateException("Global reference counter of Realm" + canonicalPath + " got corrupted."); } if (realm instanceof Realm && refAndCount.globalCount == 0) { cache.typedColumnIndices = null; } int totalRefCount = 0; for (RealmCacheType type : RealmCacheType.values()) { totalRefCount += cache.refAndCountMap.get(type).globalCount; } if (totalRefCount == 0) { cachesMap.remove(canonicalPath); } realm.doClose(); } else { refAndCount.localCount.set(refCount); } }