auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void should_exclude_virtual_keyspaces_from_token_map() { if (ccmRule.getDseVersion().isPresent()) { Version dseVersion = ccmRule.getDseVersion().get(); if (dseVersion.compareTo(DSE_MIN_VIRTUAL_TABLES) < 0) { throw new AssumptionViolatedException("DSE 6.0 does not support virtual tables"); } } Metadata metadata = sessionRule.session().getMetadata(); Map<CqlIdentifier, ? extends KeyspaceMetadata> keyspaces = metadata.getKeyspaces(); assertThat(keyspaces) .containsKey(CqlIdentifier.fromCql("system_views")) .containsKey(CqlIdentifier.fromCql("system_virtual_schema")); TokenMap tokenMap = metadata.getTokenMap().orElseThrow(AssertionError::new); ByteBuffer partitionKey = Bytes.fromHexString("0x00"); assertThat(tokenMap.getReplicas("system_views", partitionKey)).isEmpty(); assertThat(tokenMap.getReplicas("system_virtual_schema", partitionKey)).isEmpty(); assertThat(tokenMap.getReplicas(sessionRule.keyspace(), partitionKey)).isNotEmpty(); }

Target:
public void should_exclude_virtual_keyspaces_from_token_map() { skipIfDse60(); Metadata metadata = sessionRule.session().getMetadata(); Map<CqlIdentifier, ? extends KeyspaceMetadata> keyspaces = metadata.getKeyspaces(); assertThat(keyspaces) .containsKey(CqlIdentifier.fromCql("system_views")) .containsKey(CqlIdentifier.fromCql("system_virtual_schema")); TokenMap tokenMap = metadata.getTokenMap().orElseThrow(AssertionError::new); ByteBuffer partitionKey = Bytes.fromHexString("0x00"); assertThat(tokenMap.getReplicas("system_views", partitionKey)).isEmpty(); assertThat(tokenMap.getReplicas("system_virtual_schema", partitionKey)).isEmpty(); assertThat(tokenMap.getReplicas(sessionRule.keyspace(), partitionKey)).isNotEmpty(); }
Source:
public GDPRSymmetricKey(String secret, String algorithm) throws Exception { Preconditions.checkArgument(secret.length() == 32, "Secret must be exactly 32 characters"); this.secret = secret; this.algorithm = algorithm; this.secretKey = new SecretKeySpec( secret.substring(0, OzoneConsts.GDPR_RANDOM_SECRET_LENGTH) .getBytes(OzoneConsts.GDPR_CHARSET), algorithm); this.cipher = Cipher.getInstance(algorithm); }

Target:
public GDPRSymmetricKey(String secret, String algorithm) throws Exception { Preconditions.checkArgument(secret.length() == 32, "Secret must be exactly 32 characters"); this.secret = secret; this.algorithm = algorithm; this.secretKey = new SecretKeySpec( secret.getBytes(OzoneConsts.GDPR_CHARSET), algorithm); this.cipher = Cipher.getInstance(algorithm); }
Source:
public Iterator<T> iterator() { if (state == State.INFLATED) { return Collections.unmodifiableSet(inflatedSet).iterator(); } return new ImmutableHybridIterator(); }

Target:
public Iterator<T> iterator() { if (state == State.INFLATED) { throw new IllegalStateException("Set is immutable and can not be inflated."); } return new ImmutableHybridIterator(); }
Source:
public boolean allObjUids(String typeName, InputObjectState foundInstances, int matchState) throws ObjectStoreException { if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger.trace("SlotStore.allObjUids(" + typeName + ", " + matchState + ")"); } SlotStoreKey key = new SlotStoreKey(null, typeName, matchState); SlotStoreKey[] matchingKeys = store.getMatchingKeys(key); OutputObjectState buffer = new OutputObjectState(); try { if (matchingKeys != null) { for (SlotStoreKey matchingKey : matchingKeys) { if (matchingKey != null) { UidHelper.packInto(matchingKey.getUid(), buffer); } } } UidHelper.packInto(Uid.nullUid(), buffer); } catch (IOException e) { throw new ObjectStoreException(e); } foundInstances.setBuffer(buffer.buffer()); return true; }

Target:
public boolean allObjUids(String typeName, InputObjectState foundInstances, int matchState) throws ObjectStoreException { if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger.trace("SlotStore.allObjUids(" + typeName + ", " + matchState + ")"); } SlotStoreKey key = new SlotStoreKey(null, typeName, matchState); SlotStoreKey[] matchingKeys = store.getMatchingKeys(key); OutputObjectState buffer = new OutputObjectState(); try { for (SlotStoreKey matchingKey : matchingKeys) { UidHelper.packInto(matchingKey.getUid(), buffer); } UidHelper.packInto(Uid.nullUid(), buffer); } catch (IOException e) { throw new ObjectStoreException(e); } foundInstances.setBuffer(buffer.buffer()); return true; }
Source:
private DataCenter reInitializeDataCenter(String dcId) throws RuntimeException { log.info("about to reinitialize dc"); DataCenter dataCenter = new DataCenter(); dataCenter.setId(dcId); updateDataCenter(dataCenter); return dataCenter; }

Target:
private DataCenter reInitializeDataCenter(String dcId) throws RuntimeException { log.warn("about to reinitialize dc"); DataCenter dataCenter = new DataCenter(); dataCenter.setId(dcId); updateDataCenter(dataCenter); return dataCenter; }
Source:
public void test() throws Exception { connect(); waitResponse(); JQuery input = jq(".z-paging").eq(1).find("input"); sendKeys(input, Keys.BACK_SPACE); waitResponse(); sendKeys(input, Keys.NUMPAD2); waitResponse(); sendKeys(input, Keys.ENTER); waitResponse(); JQuery activePageLabel = jq("$currentPage"); assertEquals("1", activePageLabel.html().trim()); click(jq(".z-paging-previous")); waitResponse(); assertEquals("0", activePageLabel.html().trim()); click(jq(".z-paging-next")); waitResponse(); assertEquals("1", activePageLabel.html().trim()); click(jq("@button")); waitResponse(); click(jq(".z-paging-button").eq(3)); waitResponse(); assertEquals("0", activePageLabel.html().trim()); click(jq(".z-paging-button").eq(5)); waitResponse(); assertEquals("1", activePageLabel.html().trim()); }

Target:
public void test() throws Exception { connect(); waitResponse(); JQuery input = jq(".z-paging").eq(1).find("input"); sendKeys(input, Keys.BACK_SPACE); waitResponse(); sendKeys(input, "2"); waitResponse(); sendKeys(input, Keys.ENTER); waitResponse(); JQuery activePageLabel = jq("$currentPage"); assertEquals("1", activePageLabel.html().trim()); click(jq(".z-paging-previous")); waitResponse(); assertEquals("0", activePageLabel.html().trim()); click(jq(".z-paging-next")); waitResponse(); assertEquals("1", activePageLabel.html().trim()); click(jq("@button")); waitResponse(); click(jq(".z-paging-button").eq(3)); waitResponse(); assertEquals("0", activePageLabel.html().trim()); click(jq(".z-paging-button").eq(5)); waitResponse(); assertEquals("1", activePageLabel.html().trim()); }
Source:
public static void loadPlayerTransports(int trnId, Set<Integer> toLoad, Client client, boolean loadFighters, boolean loadGround) { if (!loadFighters && !loadGround) { return; } Entity transport = client.getEntity(trnId); transport.resetTransporter(); for (int id : toLoad) { Entity cargo = client.getEntity(id); if (cargo == null) { continue; } cargo.setTargetBay(selectBestBayFor(cargo, transport)); } transport.resetTransporter(); for (int id : toLoad) { Entity cargo = client.getEntity(id); if (cargo.isFighter() && loadFighters && transport.canLoad(cargo, false) && cargo.getTargetBay() != -1) { client.sendLoadEntity(id, trnId, cargo.getTargetBay()); } else if(loadGround && transport.canLoad(cargo, false) && cargo.getTargetBay() != -1) { client.sendLoadEntity(id, trnId, cargo.getTargetBay()); } } }

Target:
public static void loadPlayerTransports(int trnId, Set<Integer> toLoad, Client client, boolean loadFighters, boolean loadGround) { String METHOD_NAME = "loadPlayerTransports(int,Set<Integer>,Client,boolean,boolean)"; if (!loadFighters && !loadGround) { return; } Entity transport = client.getEntity(trnId); transport.resetTransporter(); for (int id : toLoad) { Entity cargo = client.getEntity(id); if (cargo == null) { continue; } cargo.setTargetBay(selectBestBayFor(cargo, transport)); } transport.resetTransporter(); for (int id : toLoad) { Entity cargo = client.getEntity(id); if (cargo.isFighter() && loadFighters && transport.canLoad(cargo, false) && cargo.getTargetBay() != -1) { client.sendLoadEntity(id, trnId, cargo.getTargetBay()); try { Thread.sleep(500); } catch (Exception e) { MekHQ.getLogger().error(Utilities.class, METHOD_NAME, e); } } else if(loadGround && transport.canLoad(cargo, false) && cargo.getTargetBay() != -1) { client.sendLoadEntity(id, trnId, cargo.getTargetBay()); try { Thread.sleep(500); } catch (Exception e) { MekHQ.getLogger().error(Utilities.class, METHOD_NAME, e); } } } }
Source:
public DocumentModel updateUserInfo(DocumentModel user, OpenIDUserInfo userInfo) { try { UserManager userManager = Framework.getService(UserManager.class); user.setPropertyValue(userManager.getUserEmailField(), userInfo.getEmail()); Framework.doPrivileged(() -> { userManager.updateUser(user); }); } catch (NuxeoException e) { log.error("Error while search user in UserManager using email " + userInfo.getEmail(), e); return null; } return user; }

Target:
public DocumentModel updateUserInfo(DocumentModel user, OpenIDUserInfo userInfo) { try { UserManager userManager = Framework.getService(UserManager.class); user.setPropertyValue(userManager.getUserEmailField(), userInfo.getEmail()); Framework.doPrivileged(() -> userManager.updateUser(user)); } catch (NuxeoException e) { log.error("Error while search user in UserManager using email " + userInfo.getEmail(), e); return null; } return user; }
Source:
public void interoperability() { story.addStep(new Statement() { @Override public void evaluate() throws Throwable { defineResource("resource1"); WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( "lock('resource1') {\n" + " echo 'Locked'\n" + "}\n" + "echo 'Finish'" )); FreeStyleProject f = story.j.createFreeStyleProject("f"); f.addProperty(new RequiredResourcesProperty("resource1", null, null, null)); f.getBuildersList().add(new Shell("sleep 10")); f.scheduleBuild2(0).waitForStart(); WorkflowRun b1 = p.scheduleBuild2(0).waitForStart(); story.j.waitForMessage("[resource1] is locked, waiting...", b1); story.j.waitForMessage("Lock released on resouce [resource1]", b1); } }); }

Target:
public void interoperability() { final Semaphore semaphore = new Semaphore(1); story.addStep(new Statement() { @Override public void evaluate() throws Throwable { LockableResourcesManager.get().createResource("resource1"); WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition( "lock('resource1') {\n" + " echo 'Locked'\n" + "}\n" + "echo 'Finish'" )); FreeStyleProject f = story.j.createFreeStyleProject("f"); f.addProperty(new RequiredResourcesProperty("resource1", null, null, null)); f.getBuildersList().add(new TestBuilder() { @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { semaphore.acquire(); return true; } }); semaphore.acquire(); f.scheduleBuild2(0).waitForStart(); WorkflowRun b1 = p.scheduleBuild2(0).waitForStart(); story.j.waitForMessage("[resource1] is locked, waiting...", b1); semaphore.release(); story.j.waitForMessage("Lock released on resouce [resource1]", b1); } }); }
Source:
private IntegrationBus(Builder builder) { this.boundedContextName = builder.boundedContextName; this.subscriberHub = new SubscriberHub(builder.getTransportFactory().get()); this.publisherHub = new PublisherHub(builder.getTransportFactory().get()); this.localBusAdapters = createAdapters(builder, publisherHub); configurationChangeObserver = observeConfigurationChanges(); subscriberHub.get(CONFIG_EXCHANGE_CHANNEL_ID) .addObserver(configurationChangeObserver); }

Target:
private IntegrationBus(Builder builder) { final TransportFactory transportFactory = builder.getTransportFactory() .get(); this.boundedContextName = builder.boundedContextName; this.subscriberHub = new SubscriberHub(transportFactory); this.publisherHub = new PublisherHub(transportFactory); this.localBusAdapters = createAdapters(builder, publisherHub); configurationChangeObserver = observeConfigurationChanges(); subscriberHub.get(CONFIG_EXCHANGE_CHANNEL_ID) .addObserver(configurationChangeObserver); }
Source:
protected void handleMessageInternal(Message<?> message) { boolean sent = false; Collection<MessageChannel> results = this.determineTargetChannels(message); if (results != null) { int sequenceSize = results.size(); int sequenceNumber = 1; for (MessageChannel channel : results) { final Message<?> messageToSend; if (!this.applySequence) { messageToSend = message; } else { UUID id = message.getHeaders().getId(); messageToSend = getMessageBuilderFactory() .fromMessage(message) .pushSequenceDetails(id == null ? IntegrationObjectSupport.generateId() : id, sequenceNumber++, sequenceSize) .build(); } if (channel != null) { sent |= doSend(channel, messageToSend); } } } if (!sent) { getDefaultOutputChannel(); if (this.defaultOutputChannel != null) { this.messagingTemplate.send(this.defaultOutputChannel, message); } else { throw new MessageDeliveryException(message, "No channel resolved by router '" + this.getComponentName() + "' and no 'defaultOutputChannel' defined."); } } }

Target:
protected void handleMessageInternal(Message<?> message) { boolean sent = false; Collection<MessageChannel> results = this.determineTargetChannels(message); if (results != null) { int sequenceSize = results.size(); int sequenceNumber = 1; for (MessageChannel channel : results) { final Message<?> messageToSend; if (!this.applySequence) { messageToSend = message; } else { UUID id = message.getHeaders().getId(); messageToSend = getMessageBuilderFactory() .fromMessage(message) .pushSequenceDetails(id == null ? generateId() : id, sequenceNumber++, sequenceSize) .build(); } if (channel != null) { sent |= doSend(channel, messageToSend); } } } if (!sent) { getDefaultOutputChannel(); if (this.defaultOutputChannel != null) { this.messagingTemplate.send(this.defaultOutputChannel, message); } else { throw new MessageDeliveryException(message, "No channel resolved by router '" + this.getComponentName() + "' and no 'defaultOutputChannel' defined."); } } }
Source:
protected String getToolOptions(String languageId) { String flags = ""; ITool tool = getTool(languageId); if (tool != null) { IOption[] options = tool.getOptions(); for (IOption option : options) { if (option.isForScannerDiscovery()) { try { String optionValue = null; switch (option.getBasicValueType()) { case IOption.BOOLEAN: if (option.getBooleanValue()) { optionValue = option.getCommand(); } else { optionValue = option.getCommandFalse(); } break; case IOption.ENUMERATED: optionValue = option.getEnumCommand(option.getSelectedEnum()); break; case IOption.STRING: optionValue = option.getCommand() + option.getStringValue(); break; case IOption.STRING_LIST: String[] values = option.getBasicStringListValue(); if(values != null) { optionValue = ""; StringBuilder sb = new StringBuilder(optionValue); String cmd = option.getCommand(); for (String value : values) { if(!value.isEmpty() && !value.equals(EMPTY_QUOTED_STRING)) { sb.append(cmd).append(value); sb.append(' '); } } optionValue = sb.toString(); } break; case IOption.TREE: optionValue = option.getCommand(option.getStringValue()); break; default: } if (optionValue != null) { flags = flags + ' ' + optionValue.trim(); } } catch (BuildException e) { ManagedBuilderCorePlugin.log(e); } } } } return flags.trim(); }

Target:
protected String getToolOptions(String languageId) { String flags = ""; ITool tool = getTool(languageId); if (tool != null) { IOption[] options = tool.getOptions(); for (IOption option : options) { if (option.isForScannerDiscovery()) { try { String optionValue = null; switch (option.getBasicValueType()) { case IOption.BOOLEAN: if (option.getBooleanValue()) { optionValue = option.getCommand(); } else { optionValue = option.getCommandFalse(); } break; case IOption.ENUMERATED: optionValue = option.getEnumCommand(option.getSelectedEnum()); break; case IOption.STRING: optionValue = option.getCommand() + option.getStringValue(); break; case IOption.STRING_LIST: String[] values = option.getBasicStringListValue(); if(values != null) { optionValue = ""; StringBuilder sb = new StringBuilder(); String cmd = option.getCommand(); for (String value : values) { if(!value.isEmpty() && !value.equals(EMPTY_QUOTED_STRING)) { sb.append(cmd).append(value); sb.append(' '); } } optionValue = sb.toString(); } break; case IOption.TREE: optionValue = option.getCommand(option.getStringValue()); break; default: } if (optionValue != null) { flags = flags + ' ' + optionValue.trim(); } } catch (BuildException e) { ManagedBuilderCorePlugin.log(e); } } } } return flags.trim(); }
Source:
public static boolean getBooleanHeader(Map<String, Object> args, String header, boolean required) throws RestServiceException { boolean booleanValue; String stringValue = getHeader(args, header, required); if (stringValue == null || stringValue.toLowerCase().equals("false")) { booleanValue = false; } else if (stringValue.toLowerCase().equals("true")) { booleanValue = true; } else { throw new RestServiceException( header + "[" + stringValue + "] has an invalid value (allowed values: true, false)", RestServiceErrorCode.InvalidArgs); } return booleanValue; }

Target:
public static boolean getBooleanHeader(Map<String, Object> args, String header, boolean required) throws RestServiceException { boolean booleanValue; String stringValue = getHeader(args, header, required); if (stringValue == null || "false".equalsIgnoreCase(stringValue)) { booleanValue = false; } else if ("true".equalsIgnoreCase(stringValue)) { booleanValue = true; } else { throw new RestServiceException( header + "[" + stringValue + "] has an invalid value (allowed values: true, false)", RestServiceErrorCode.InvalidArgs); } return booleanValue; }
Source:
public void addUpdateTask(Operations operation, String key) { mUpdateTasks.add(new BoxMetadataUpdateTask(operation, key)); setUpdateTasks(mUpdateTasks); }

Target:
public UpdateFileMetadata addUpdateTask(Operations operation, String key) { return addUpdateTask(operation, key, ""); }
Source:
public void initializeServers(NotificationSystem notificationSystem) { List<MockDataNodeId> dataNodes = clusterMap.getDataNodes(); for (int i = 0; i < dataNodes.size(); i++) { if (sslEnabledDataCenterList != null) { dataNodes.get(i).setSslEnabledDataCenters(sslEnabledDataCenterList); } initializeServer(dataNodes.get(i), sslProps, enableHardDeletes, prefetchDataNodeIndex == i ? true : false, notificationSystem, time); } }

Target:
public void initializeServers(NotificationSystem notificationSystem) { List<MockDataNodeId> dataNodes = clusterMap.getDataNodes(); for (int i = 0; i < dataNodes.size(); i++) { if (sslEnabledDataCenterList != null) { dataNodes.get(i).setSslEnabledDataCenters(sslEnabledDataCenterList); } initializeServer(dataNodes.get(i), sslProps, enableHardDeletes, prefetchDataNodeIndex == i, notificationSystem, time); } }
Source:
protected void onNewIntent(Intent intent) { if (!searchEditText.getText().toString().isEmpty()) { Log.i(TAG, "Clearing search field"); searchEditText.setText(""); } if (isViewingAllApps()) { displayKissBar(false); } MainActivity.this.closeContextMenu(); }

Target:
protected void onNewIntent(Intent intent) { if (!searchEditText.getText().toString().isEmpty()) { Log.i(TAG, "Clearing search field"); searchEditText.setText(""); } if (isViewingAllApps()) { displayKissBar(false); } closeContextMenu(); }
Source:
public SpongeParticleEffectBuilder count(int count) throws IllegalArgumentException { if (count < 1) { throw new IllegalArgumentException("The count has to be greater then zero!"); } this.count = count; return this; }

Target:
public SpongeParticleEffectBuilder count(int count) throws IllegalArgumentException { checkArgument(count > 0, "The count has to be greater then zero!"); this.count = count; return this; }
Source:
@Test void testSelectNull() { String query = "SELECT NULL AS DUMMY FROM \"product\""; final String expected = "SELECT CAST(NULL AS NULL) AS \"DUMMY\"\n" + "FROM \"foodmart\".\"product\""; sql(query).ok(expected); }

Target:
@Test void testSelectNull() { String query = "SELECT NULL FROM \"product\""; final String expected = "SELECT NULL\n" + "FROM \"foodmart\".\"product\""; sql(query).ok(expected); }
Source:
public Dialog onCreateDialog(Bundle savedInstanceState) { Context context = getContext(); AlertDialog.Builder builder = new AlertDialog.Builder(context); View main = LayoutInflater.from(context).inflate(R.layout.pass_code_input_dialog, null); builder.setTitle(R.string.authtitle); builder.setMessage(R.string.authtext); final EditText input = (EditText) main.findViewById(R.id.pass_code_et); builder.setView(main); builder.setPositiveButton(R.string.okbutton, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String val = input.getText().toString(); if (ConstantUtil.ADMIN_AUTH_CODE.equals(val)) { onPassCodeCorrect(); if (dialog != null) { dialog.dismiss(); } } else { onPassCodeError(); if (dialog != null) { dialog.dismiss(); } } } }); builder.setNegativeButton(R.string.cancelbutton, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); } }); return builder.create(); }

Target:
public Dialog onCreateDialog(Bundle savedInstanceState) { Context context = getContext(); AlertDialog.Builder builder = new AlertDialog.Builder(context); View main = LayoutInflater.from(context).inflate(R.layout.pass_code_input_dialog, null); builder.setTitle(R.string.authtitle); builder.setMessage(R.string.authtext); final EditText input = (EditText) main.findViewById(R.id.pass_code_et); builder.setView(main); builder.setPositiveButton(R.string.okbutton, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String val = input.getText().toString(); if (ConstantUtil.ADMIN_AUTH_CODE.equals(val)) { onPassCodeCorrect(); } else { onPassCodeError(); } if (dialog != null) { dialog.dismiss(); } } }); builder.setNegativeButton(R.string.cancelbutton, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); } }); return builder.create(); }
Source:
public static Key get(int x, int z) { int id = x * 31 + z; Key key = keys.get(id); if (key != null) return key; key = new Key(x, z); keys.put(id, key); return key; }

Target:
public static Key get(int x, int z) { int id = Key.hashCode(x, z); Key key = keys.get(id); if (key != null) return key; key = new Key(x, z); keys.put(id, key); return key; }
Source:
private void attachDisk_EntityChanged(EventArgs e) { if ((Boolean) getIsAttachDisk().getEntity()) { getIsPlugged().setIsAvailable(true); AsyncDataProvider.getAllAttachableDisks(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { AbstractDiskModel model = (AbstractDiskModel) target; ArrayList<Disk> disks = (ArrayList<Disk>) returnValue; Collections.sort(disks, new Linq.DiskByAliasComparer()); ArrayList<DiskModel> diskModels = Linq.disksToDiskModelList(disks); model.getInternalAttachableDisks().setItems(Linq.toEntityModelList( Linq.filterDisksByType(diskModels, DiskStorageType.IMAGE))); } }, getHash()), getVm().getStoragePoolId(), getVm().getId()); AsyncDataProvider.getAllAttachableDisks(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { AbstractDiskModel model = (AbstractDiskModel) target; ArrayList<Disk> disks = (ArrayList<Disk>) returnValue; Collections.sort(disks, new Linq.DiskByAliasComparer()); ArrayList<DiskModel> diskModels = Linq.disksToDiskModelList(disks); model.getExternalAttachableDisks().setItems(Linq.toEntityModelList( Linq.filterDisksByType(diskModels, DiskStorageType.LUN))); } }, getHash()), null, getVm().getId()); } else { if (!getIsNew()) { getIsPlugged().setIsAvailable(false); } } }

Target:
private void attachDisk_EntityChanged(EventArgs e) { if ((Boolean) getIsAttachDisk().getEntity()) { getIsPlugged().setIsAvailable(true); AsyncDataProvider.getAllAttachableDisks(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { AbstractDiskModel model = (AbstractDiskModel) target; ArrayList<Disk> disks = (ArrayList<Disk>) returnValue; Collections.sort(disks, new Linq.DiskByAliasComparer()); ArrayList<DiskModel> diskModels = Linq.disksToDiskModelList(disks); model.getInternalAttachableDisks().setItems(Linq.toEntityModelList( Linq.filterDisksByType(diskModels, DiskStorageType.IMAGE))); } }, getHash()), getVm().getStoragePoolId(), getVm().getId()); AsyncDataProvider.getAllAttachableDisks(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { AbstractDiskModel model = (AbstractDiskModel) target; ArrayList<Disk> disks = (ArrayList<Disk>) returnValue; Collections.sort(disks, new Linq.DiskByAliasComparer()); ArrayList<DiskModel> diskModels = Linq.disksToDiskModelList(disks); model.getExternalAttachableDisks().setItems(Linq.toEntityModelList( Linq.filterDisksByType(diskModels, DiskStorageType.LUN))); } }, getHash()), null, getVm().getId()); } }
Source:
public ActionForward exportToExcel(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { final ExecutionYear executionYear = getDomainObject(request, "xecutionYearOid"); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment; filename=dissertacoes" + executionYear.getYear().replace("/", "") + ".xls"); final ServletOutputStream writer = response.getOutputStream(); exportDissertations(writer, executionYear); writer.flush(); response.flushBuffer(); return null; }

Target:
public ActionForward exportToExcel(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { final ExecutionYear executionYear = getDomainObject(request, "executionYearOid"); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment; filename=dissertacoes" + executionYear.getYear().replace("/", "") + ".xls"); final ServletOutputStream writer = response.getOutputStream(); exportDissertations(writer, executionYear); writer.flush(); response.flushBuffer(); return null; }
Source:
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { return findAnnotation(context.getElement(), DisabledForJreRange.class) .map(disabledForJreRange -> { JRE min = disabledForJreRange.min(); JRE max = disabledForJreRange.max(); Preconditions.condition(max.compareTo(min) >= 0, "@DisabledForJreRange.min must be lower or the same version as @DisabledForJreRange.max"); if (isCurrentVersionWithinRange(min, max)) { return DISABLED_ON_CURRENT_JRE; } else { return ENABLED_ON_CURRENT_JRE; } }).orElse(ENABLED_BY_DEFAULT); }

Target:
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { return findAnnotation(context.getElement(), DisabledForJreRange.class) .map(disabledForJreRange -> { JRE min = disabledForJreRange.min(); JRE max = disabledForJreRange.max(); Preconditions.condition(max.compareTo(min) >= 0, "@DisabledForJreRange.min must be lower or the same version as @DisabledForJreRange.max"); if (isCurrentVersionWithinRange(min, max)) { return DISABLED_ON_CURRENT_JRE; } return ENABLED_ON_CURRENT_JRE; }).orElse(ENABLED_BY_DEFAULT); }
Source:
public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) throws Throwable { log.tracef("Processing a remote compute %s", command); if (command.isConditional()) { return backupCache.computeIfPresent(command.getKey(), command.getRemappingBiFunction(), command.getMetadata()); } return backupCache.compute(command.getKey(), command.getRemappingBiFunction(), command.getMetadata()); }

Target:
public Object visitComputeCommand(InvocationContext ctx, ComputeCommand command) throws Throwable { if (command.isConditional()) { return backupCache.computeIfPresent(command.getKey(), command.getRemappingBiFunction(), command.getMetadata()); } return backupCache.compute(command.getKey(), command.getRemappingBiFunction(), command.getMetadata()); }
Source:
public void testOnlineConfigChange() throws IOException { LOG.debug("Starting the test testOnlineConfigChange"); Admin admin = TEST_UTIL.getAdmin(); ServerName server = TEST_UTIL.getHBaseCluster().getRegionServer(0).getServerName(); admin.updateConfiguration(server); }

Target:
public void testOnlineConfigChange() throws IOException { LOG.debug("Starting the test {}", name.getMethodName()); Admin admin = TEST_UTIL.getAdmin(); ServerName server = TEST_UTIL.getHBaseCluster().getRegionServer(0).getServerName(); admin.updateConfiguration(server); }
Source:
public void onClick(View v) { switch (v.getId()) { case R.id.sign_in_button: if (!BaseGameUtils.verifySampleSetup(this, R.string.app_id)) { Log.w(TAG, "*** Warning: setup problems detected. Sign in may not work!"); } mSignInClicked = true; mTurnBasedMatch = null; findViewById(R.id.sign_in_button).setVisibility(View.GONE); mGoogleApiClient.connect(); break; case R.id.sign_out_button: mSignInClicked = false; Games.signOut(mGoogleApiClient); mGoogleApiClient.disconnect(); setViewVisibility(); break; } }

Target:
public void onClick(View v) { switch (v.getId()) { case R.id.sign_in_button: if (!BaseGameUtils.verifySampleSetup(this, R.string.app_id)) { Log.w(TAG, "*** Warning: setup problems detected. Sign in may not work!"); } mSignInClicked = true; mTurnBasedMatch = null; findViewById(R.id.sign_in_button).setVisibility(View.GONE); mGoogleApiClient.connect(); break; case R.id.sign_out_button: mSignInClicked = false; Games.signOut(mGoogleApiClient); if (mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } setViewVisibility(); break; } }
Source:
protected int processParams(ListIterator listIterator) throws UnsupportedOperationException, IllegalArgumentException { LoggingManager.setPriority(Priority.INFO); if (!listIterator.hasNext()) { showHelp(System.out); return -1; } String command = listIterator.next().toString(); log.info("Command is: " + command); try { switch (command) { case "status": System.out.println(PluginManager.getAllPluginsStatus()); break; case "install": process(listIterator, true); break; case "uninstall": process(listIterator, false); break; case "help": showHelp(System.out); break; case "available": showAvailable(); break; case "upgrades": showUpgrades(); break; default: showHelp(System.out); return -1; } } catch (IllegalArgumentException e) { throw e; } catch (Throwable e) { throw new RuntimeException("Failed to perform cmdline operation: " + e.getMessage(), e); } return 0; }

Target:
protected int processParams(ListIterator listIterator) throws UnsupportedOperationException, IllegalArgumentException { LoggingManager.setPriority(Priority.INFO); if (!listIterator.hasNext()) { showHelp(System.out); throw new IllegalArgumentException("Command parameter is missing"); } String command = listIterator.next().toString(); log.info("Command is: " + command); try { switch (command) { case "status": System.out.println(PluginManager.getAllPluginsStatus()); break; case "install": process(listIterator, true); break; case "uninstall": process(listIterator, false); break; case "help": showHelp(System.out); break; case "available": System.out.println(PluginManager.getAvailablePluginsAsString()); break; case "upgrades": System.out.println(PluginManager.getUpgradablePluginsAsString()); break; default: showHelp(System.out); throw new UnsupportedOperationException("Wrong command: " + command); } } catch (IllegalArgumentException e) { throw e; } catch (Throwable e) { throw new RuntimeException("Failed to perform cmdline operation: " + e.getMessage(), e); } return 0; }
Source:
public static Map<String, Object> normalizeTypes(Map<String, Object> configuration, List<ConfigDescription> configDescriptions) { if (configDescriptions == null || configDescriptions.isEmpty()) { throw new IllegalArgumentException("Config description must not be null."); } if (configuration == null) { return null; } Map<String, Object> convertedConfiguration = new HashMap<>(); Map<String, ConfigDescriptionParameter> configParams = new HashMap<>(); for (int i = configDescriptions.size() - 1; i >= 0; i--) { configParams.putAll(configDescriptions.get(i).toParametersMap()); } for (Entry<String, ?> parameter : configuration.entrySet()) { String name = parameter.getKey(); Object value = parameter.getValue(); if (!name.equals("objectClass") && !name.equals("component.name") && !name.equals("component.id")) { ConfigDescriptionParameter configDescriptionParameter = configParams.get(name); convertedConfiguration.put(name, normalizeType(value, configDescriptionParameter)); } } return convertedConfiguration; }

Target:
public static Map<String, Object> normalizeTypes(Map<String, Object> configuration, List<ConfigDescription> configDescriptions) { if (configDescriptions == null || configDescriptions.isEmpty()) { throw new IllegalArgumentException("Config description must not be null."); } if (configuration == null) { return null; } Map<String, Object> convertedConfiguration = new HashMap<>(); Map<String, ConfigDescriptionParameter> configParams = new HashMap<>(); for (int i = configDescriptions.size() - 1; i >= 0; i--) { configParams.putAll(configDescriptions.get(i).toParametersMap()); } for (Entry<String, ?> parameter : configuration.entrySet()) { String name = parameter.getKey(); Object value = parameter.getValue(); if (!isOSGiConfigParameter(name)) { ConfigDescriptionParameter configDescriptionParameter = configParams.get(name); convertedConfiguration.put(name, normalizeType(value, configDescriptionParameter)); } } return convertedConfiguration; }
Source:
private IModuleResource[] getAllResources(IModuleResourceDelta[] delta, int kind, boolean depthFirst) { if( delta == null ) return new IModuleResource[0]; ArrayList<IModuleResource> list = new ArrayList<IModuleResource>(); for( int i = 0; i < delta.length; i++ ) { IModuleResource r = delta[i].getModuleResource(); IModuleResourceDelta[] children = delta[i].getAffectedChildren(); IModuleResource[] childrenRes = null; if( children != null ) { childrenRes = getAllResources(children, kind, depthFirst); } else { childrenRes = new IModuleResource[0]; } if( depthFirst ) { list.addAll(Arrays.asList(childrenRes)); if( delta[i].getKind() == kind) { list.add(r); } } else { if( delta[i].getKind() == kind) { list.add(r); } list.addAll(Arrays.asList(childrenRes)); } } return (IModuleResource[]) list.toArray(new IModuleResource[list.size()]); }

Target:
private IModuleResource[] getAllResources(IModuleResourceDelta[] delta, int kind, boolean depthFirst) { if( delta == null ) return new IModuleResource[0]; List<IModuleResource> list = new ArrayList<>(); for( int i = 0; i < delta.length; i++ ) { IModuleResource r = delta[i].getModuleResource(); IModuleResourceDelta[] children = delta[i].getAffectedChildren(); IModuleResource[] childrenRes; if( children != null ) { childrenRes = getAllResources(children, kind, depthFirst); } else { childrenRes = new IModuleResource[0]; } if( depthFirst ) { list.addAll(Arrays.asList(childrenRes)); if( delta[i].getKind() == kind) { list.add(r); } } else { if( delta[i].getKind() == kind) { list.add(r); } list.addAll(Arrays.asList(childrenRes)); } } return list.toArray(new IModuleResource[list.size()]); }
Source:
public void testIscsiLunCanBeAdded() { LunDisk disk = createISCSILunDisk(); command.getParameters().setDiskInfo(disk); DiskVmElement dve = new DiskVmElement(); command.getParameters().getDiskVmElement().setUsingScsiReservation(false); assertTrue("checkIfLunDiskCanBeAdded() failed for valid iscsi lun", command.checkIfLunDiskCanBeAdded(spyDiskValidator(disk))); }

Target:
public void testIscsiLunCanBeAdded() { LunDisk disk = createISCSILunDisk(); command.getParameters().setDiskInfo(disk); command.getParameters().getDiskVmElement().setUsingScsiReservation(false); assertTrue("checkIfLunDiskCanBeAdded() failed for valid iscsi lun", command.checkIfLunDiskCanBeAdded(spyDiskValidator(disk))); }
Source:
public final <T> T build(Class<T> serviceClass, UserAgent userAgent) { ObjectMapper objectMapper = getObjectMapper(); ObjectMapper cborObjectMapper = getCborObjectMapper(); Preconditions.checkNotNull(hostEventsSink, "hostEventsSink must be set"); okhttp3.OkHttpClient okHttpClient = OkHttpClients.create(config, userAgent, hostEventsSink, serviceClass); return Feign.builder() .contract(createContract()) .encoder( new ConjureInputStreamDelegateEncoder( new ConjureTextDelegateEncoder( new ConjureCborDelegateEncoder( cborObjectMapper, new JacksonEncoder(objectMapper))))) .decoder(createDecoder(objectMapper, cborObjectMapper)) .errorDecoder(QosErrorDecoder.INSTANCE) .client(new OkHttpClient(okHttpClient)) .options(createRequestOptions()) .logLevel(Logger.Level.NONE) .retryer(new Retryer.Default(0, 0, 1)) .target(serviceClass, primaryUri); }

Target:
public final <T> T build(Class<T> serviceClass, UserAgent userAgent) { ObjectMapper objectMapper = getObjectMapper(); ObjectMapper cborObjectMapper = getCborObjectMapper(); Preconditions.checkNotNull(hostEventsSink, "hostEventsSink must be set"); okhttp3.OkHttpClient okHttpClient = OkHttpClients.create(config, userAgent, hostEventsSink, serviceClass); return Feign.builder() .contract(createContract()) .encoder( new InputStreamDelegateEncoder( new TextDelegateEncoder( new CborDelegateEncoder( cborObjectMapper, new JacksonEncoder(objectMapper))))) .decoder(createDecoder(objectMapper, cborObjectMapper)) .errorDecoder(new QosErrorDecoder(new ErrorDecoder.Default())) .client(new OkHttpClient(okHttpClient)) .options(createRequestOptions()) .logLevel(Logger.Level.NONE) .retryer(new Retryer.Default(0, 0, 1)) .target(serviceClass, primaryUri); }
Source:
private OffsetsMaps fetchTopicPartitionsMetadata(List<TopicPartition> topicPartitions) { Map<SystemStreamPartition, String> oldestOffsets = new HashMap<>(); Map<SystemStreamPartition, String> newestOffsets = new HashMap<>(); Map<SystemStreamPartition, String> upcomingOffsets = new HashMap<>(); Map<TopicPartition, Long> oldestOffsetsWithLong = metadataConsumer.beginningOffsets(topicPartitions); LOG.debug("Kafka-fetched beginningOffsets: {}", oldestOffsetsWithLong); Map<TopicPartition, Long> upcomingOffsetsWithLong = metadataConsumer.endOffsets(topicPartitions); LOG.debug("Kafka-fetched endOffsets: {}", upcomingOffsetsWithLong); oldestOffsetsWithLong.forEach((topicPartition, offset) -> { oldestOffsets.put(createSystemStreamPartition(topicPartition), String.valueOf(offset)); }); upcomingOffsetsWithLong.forEach((topicPartition, offset) -> { upcomingOffsets.put(createSystemStreamPartition(topicPartition), String.valueOf(offset)); if (offset <= 0) { LOG.debug( "Empty Kafka topic partition with upcoming offset {}. Skipping newest offset and setting oldest offset to 0 to consume from beginning", topicPartition, offset); oldestOffsets.put(createSystemStreamPartition(topicPartition), "0"); } else { newestOffsets.put(createSystemStreamPartition(topicPartition), String.valueOf(offset - 1)); } }); return new OffsetsMaps(oldestOffsets, newestOffsets, upcomingOffsets); }

Target:
private OffsetsMaps fetchTopicPartitionsMetadata(List<TopicPartition> topicPartitions) { Map<SystemStreamPartition, String> oldestOffsets = new HashMap<>(); Map<SystemStreamPartition, String> newestOffsets = new HashMap<>(); Map<SystemStreamPartition, String> upcomingOffsets = new HashMap<>(); Map<TopicPartition, Long> oldestOffsetsWithLong = metadataConsumer.beginningOffsets(topicPartitions); LOG.debug("Kafka-fetched beginningOffsets: {}", oldestOffsetsWithLong); Map<TopicPartition, Long> upcomingOffsetsWithLong = metadataConsumer.endOffsets(topicPartitions); LOG.debug("Kafka-fetched endOffsets: {}", upcomingOffsetsWithLong); oldestOffsetsWithLong.forEach((topicPartition, offset) -> { oldestOffsets.put(createSystemStreamPartition(topicPartition), String.valueOf(offset)); }); upcomingOffsetsWithLong.forEach((topicPartition, offset) -> { upcomingOffsets.put(createSystemStreamPartition(topicPartition), String.valueOf(offset)); if (offset <= 0) { LOG.warn( "Empty Kafka topic partition with upcoming offset {}. Skipping newest offset and setting oldest offset to 0 to consume from beginning", topicPartition, offset); oldestOffsets.put(createSystemStreamPartition(topicPartition), "0"); } else { newestOffsets.put(createSystemStreamPartition(topicPartition), String.valueOf(offset - 1)); } }); return new OffsetsMaps(oldestOffsets, newestOffsets, upcomingOffsets); }
Source:
private boolean employeeIdIsValid(ConcurRequestExtractRequestDetailFileLine detailFileLine) { if (StringUtils.isEmpty(detailFileLine.getEmployeeId())) { detailFileLine.getValidationResult().addMessage(getConfigurationService().getPropertyValueAsString(ConcurKeyConstants.CONCUR_REQUEST_EXTRACT_EMPLOYEE_ID_NULL_OR_BLANK)); return false; } else { boolean validPerson = getConcurPersonValidationService().validPerson(detailFileLine.getEmployeeId()); if(validPerson) { return true; } else { detailFileLine.getValidationResult().addMessage(getConfigurationService().getPropertyValueAsString(ConcurKeyConstants.CONCUR_EMPLOYEE_ID_NOT_FOUND_IN_KFS)); return false; } } }

Target:
private boolean employeeIdIsValid(ConcurRequestExtractRequestDetailFileLine detailFileLine) { if (StringUtils.isEmpty(detailFileLine.getEmployeeId())) { detailFileLine.getValidationResult().addMessage(getConfigurationService().getPropertyValueAsString(ConcurKeyConstants.CONCUR_REQUEST_EXTRACT_EMPLOYEE_ID_NULL_OR_BLANK)); return false; } else { boolean validPerson = getConcurEmployeeInfoValidationService().validPerson(detailFileLine.getEmployeeId()); if(validPerson) { return true; } else { detailFileLine.getValidationResult().addMessage(getConfigurationService().getPropertyValueAsString(ConcurKeyConstants.CONCUR_EMPLOYEE_ID_NOT_FOUND_IN_KFS)); return false; } } }
Source:
protected void startWatchers() { int watcherId = manager.registerByMatcher( folderMatcher(), s -> report(s, FileChangeType.Created), s -> report(s, FileChangeType.Changed), s -> report(s, FileChangeType.Deleted)); watcherIds.add(watcherId); eventService.subscribe(this::onServerInitialized, LanguageServerInitializedEvent.class); eventService.subscribe(this::onProjectUpdated, ProjectUpdatedEvent.class); }

Target:
protected void startWatchers() { int watcherId = manager.registerByMatcher( folderMatcher(), s -> report(s, FileChangeType.Created), s -> {}, s -> report(s, FileChangeType.Deleted)); watcherIds.add(watcherId); eventService.subscribe(this::onProjectUpdated, ProjectUpdatedEvent.class); }
Source:
protected ViewPrototype doGetPrototypeFor(PapyrusDiagram diagramKind) { String commandClassName = diagramKind.getCreationCommandClass(); if (commandClassName != null) { Class<?> creationCommandClass = null; URI uri = diagramKind.eResource().getURI(); if (uri.isPlatformPlugin()) { String bundleName = uri.segment(1); Bundle bundle = Platform.getBundle(bundleName); try { creationCommandClass = bundle.loadClass(diagramKind.getCreationCommandClass()); } catch (ClassNotFoundException e) { Activator.log.error(e); } } else { Activator.log.error(new IllegalArgumentException( String.format("URI %s for diagramKind %s is invalid. It must be a platform URI", uri, diagramKind.getName()))); } if (creationCommandClass != null) { AbstractPapyrusGmfCreateDiagramCommandHandler command; try { command = (AbstractPapyrusGmfCreateDiagramCommandHandler) creationCommandClass.newInstance(); } catch (Exception e) { Activator.log.error(e); return null; } String language = diagramKind.getLanguage().getId(); return new DiagramPrototype(diagramKind, language, command); } } return null; }

Target:
protected ViewPrototype doGetPrototypeFor(PapyrusDiagram diagramKind) { String commandClassName = diagramKind.getCreationCommandClass(); if (commandClassName != null) { Class<?> creationCommandClass = ClassLoaderHelper.loadClass(commandClassName); if (creationCommandClass != null) { AbstractPapyrusGmfCreateDiagramCommandHandler command; try { command = (AbstractPapyrusGmfCreateDiagramCommandHandler) creationCommandClass.newInstance(); } catch (Exception e) { Activator.log.error(e); return null; } String language = diagramKind.getLanguage().getId(); return new DiagramPrototype(diagramKind, language, command); } else { Activator.log.error(new ClassNotFoundException( String.format("Can not load creation command class %s for diagramKind %s.", commandClassName, diagramKind.getName()))); } } return null; }
Source:
private String getBodyAsMessage(ClientResponseContext responseContext) { if (responseContext.hasEntity()) { try (InputStream entityStream = responseContext.getEntityStream()) { Charset charset = null; MediaType mediaType = responseContext.getMediaType(); if (mediaType != null) { String charsetName = mediaType.getParameters().get("charset"); if (charsetName != null) { try { charset = Charset.forName(charsetName); } catch (Exception ignored) { } } } if (charset == null) { charset = Charset.defaultCharset(); } String message = IOUtils.toString(entityStream, charset); if (MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(message); if (node != null) { JsonNode messageNode = node.get("message"); if (messageNode != null && messageNode.isTextual()) { message = messageNode.textValue(); } } } return message; } catch (Exception ignored) { } } return null; }

Target:
private String getBodyAsMessage(ClientResponseContext responseContext) { if (responseContext.hasEntity()) { try (InputStream entityStream = responseContext.getEntityStream()) { Charset charset = null; MediaType mediaType = responseContext.getMediaType(); if (mediaType != null) { String charsetName = mediaType.getParameters().get("charset"); if (charsetName != null) { try { charset = Charset.forName(charsetName); } catch (Exception ignored) { } } } if (charset == null) { charset = Charset.defaultCharset(); } String message = IOUtils.toString(entityStream, charset); if (MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) { try { JsonNode node = new ObjectMapper().readTree(message); if (node != null) { JsonNode messageNode = node.get("message"); if (messageNode != null && messageNode.isTextual()) { message = messageNode.textValue(); } } } catch (IOException e) { LOG.debug("Failed to unwrap error message: {}", e.getMessage(), e); } } return message; } catch (Exception ignored) { } } return null; }
Source:
public void testDatabaseWithComplexTree() throws Exception { final String sql = "INSERT INTO revs (doc_id, parent, current, deleted, available, revid, json) SELECT doc_id, parent, current, deleted, available, revid, json FROM revs where revs.revid = ?"; final String updateCurrent = "UPDATE revs SET current=0 where sequence=2"; ((DatastoreImpl)ds).runOnDbQueue(new SQLQueueCallable<Void>() { @Override public Void call(SQLDatabase db) throws Exception { db.execSQL(sql, new String[]{rootRevision.getRevision()}); db.execSQL(updateCurrent, new String[]{}); return null; } }).get(); DocumentRevision rev = new DocumentRevision(rootRevision.id, "1-abc"); rev.setBody(rootRevision.getBody()); ((DatastoreImpl) ds).forceInsert(rev, "1-abc"); runMigration(); int count = revisionCount(); Assert.assertThat(count, is(2)); }

Target:
public void testDatabaseWithComplexTree() throws Exception { final String updateCurrent = "UPDATE revs SET current=0 where sequence=2"; ds.runOnDbQueue(new SQLQueueCallable<Void>() { @Override public Void call(SQLDatabase db) throws Exception { db.execSQL(duplicateRevs, new String[]{rootRevision.getRevision()}); db.execSQL(updateCurrent, new String[]{}); return null; } }).get(); DocumentRevision rev = new DocumentRevision(rootRevision.id, "1-abc"); rev.setBody(rootRevision.getBody()); ((DatastoreImpl) ds).forceInsert(rev, "1-abc"); runMigration(); int count = revisionCount(); Assert.assertThat("Only 2 revisions should be present in the database.", count, is(2)); Assert.assertThat(getRevs(), containsInAnyOrder("1-abc", rootRevision.revision)); }