auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected int executeTimestampCommand(AtlasDbServices services) { KeyValueService kvs = services.getKeyValueService(); long backupTimestamp = timestamp; ClosableIterator<RowResult<Value>> range = kvs.getRange( TransactionConstants.TRANSACTION_TABLE, RangeRequest.all(), Long.MAX_VALUE); Multimap<Cell, Long> toDelete = HashMultimap.create(); while (range.hasNext()) { RowResult<Value> row = range.next(); byte[] rowName = row.getRowName(); long startTs = TransactionConstants.getTimestampForValue(rowName); Value value; try { value = row.getOnlyColumnValue(); } catch (IllegalStateException e){ printer.error("Found a row in the transactions table that didn't have 1 and only 1 column value: start={}", startTs); continue; } long commitTs = TransactionConstants.getTimestampForValue(value.getContents()); if (commitTs <= backupTimestamp) { continue; } printer.info("Found and cleaning possibly inconsistent transaction: [start={}, commit={}]", startTs, commitTs); Cell key = Cell.create(rowName, TransactionConstants.COMMIT_TS_COLUMN); toDelete.put(key, value.getTimestamp()); } if (!toDelete.isEmpty()) { kvs.delete(TransactionConstants.TRANSACTION_TABLE, toDelete); printer.info("Delete completed."); } else { printer.info("Found no transactions after the given timestamp to delete."); } return 0; }

Target:
protected int executeTimestampCommand(AtlasDbServices services) { KeyValueService kvs = services.getKeyValueService(); ClosableIterator<RowResult<Value>> range = kvs.getRange( TransactionConstants.TRANSACTION_TABLE, RangeRequest.all(), Long.MAX_VALUE); Multimap<Cell, Long> toDelete = HashMultimap.create(); while (range.hasNext()) { RowResult<Value> row = range.next(); byte[] rowName = row.getRowName(); long startTs = TransactionConstants.getTimestampForValue(rowName); Value value; try { value = row.getOnlyColumnValue(); } catch (IllegalStateException e){ printer.error("Found a row in the transactions table that didn't have 1 and only 1 column value: start={}", startTs); continue; } long commitTs = TransactionConstants.getTimestampForValue(value.getContents()); if (commitTs <= timestamp) { continue; } printer.info("Found and cleaning possibly inconsistent transaction: [start={}, commit={}]", startTs, commitTs); Cell key = Cell.create(rowName, TransactionConstants.COMMIT_TS_COLUMN); toDelete.put(key, value.getTimestamp()); } if (!toDelete.isEmpty()) { kvs.delete(TransactionConstants.TRANSACTION_TABLE, toDelete); printer.info("Delete completed."); } else { printer.info("Found no transactions after the given timestamp to delete."); } return 0; }
Source:
private static void verifyLength(int suppliedLength, int availableLength) { if (suppliedLength > availableLength) { throw new RuntimeException(String.format("Length parsed from RLP (%s bytes) is greater " + "than remaining size of data (%s bytes)", suppliedLength, availableLength)); } }

Target:
private static void verifyLength(int suppliedLength, int availableLength) { if (suppliedLength > availableLength) { throw new RuntimeException(String.format("Length parsed from RLP (%s bytes) is greater " + "than possible size of data (%s bytes)", suppliedLength, availableLength)); } }
Source:
protected String doInBackground(String... api_path) { try { Response response = request.execute(api_path[0], api_path[1]); return response.body().string(); } catch (SocketTimeoutException e){ ZLog.logException(e); } catch (IOException e) { handleError(e); } catch (Exception e) { handleHTTPError(e); } return ""; }

Target:
protected String doInBackground(String... api_path) { try { Response response = request.execute(); String responseString = response.body().string(); if (response.isSuccessful()) { Log.d("OkHTTP200", responseString); return responseString; } else { Log.e("OkHTTPError", "Code:" + response.code()); Log.e("OkHTTPError", "Message:" + responseString); this.cancel(true); return responseString; } } catch (Exception e) { ZLog.logException(e); this.cancel(true); } return ""; }
Source:
public void updated(Dictionary<String, ?> properties) throws ConfigurationException { if (properties == null) { logger.warn("no configuration found"); } else { String read = (String) properties.get(KEY_READ_CALENDARS); if (read != null) { for (String value : read.split(",")) { this.readCalendars.add(value.trim()); } } } }

Target:
public void updated(Dictionary<String, ?> properties) throws ConfigurationException { if (properties != null) { logger.debug("reading configuration data..."); String read = (String) properties.get(KEY_READ_CALENDARS); if (read != null) { for (String value : read.split(",")) { this.readCalendars.add(value.trim()); } } this.reloadCurrentLoadedEvents(); } }
Source:
static <T> java.util.List<T> asJava(LinearSeq<T> seq) { return new SeqAsJavaList<>(seq); }

Target:
static <T> java.util.List<T> asJava(LinearSeq<T> seq) { return new SeqAsJavaList<>(seq, LinearSeqListIterator::new); }
Source:
public List<ColumnMetadata> getColumnsMetadata() { return new ArrayList<>(columnsMetadata); }

Target:
public List<ColumnMetadata> getColumnsMetadata() { return ImmutableList.copyOf(columnsMetadata); }
Source:
private static void mergeParentPatronAcls(PID parentPid, Resource destResc, Property everyoneRole, Property authRole) { Model parentUnitModel = unitPatronAccessCache.get(parentPid); if (parentUnitModel != null) { Resource parentUnitResc = parentUnitModel.getResource(parentPid.getRepositoryPath()); if (!destResc.hasProperty(CdrAcl.embargoUntil) && parentUnitResc.hasProperty(CdrAcl.embargoUntil)) { String embargoDate = formatEmbargoDate(parentUnitResc.getProperty( CdrAcl.embargoUntil).getLiteral().getString()); Literal embargoLiteral = parentUnitModel.createTypedLiteral(embargoDate, XSDDatatype.XSDdateTime); destResc.addLiteral(CdrAcl.embargoUntil, embargoLiteral); } if (everyoneRole == null) { StmtIterator it = parentUnitModel.listStatements(parentUnitResc, null, PUBLIC_PRINC); if (it.hasNext()) { Statement roleStmt = it.next(); destResc.addLiteral(roleStmt.getPredicate(), PUBLIC_PRINC); it.close(); } } if (authRole == null) { StmtIterator it = parentUnitModel.listStatements(parentUnitResc, null, AUTHENTICATED_PRINC); if (it.hasNext()) { Statement roleStmt = it.next(); destResc.addLiteral(roleStmt.getPredicate(), AUTHENTICATED_PRINC); it.close(); } } } }

Target:
private static void mergeParentPatronAcls(PID parentPid, Resource destResc, Property everyoneRole, Property authRole) { Model parentUnitModel = unitPatronAccessCache.get(parentPid); if (parentUnitModel != null) { Resource parentUnitResc = parentUnitModel.getResource(parentPid.getRepositoryPath()); if (!destResc.hasProperty(CdrAcl.embargoUntil) && parentUnitResc.hasProperty(CdrAcl.embargoUntil)) { String embargoDate = parentUnitResc.getProperty( CdrAcl.embargoUntil).getLiteral().getString(); Literal embargoLiteral = parentUnitModel.createTypedLiteral(embargoDate, XSDDatatype.XSDdateTime); destResc.addLiteral(CdrAcl.embargoUntil, embargoLiteral); } if (everyoneRole == null) { StmtIterator it = parentUnitModel.listStatements(parentUnitResc, null, PUBLIC_PRINC); if (it.hasNext()) { Statement roleStmt = it.next(); destResc.addLiteral(roleStmt.getPredicate(), PUBLIC_PRINC); it.close(); } } if (authRole == null) { StmtIterator it = parentUnitModel.listStatements(parentUnitResc, null, AUTHENTICATED_PRINC); if (it.hasNext()) { Statement roleStmt = it.next(); destResc.addLiteral(roleStmt.getPredicate(), AUTHENTICATED_PRINC); it.close(); } } } }
Source:
public List<Object[]> executeStatement(String hql) { return executeStatementWithCommandShellEmulation(hql); }

Target:
public List<Object[]> executeStatement(String hql) { List<HiveQueryLanguageStatement> hsqlStatements = statementFactory.newInstanceForStatement(hql); return executeStatementsWithCommandShellEmulation(hsqlStatements); }
Source:
public void deleteNamespacedJob(final String queue, final String job, boolean forceDelete) { WorkflowConfig jobQueueConfig = TaskUtil.getWorkflowConfig(_accessor, queue); if (forceDelete) { LOG.info("Forcefully removing job: from queue: {}", job, queue); if (!TaskUtil.removeJob(_accessor, _propertyStore, job)) { LOG.info("Failed to delete job: from queue: {}", job, queue); throw new HelixException("Failed to delete job: " + job + " from queue: " + queue); } return; } if (jobQueueConfig == null) { throw new IllegalArgumentException( String.format("JobQueue %s's config is not found!", queue)); } if (!jobQueueConfig.isJobQueue()) { throw new IllegalArgumentException(String.format("%s is not a queue!", queue)); } boolean isRecurringWorkflow = (jobQueueConfig.getScheduleConfig() != null && jobQueueConfig.getScheduleConfig().isRecurring()); String denamespacedJob = TaskUtil.getDenamespacedJobName(queue, job); if (isRecurringWorkflow) { WorkflowContext wCtx = TaskUtil.getWorkflowContext(_propertyStore, queue); String lastScheduledQueue = null; if (wCtx != null) { lastScheduledQueue = wCtx.getLastScheduledSingleWorkflow(); } if (lastScheduledQueue != null) { WorkflowConfig lastWorkflowCfg = TaskUtil.getWorkflowConfig(_accessor, lastScheduledQueue); if (lastWorkflowCfg != null) { deleteJobFromQueue(lastScheduledQueue, denamespacedJob); } } } deleteJobFromQueue(queue, denamespacedJob); }

Target:
public void deleteNamespacedJob(final String queue, final String job, boolean forceDelete) { WorkflowConfig jobQueueConfig = TaskUtil.getWorkflowConfig(_accessor, queue); boolean isRecurringWorkflow; if (forceDelete) { LOG.info("Forcefully removing job: from queue: {}", job, queue); if (!TaskUtil.removeJob(_accessor, _propertyStore, job)) { LOG.info("Failed to delete job: from queue: {}", job, queue); throw new HelixException("Failed to delete job: " + job + " from queue: " + queue); } if (jobQueueConfig != null) { isRecurringWorkflow = jobQueueConfig.getScheduleConfig() != null && jobQueueConfig.getScheduleConfig().isRecurring(); if (isRecurringWorkflow) { deleteJobFromLastScheduledQueue(queue, TaskUtil.getDenamespacedJobName(queue, job)); } } return; } if (jobQueueConfig == null) { throw new IllegalArgumentException( String.format("JobQueue %s's config is not found!", queue)); } if (!jobQueueConfig.isJobQueue()) { throw new IllegalArgumentException(String.format("%s is not a queue!", queue)); } isRecurringWorkflow = jobQueueConfig.getScheduleConfig() != null && jobQueueConfig.getScheduleConfig().isRecurring(); String denamespacedJob = TaskUtil.getDenamespacedJobName(queue, job); if (isRecurringWorkflow) { deleteJobFromLastScheduledQueue(queue, denamespacedJob); } deleteJobFromQueue(queue, denamespacedJob); }
Source:
public double getAttributeAsDouble(final String key, final double defaultValue) { final Object x = getAttribute(key); if ( x == null ) return defaultValue; if ( x instanceof Double ) return (Double)x; if ( x instanceof Integer ) return (Integer)x; if ( !( x instanceof String ) ) throw new IllegalArgumentException( "Cannot get attribute(key=\"" + key + ") as a double because it's not a Double, a Integer or a String. Class = " + x.getClass()); try { return Double.parseDouble((String)x); } catch (final NumberFormatException err) { throw new IllegalArgumentException( "Cannot convert attribute(key=\"" + key + ") = "+ x + " as a double.", err); } }

Target:
public double getAttributeAsDouble(final String key, final double defaultValue) { Object x = getAttribute(key); if ( x == null ) return defaultValue; if ( x instanceof Double ) return (Double)x; if ( x instanceof Integer ) return (Integer)x; return Double.valueOf((String)x); }
Source:
private void performDiskUpdate(final boolean unlockImage) { if (shouldPerformMetadataUpdate()) { updateMetaDataDescription((DiskImage) getNewDisk()); } final Disk disk = getDiskDao().get(getParameters().getDiskId()); applyUserChanges(disk); TransactionSupport.executeInNewTransaction(new TransactionMethod<Object>() { @Override public Object runInTransaction() { getVmStaticDAO().incrementDbGeneration(getVm().getId()); updateDeviceProperties(); getBaseDiskDao().update(disk); if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { DiskImage diskImage = (DiskImage) disk; diskImage.setQuotaId(getQuotaId()); if (unlockImage && diskImage.getImageStatus() == ImageStatus.LOCKED) { diskImage.setImageStatus(ImageStatus.OK); } getImageDao().update(diskImage.getImage()); updateQuota(diskImage); updateDiskProfile(); } else if (disk.getDiskStorageType() == DiskStorageType.LUN) { updateLunProperties((LunDisk)getNewDisk()); } else { log.error("Unexpected disk storage type ..."); } clearDeviceAddressIfNeeded(); reloadDisks(); updateBootOrder(); setSucceeded(true); return null; } private void updateDeviceProperties() { if (updateReadOnlyRequested()) { vmDeviceForVm.setIsReadOnly(getNewDisk().getReadOnly()); getVmDeviceDao().update(vmDeviceForVm); } } private void updateLunProperties(LunDisk lunDisk) { vmDeviceForVm.setUsingScsiReservation(lunDisk.isUsingScsiReservation()); getVmDeviceDao().update(vmDeviceForVm); } private void clearDeviceAddressIfNeeded() { if (getOldDisk().getDiskInterface() != getNewDisk().getDiskInterface()) { getVmDeviceDao().clearDeviceAddress(getOldDisk().getId()); } } }); }

Target:
private void performDiskUpdate(final boolean unlockImage) { if (shouldPerformMetadataUpdate()) { updateMetaDataDescription((DiskImage) getNewDisk()); } final Disk disk = getDiskDao().get(getParameters().getDiskId()); applyUserChanges(disk); TransactionSupport.executeInNewTransaction(new TransactionMethod<Object>() { @Override public Object runInTransaction() { getVmStaticDAO().incrementDbGeneration(getVm().getId()); updateDeviceProperties(); getBaseDiskDao().update(disk); if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { DiskImage diskImage = (DiskImage) disk; diskImage.setQuotaId(getQuotaId()); if (unlockImage && diskImage.getImageStatus() == ImageStatus.LOCKED) { diskImage.setImageStatus(ImageStatus.OK); } getImageDao().update(diskImage.getImage()); updateQuota(diskImage); updateDiskProfile(); } else if (disk.getDiskStorageType() == DiskStorageType.LUN) { updateLunProperties((LunDisk)getNewDisk()); } clearDeviceAddressIfNeeded(); reloadDisks(); updateBootOrder(); setSucceeded(true); return null; } private void updateDeviceProperties() { if (updateReadOnlyRequested()) { vmDeviceForVm.setIsReadOnly(getNewDisk().getReadOnly()); getVmDeviceDao().update(vmDeviceForVm); } } private void updateLunProperties(LunDisk lunDisk) { vmDeviceForVm.setUsingScsiReservation(lunDisk.isUsingScsiReservation()); getVmDeviceDao().update(vmDeviceForVm); } private void clearDeviceAddressIfNeeded() { if (getOldDisk().getDiskInterface() != getNewDisk().getDiskInterface()) { getVmDeviceDao().clearDeviceAddress(getOldDisk().getId()); } } }); }
Source:
private void registerValidationListener() { issueStore = getEditorInjector().getInstance(IValidationIssueStore.class); issueStore.connect(getDiagram().eResource()); validationListener = getEditorInjector().getInstance(LiveValidationListener.class); validationListener.setResource(getDiagram().eResource()); validationListener.setValidationIssueProcessor(issueStore); getEditingDomain().addResourceSetListener(validationListener); validationListener.scheduleValidation(); }

Target:
protected void registerValidationListener() { issueStore = getEditorInjector().getInstance(IValidationIssueStore.class); issueStore.connect(getDiagram().eResource()); validationListener = getEditorInjector().getInstance(LiveValidationListener.class); validationListener.setResource(getDiagram().eResource()); validationListener.setValidationIssueProcessor(issueStore); getEditingDomain().addResourceSetListener(validationListener); validationListener.scheduleValidation(); }
Source:
public BlockSortedField updateSortedField(long blockId, LRUSortedField oldValue) { long clockValue = 0; if (oldValue != null) { clockValue = mLRUClock.incrementAndGet(); } if (LOG.isDebugEnabled()) { LOG.debug("LRU update for Block: {}. Clock: {}", blockId, clockValue); } return new LRUSortedField(clockValue); }

Target:
public BlockSortedField updateSortedField(long blockId, LRUSortedField oldValue) { long clockValue = mLRUClock.incrementAndGet(); if (LOG.isDebugEnabled()) { LOG.debug("LRU update for Block: {}. Clock: {}", blockId, clockValue); } return new LRUSortedField(clockValue); }
Source:
public byte[] getCacheKey() { return new CacheKeyBuilder( cacheTypeId ).appendString(name).appendString(fieldName).appendInt(k).build(); }

Target:
public byte[] getCacheKey() { return new CacheKeyBuilder( cacheTypeId ).appendString(fieldName).appendInt(k).appendBoolean(compress).build(); }
Source:
public void delete(RuleKey ruleKey) { try (DbSession dbSession = dbClient.openSession(false)) { RuleDefinitionDto rule = dbClient.ruleDao().selectOrFailDefinitionByKey(dbSession, ruleKey); if (!rule.isCustomRule()) { throw new IllegalArgumentException("Only custom rules can be deleted"); } if (rule.isCustomRule()) { ruleActivator.deactivateOfAllOrganizations(dbSession, rule); } rule.setStatus(RuleStatus.REMOVED); rule.setUpdatedAt(system2.now()); dbClient.ruleDao().update(dbSession, rule); dbSession.commit(); ruleIndexer.indexRuleDefinition(ruleKey); } }

Target:
public void delete(RuleKey ruleKey) { try (DbSession dbSession = dbClient.openSession(false)) { RuleDefinitionDto rule = dbClient.ruleDao().selectOrFailDefinitionByKey(dbSession, ruleKey); checkArgument(rule.isCustomRule(), "Rule '%s' cannot be deleted because it is not a custom rule", rule.getKey().toString()); if (rule.isCustomRule()) { ruleActivator.deactivateOfAllOrganizations(dbSession, rule); } rule.setStatus(RuleStatus.REMOVED); rule.setUpdatedAt(system2.now()); dbClient.ruleDao().update(dbSession, rule); dbSession.commit(); ruleIndexer.indexRuleDefinition(ruleKey); } }
Source:
protected void createLayout(Context context) { adapter = new SelectOneListAdapter(items, selectedValue, this, numColumns, this.getFormEntryPrompt(), this.getReferenceManager(), this.getAnswerFontSize(), this.getAudioHelper(), getPlayColor(getFormEntryPrompt(), themeUtils), this.getContext(), autoAdvance); if (items != null) { RecyclerView recyclerView = setUpRecyclerView(); recyclerView.setAdapter(adapter); answerLayout.addView(recyclerView); adjustRecyclerViewSize(adapter, recyclerView); Resources resources = context.getResources(); int marginStandard = dpFromPx(context, resources.getDimensionPixelSize(R.dimen.margin_standard)); int margin = marginStandard - FIELD_HORIZONTAL_MARGIN_MODIFIER; addAnswerView(answerLayout, margin); } }

Target:
protected void createLayout(Context context) { adapter = new SelectOneListAdapter(items, selectedValue, this, numColumns, this.getFormEntryPrompt(), this.getReferenceManager(), this.getAnswerFontSize(), this.getAudioHelper(), getPlayColor(getFormEntryPrompt(), themeUtils), this.getContext(), autoAdvance); if (items != null) { RecyclerView recyclerView = setUpRecyclerView(); recyclerView.setAdapter(adapter); answerLayout.addView(recyclerView); adjustRecyclerViewSize(adapter, recyclerView); addAnswerView(answerLayout); } }
Source:
protected Type _deserialize(String value, DeserializationContext context) { Type type = types.get(value.toLowerCase(ENGLISH)); if (type == null) { throw new IllegalArgumentException(String.valueOf("Unknown type " + value)); } return type; }

Target:
protected Type _deserialize(String value, DeserializationContext context) { Type type = types.get(value.toLowerCase(ENGLISH)); return requireNonNull(type, "Unknown type " + value); }
Source:
public void shouldShowCorrectTitle_whenFormIsLoaded() { when(formSaveViewModel.getFormName()).thenReturn("blah"); dialogFragment.show(fragmentManager, "TAG"); AlertDialog dialog = (AlertDialog) ShadowDialog.getLatestDialog(); String title = formSaveViewModel.getFormName() == null ? activity.getString(R.string.no_form_loaded) : formSaveViewModel.getFormName(); TextView dialogTitle = dialog.findViewById(R.id.alertTitle); assertThat(dialogTitle.getText().toString(), equalTo(title)); }

Target:
public void shouldShowCorrectTitle_whenFormIsLoaded() { when(formSaveViewModel.getFormName()).thenReturn("blah"); dialogFragment.show(fragmentManager, "TAG"); AlertDialog dialog = (AlertDialog) ShadowDialog.getLatestDialog(); TextView dialogTitle = dialog.findViewById(R.id.alertTitle); assertThat(dialogTitle.getText().toString(), equalTo("blah")); }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } StoragePool other = (StoragePool) obj; return (ObjectUtils.objectsEqual(id, other.id) && ObjectUtils.objectsEqual(LVER, other.LVER) && ObjectUtils.objectsEqual(description, other.description) && ObjectUtils.objectsEqual(comment, other.comment) && ObjectUtils.objectsEqual(getcompatibility_version(), other.getcompatibility_version()) && masterDomainVersion == other.masterDomainVersion && ObjectUtils.objectsEqual(name, other.name) && recovery_mode == other.recovery_mode && ObjectUtils.objectsEqual(spmVdsId, other.spmVdsId) && status == other.status && ObjectUtils.objectsEqual(storagePoolFormatType, other.storagePoolFormatType) && quotaEnforcementType == other.quotaEnforcementType); }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } StoragePool other = (StoragePool) obj; return (ObjectUtils.objectsEqual(id, other.id) && ObjectUtils.objectsEqual(LVER, other.LVER) && ObjectUtils.objectsEqual(description, other.description) && ObjectUtils.objectsEqual(comment, other.comment) && ObjectUtils.objectsEqual(getcompatibility_version(), other.getcompatibility_version()) && masterDomainVersion == other.masterDomainVersion && ObjectUtils.objectsEqual(name, other.name) && recovery_mode == other.recovery_mode && ObjectUtils.objectsEqual(spmVdsId, other.spmVdsId) && status == other.status && isLocal == other.isLocal && ObjectUtils.objectsEqual(storagePoolFormatType, other.storagePoolFormatType) && quotaEnforcementType == other.quotaEnforcementType); }
Source:
public void testBlockUseHostCpuWithPPCArch() { final int osId = 2; mockConfig(); AddVmCommand<AddVmParameters> cmd = setupCanAddPpcTest(); cmd.setEffectiveCompatibilityVersion(Version.v4_0); doReturn(Collections.<DiskImageBase> emptyList()).when(cmd).getImagesToCheckDestinationStorageDomains(); Cluster cluster = createPpcCluster(); when(clusterDao.get(any(Guid.class))).thenReturn(cluster); doReturn(clusterDao).when(dbFacade).getClusterDao(); doReturn(true).when(cmd).areParametersLegal(Collections.<String> emptyList()); doReturn(true).when(cmd).validateAddVmCommand(); doReturn(true).when(cmd).isVmNameValidLength(any(VM.class)); when(osRepository.getArchitectureFromOS(any(Integer.class))).thenReturn(ArchitectureType.ppc64); cmd.getParameters().getVm().setClusterArch(ArchitectureType.ppc64); cmd.getParameters().getVm().setUseHostCpuFlags(true); cmd.getParameters().getVm().setMigrationSupport(MigrationSupport.PINNED_TO_HOST); cmd.getParameters().getVm().setClusterId(cluster.getId()); cmd.getParameters().getVm().setVmOs(osId); ValidateTestUtils.runAndAssertValidateFailure (cmd, EngineMessage.USE_HOST_CPU_REQUESTED_ON_UNSUPPORTED_ARCH); }

Target:
public void testBlockUseHostCpuWithPPCArch() { mockConfig(); AddVmCommand<AddVmParameters> cmd = setupCanAddPpcTest(); cmd.setEffectiveCompatibilityVersion(Version.v4_0); doReturn(Collections.<DiskImageBase> emptyList()).when(cmd).getImagesToCheckDestinationStorageDomains(); Cluster cluster = createPpcCluster(); when(clusterDao.get(any(Guid.class))).thenReturn(cluster); doReturn(clusterDao).when(dbFacade).getClusterDao(); doReturn(true).when(cmd).areParametersLegal(Collections.<String> emptyList()); doReturn(true).when(cmd).validateAddVmCommand(); doReturn(true).when(cmd).isVmNameValidLength(any(VM.class)); when(osRepository.getArchitectureFromOS(any(Integer.class))).thenReturn(ArchitectureType.ppc64); cmd.getParameters().getVm().setClusterArch(ArchitectureType.ppc64); cmd.getParameters().getVm().setUseHostCpuFlags(true); cmd.getParameters().getVm().setMigrationSupport(MigrationSupport.PINNED_TO_HOST); cmd.getParameters().getVm().setClusterId(cluster.getId()); cmd.getParameters().getVm().setVmOs(OsType.Other.ordinal()); ValidateTestUtils.runAndAssertValidateFailure (cmd, EngineMessage.USE_HOST_CPU_REQUESTED_ON_UNSUPPORTED_ARCH); }
Source:
private static String getLookAndFeelClassName() { String userClass = SYSTEM_PREFERENCES.get(USER_LOOK_AND_FEEL_CLASSNAME, null); if (userClass == null) { return SYSTEM_PREFERENCES.getBoolean(LOOK_AND_FEEL_PREFERENCE, false) ? MetalLookAndFeel.class.getName() : null; } else { return userClass; } }

Target:
private static String getLookAndFeelClassName() { return AnathemaPreferences.getDefaultPreferences().getUserLookAndFeel(); }
Source:
public Map<Integer, String> getHostGroupsFromZK() throws KeeperException, InterruptedException, JSONException { Map<Integer, String> hostGroups = Maps.newHashMap(); List<String> children = m_zk.getChildren(CoreZK.hosts, false); for (String child : children) { byte[] payload = m_zk.getData( ZKUtil.joinZKPath(CoreZK.hosts, child), false, new Stat()); final HostInfo info = HostInfo.fromBytes(payload); hostGroups.put(parseHostId(child), info.m_group); } return hostGroups; }

Target:
public Map<Integer, String> getHostGroupsFromZK() throws KeeperException, InterruptedException, JSONException { Map<Integer, String> hostGroups = Maps.newHashMap(); List<String> children = m_zk.getChildren(CoreZK.hosts, false); Queue<ZKUtil.ByteArrayCallback> callbacks = new ArrayDeque<ZKUtil.ByteArrayCallback>(); for (int i = 0; i < children.size() - 1; i++) { ZKUtil.ByteArrayCallback cb = new ZKUtil.ByteArrayCallback(); m_zk.getData(ZKUtil.joinZKPath(CoreZK.hosts, children.get(i)), false, cb, null); callbacks.offer(cb); } ZKUtil.ByteArrayCallback lastCallback = new ZKUtil.ByteArrayCallback(); String lastChild = children.get(children.size() - 1); m_zk.getData(ZKUtil.joinZKPath(CoreZK.hosts, lastChild), false, lastCallback, null); byte[] lastPayload = lastCallback.getData(); final HostInfo lastOne = HostInfo.fromBytes(lastPayload); hostGroups.put(parseHostId(lastChild), lastOne.m_group); for (int i = 0; i < children.size() - 1; i++) { byte[] payload = callbacks.poll().getData(); final HostInfo info = HostInfo.fromBytes(payload); hostGroups.put(parseHostId(children.get(i)), info.m_group); } return hostGroups; }
Source:
public AbstractDeclarable(@Nullable Map<String, Object> arguments) { if (arguments != null) { this.arguments = arguments; } else { this.arguments = new HashMap<String, Object>(); } }

Target:
public AbstractDeclarable(@Nullable Map<String, Object> arguments) { if (arguments != null) { this.arguments = new HashMap<>(arguments); } else { this.arguments = new HashMap<String, Object>(); } }
Source:
public static void appendChecksum(ChannelBuffer buffer, int length) { buffer.writeByte(0x2a); int checksum = Checksum.xor(buffer.toByteBuffer(0, length)) & 0xFF; String checksumString = String.format("%02X", checksum); buffer.writeBytes(checksumString.getBytes(StandardCharsets.US_ASCII)); buffer.writeByte(0x0D); buffer.writeByte(0x0A); }

Target:
public static void appendChecksum(ChannelBuffer buffer, int length) { buffer.writeByte('*'); int checksum = Checksum.xor(buffer.toByteBuffer(0, length)) & 0xFF; String checksumString = String.format("%02X", checksum); buffer.writeBytes(checksumString.getBytes(StandardCharsets.US_ASCII)); buffer.writeByte('\r'); buffer.writeByte('\n'); }
Source:
public void setup() { super.setup(); String key = "test." + provider + ".zone"; if (System.getProperties().containsKey(key)) { zones.add(System.getProperty(key)); } else { zones = api.getConfiguredZones(); } for (String zone : zones) { ServerApi serverApi = api.getServerApiForZone(zone); for (Resource server : serverApi.list().concat()) { if (server.getName().equals(hostName)) serverApi.delete(server.getId()); } } }

Target:
public void setup() { super.setup(); String testZone = System.getProperty("test." + provider + ".zone"); if (testZone != null) { zones = ImmutableSet.of(testZone); } else { zones = api.getConfiguredZones(); } for (String zone : zones) { ServerApi serverApi = api.getServerApiForZone(zone); for (Resource server : serverApi.list().concat()) { if (server.getName().equals(hostName)) serverApi.delete(server.getId()); } } }
Source:
public String changeDateToLastMonth() { datePickerInput.click(); waitForElementVisibleByElement(calendarElement); previousMonthArrow.click(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, -1); Date date = calendar.getTime(); SimpleDateFormat sdfMonth = new SimpleDateFormat("MMMM", Locale.ENGLISH); String previousMonth = sdfMonth.format(date); waitForTextToBePresentInElementByElement(monthInCalendar, previousMonth); JavascriptExecutor js = (JavascriptExecutor) driver; WebElement firstDay = (WebElement) js.executeScript( "return $(arguments[0]).find('.ui-state-default:not(.ui-priority-secondary):nth(0)')[0]", calendarElement ); firstDay.click(); SimpleDateFormat sdfYear = new SimpleDateFormat("YYYY"); String year = sdfYear.format(date); String expectedDate = previousMonth + " 1, " + year; return expectedDate; }

Target:
public String changeDateToLastMonth() { datePickerInput.click(); waitForElementVisibleByElement(calendarElement); previousMonthArrow.click(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, -1); Date date = calendar.getTime(); String previousMonth = getFormatedDate(date, "MMMM"); waitForTextToBePresentInElementByElement(monthInCalendar, previousMonth); JavascriptExecutor js = (JavascriptExecutor) driver; WebElement firstDay = (WebElement) js.executeScript( "return $(arguments[0]).find('.ui-state-default:not(.ui-priority-secondary):nth(0)')[0]", calendarElement ); firstDay.click(); String year = getFormatedDate(date, "YYYY"); String expectedDate = previousMonth + " 1, " + year; return expectedDate; }
Source:
public String read(final String file) throws IOException { final List<String> contents = this.storage.xml().xpath( String.format( "%s/files/file[filename='%s']/raw_content/text()", this.xpath(), file ) ); String content = ""; if (contents.size() == 1) { content = contents.get(0); } return content; }

Target:
public String read(final String file) throws IOException { final List<XML> files = this.storage.xml().nodes( String.format( "%s/files/file[filename='%s']", this.xpath(), file ) ); if (files.isEmpty()) { throw new IOException( String.format("Couldn't find file with the name %s.", file) ); } final List<String> contents = files.get(0) .xpath("raw_content/text()"); String content = ""; if (!contents.isEmpty()) { content = contents.get(0); } return content; }
Source:
public void configureCredentialFactory(final ChainingRestHttpRequestCredentialFactory factory) { final X509CertificateExtractor extractor = x509CertificateExtractor.getIfAvailable(); final boolean headerAuth = casProperties.getRest().isHeaderAuth(); final boolean bodyAuth = casProperties.getRest().isBodyAuth(); LOGGER.debug("is certificate extractor available? = {}, headerAuth = {}, bodyAuth = {}", extractor, headerAuth, bodyAuth); if (extractor != null && headerAuth) { factory.registerCredentialFactory(x509RestRequestHeader()); } if (bodyAuth) { factory.registerCredentialFactory(x509RestMultipartBody()); } }

Target:
public void configureCredentialFactory(final ChainingRestHttpRequestCredentialFactory factory) { final RestProperties restProperties = casProperties.getRest(); final X509CertificateExtractor extractor = x509CertificateExtractor.getIfAvailable(); final boolean headerAuth = restProperties.isHeaderAuth(); final boolean bodyAuth = restProperties.isBodyAuth(); LOGGER.debug("is certificate extractor available? = {}, headerAuth = {}, bodyAuth = {}", extractor, headerAuth, bodyAuth); if (extractor != null && headerAuth) { factory.registerCredentialFactory(x509RestRequestHeader()); } if (bodyAuth) { factory.registerCredentialFactory(x509RestMultipartBody()); } }
Source:
public void close() throws ConnectException { List<Exception> exceptions = new ArrayList<>(); for (String encodedPartition : tempFiles.keySet()) try { if (writers.containsKey(encodedPartition)) { closeTempFile(encodedPartition); appendToWAL(encodedPartition); commitFile(encodedPartition); } } catch (IOException e) { log.error("Error rotating when closing TopicPartitionWriter.", tempFiles.get(encodedPartition)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); e.printStackTrace(ps); ps.close(); log.error(baos.toString()); log.error(e.getMessage()); log.error(e.toString()); exceptions.add(e); } writers.clear(); try { wal.close(); } catch (ConnectException e) { log.error("Error closing {}.", wal.getLogFile()); log.debug(e.getMessage()); exceptions.add(e); } startOffsets.clear(); offsets.clear(); if (exceptions.size() != 0) { StringBuilder sb = new StringBuilder(); for (Exception exception: exceptions) { sb.append(exception.getMessage()); sb.append("\n"); } throw new ConnectException("Error closing writer: " + sb.toString()); } }

Target:
public void close() throws ConnectException { List<Exception> exceptions = new ArrayList<>(); for (String encodedPartition : tempFiles.keySet()) { try { if (writers.containsKey(encodedPartition)) { closeTempFile(encodedPartition); appendToWAL(encodedPartition); commitFile(encodedPartition); } } catch (IOException e) { log.error("Error rotating when closing TopicPartitionWriter.", tempFiles.get(encodedPartition), e); exceptions.add(e); } } writers.clear(); try { wal.close(); } catch (ConnectException e) { log.error("Error closing {}.", wal.getLogFile(), e); exceptions.add(e); } startOffsets.clear(); offsets.clear(); if (exceptions.size() != 0) { StringBuilder sb = new StringBuilder(); for (Exception exception: exceptions) { sb.append(exception.getMessage()); sb.append("\n"); } throw new ConnectException("Error closing writer: " + sb.toString()); } }
Source:
public CeType extractNhinCodedElement(Attribute attrib, String codeId) { LOG.debug("Entering AttributeHelper.extractNhinCodedElement..."); CeType ce = new CeType(); ce.setCode(""); ce.setCodeSystem(""); ce.setCodeSystemName(""); ce.setDisplayName(""); List<XMLObject> attrVals = attrib.getAttributeValues(); if (!attrVals.isEmpty()) { if (LOG.isTraceEnabled()) { LOG.trace("AttributeValue is: " + attrVals.get(0).getClass()); } NodeList nodelist = null; if (attrVals.get(0) instanceof XSAnyImpl) { XSAnyImpl elem = (XSAnyImpl) attrVals.get(0); nodelist = elem.getDOM().getChildNodes(); } else { LOG.error("The value for the " + codeId + " attribute is a: " + attrVals.get(0).getClass() + " expected an XSAnyImpl"); } if (nodelist != null && nodelist.getLength() > 0) { int numNodes = nodelist.getLength(); for (int idx = 0; idx < numNodes; idx++) { compareAttrMap(nodelist, ce, codeId, idx); } } else { LOG.error("The AttributeValue for " + codeId + " should have a Child Node"); } } else { LOG.error("Attributes for " + codeId + " are invalid: " + attrVals); } LOG.debug("Exiting AttributeHelper.extractNhinCodedElement..."); return ce; }

Target:
public CeType extractNhinCodedElement(Attribute attrib, String codeId) { LOG.debug("Entering AttributeHelper.extractNhinCodedElement..."); CeType ce = new CeType(); ce.setCode(""); ce.setCodeSystem(""); ce.setCodeSystemName(""); ce.setDisplayName(""); List<XMLObject> attrVals = attrib.getAttributeValues(); if (!attrVals.isEmpty()) { LOG.trace("AttributeValue is: " + attrVals.get(0).getClass()); NodeList nodelist = null; if (attrVals.get(0) instanceof XSAnyImpl) { XSAnyImpl elem = (XSAnyImpl) attrVals.get(0); nodelist = elem.getDOM().getChildNodes(); } else { LOG.error("The value for the attribute is a: expected an XSAnyImpl", codeId, attrVals.get(0).getClass()); } if (nodelist != null && nodelist.getLength() > 0) { int numNodes = nodelist.getLength(); for (int idx = 0; idx < numNodes; idx++) { compareAttrMap(nodelist, ce, codeId, idx); } } else { LOG.error("The AttributeValue for should have a Child Node", codeId); } } else { LOG.error("Attributes for are invalid: ", codeId, attrVals); } LOG.debug("Exiting AttributeHelper.extractNhinCodedElement..."); return ce; }
Source:
private List<SearchHit> sendElasticQuery(ElasticsearchQueryBuilder queryBuilder) { List<SearchHit> result = new ArrayList<>(); SearchResponse response = queryBuilder.buildScrollSearchRequest().execute().actionGet(); if (response.getHits().getTotalHits() > maxHits) { throw new PrestoException(ELASTIC_SEARCH_EXCEEDS_MAX_HIT_ERROR, "Query get: " + response.getHits().getTotalHits() + " hits, exceeds Elasticsearch max hits configuration: " + maxHits); } while (true) { for (SearchHit hit : response.getHits().getHits()) { result.add(hit); } response = queryBuilder.prepareSearchScroll(response.getScrollId()).execute().actionGet(); if (response.getHits().getHits().length == 0) { break; } } return result; }

Target:
private List<SearchHit> sendElasticQuery(ElasticsearchQueryBuilder queryBuilder) { ImmutableList.Builder<SearchHit> result = ImmutableList.builder(); SearchResponse response = queryBuilder.buildScrollSearchRequest().execute().actionGet(timeout.toMillis()); if (response.getHits().getTotalHits() > maxHits) { throw new PrestoException(ELASTIC_SEARCH_MAX_HITS_EXCEEDED, "The number of hits for the query: " + response.getHits().getTotalHits() + " exceeds the configured max hits: " + maxHits); } while (true) { for (SearchHit hit : response.getHits().getHits()) { result.add(hit); } response = queryBuilder.prepareSearchScroll(response.getScrollId()) .execute() .actionGet(timeout.toMillis()); if (response.getHits().getHits().length == 0) { break; } } return result.build(); }
Source:
protected void doChmod(RemoteFileTemplate<FTPFile> remoteFileTemplate, final String path, final int chmod) { remoteFileTemplate.executeWithClient((ClientCallbackWithoutResult<FTPClient>) client -> { String chModCommand = "chmod " + chmod + " " + path; try { client.sendSiteCommand(chModCommand); } catch (IOException e) { throw new UncheckedIOException("Failed to execute '" + chModCommand + "'", e); } }); }

Target:
protected void doChmod(RemoteFileTemplate<FTPFile> remoteFileTemplate, final String path, final int chmod) { remoteFileTemplate.executeWithClient((ClientCallbackWithoutResult<FTPClient>) client -> { String chModCommand = "chmod " + Integer.toOctalString(chmod) + " " + path; try { client.sendSiteCommand(chModCommand); } catch (IOException e) { throw new UncheckedIOException("Failed to execute '" + chModCommand + "'", e); } }); }
Source:
protected ApacheDockerHttpClientImpl( URI dockerHost, SSLConfig sslConfig, ConnectionPoolConfig connectionPoolConf ) { Registry<ConnectionSocketFactory> socketFactoryRegistry = createConnectionSocketFactoryRegistry(sslConfig, dockerHost); switch (dockerHost.getScheme()) { case "unix": case "npipe": host = new HttpHost(dockerHost.getScheme(), "localhost", 2375); break; case "tcp": host = new HttpHost( socketFactoryRegistry.lookup("https") != null ? "https" : "http", dockerHost.getHost(), dockerHost.getPort() ); break; default: host = HttpHost.create(dockerHost); } PoolingHttpClientConnectionManager connectionPoolMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry, new ManagedHttpClientConnectionFactory( null, null, null, null, message -> { Header transferEncodingHeader = message.getFirstHeader(HttpHeaders.TRANSFER_ENCODING); if (transferEncodingHeader != null) { if ("identity".equalsIgnoreCase(transferEncodingHeader.getValue())) { return ContentLengthStrategy.UNDEFINED; } } return DefaultContentLengthStrategy.INSTANCE.determineLength(message); }, null ) ); if (connectionPoolConf != null) { if (connectionPoolConf.getMaxTotal() != null) { connectionPoolMgr.setMaxTotal(connectionPoolConf.getMaxTotal()); } if (connectionPoolConf.getDefaultMaxPerRoute() != null) { connectionPoolMgr.setDefaultMaxPerRoute(connectionPoolConf.getDefaultMaxPerRoute()); } } httpClient = HttpClients.custom() .setRequestExecutor(new HijackingHttpRequestExecutor(null)) .setConnectionManager(connectionPoolMgr) .build(); }

Target:
protected ApacheDockerHttpClientImpl( URI dockerHost, SSLConfig sslConfig, ConnectionPoolConfig connectionPoolConf ) { Registry<ConnectionSocketFactory> socketFactoryRegistry = createConnectionSocketFactoryRegistry(sslConfig, dockerHost); switch (dockerHost.getScheme()) { case "unix": case "npipe": host = new HttpHost(dockerHost.getScheme(), "localhost", 2375); break; case "tcp": host = new HttpHost( socketFactoryRegistry.lookup("https") != null ? "https" : "http", dockerHost.getHost(), dockerHost.getPort() ); break; default: host = HttpHost.create(dockerHost); } PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry, new ManagedHttpClientConnectionFactory( null, null, null, null, message -> { Header transferEncodingHeader = message.getFirstHeader(HttpHeaders.TRANSFER_ENCODING); if (transferEncodingHeader != null) { if ("identity".equalsIgnoreCase(transferEncodingHeader.getValue())) { return ContentLengthStrategy.UNDEFINED; } } return DefaultContentLengthStrategy.INSTANCE.determineLength(message); }, null ) ); if (connectionPoolConf != null) { Integer maxConnections = connectionPoolConf.getMaxConnections(); if (maxConnections != null) { connectionManager.setMaxTotal(maxConnections); connectionManager.setDefaultMaxPerRoute(maxConnections); } } httpClient = HttpClients.custom() .setRequestExecutor(new HijackingHttpRequestExecutor(null)) .setConnectionManager(connectionManager) .build(); }
Source:
private void closeSessionWithoutWakeup(long sessionId) { NIOServerCnxn cnxn = sessionMap.remove(sessionId); if (cnxn != null) { cnxn.close(); } }

Target:
private void closeSessionWithoutWakeup(long sessionId) { NIOServerCnxn cnxn = (NIOServerCnxn) sessionMap.remove(sessionId); if (cnxn != null) { try { cnxn.close(); } catch (Exception e) { LOG.warn("exception during session close", e); } } }
Source:
private Flux<String> listChunks() { Flux<String> chunks = client.listBlobs(new ListBlobsOptions().setPrefix(shardPath)) .map(BlobItem::getName); if (userCursor == null) { return chunks; } else { AtomicBoolean pass = new AtomicBoolean(); return chunks.filter(chunkPath -> { if (pass.get()) { return true; } else { if (userCursor.getChunkPath().equals(chunkPath)) { pass.set(true); return true; } else { return false; } } }); } }

Target:
private Flux<String> listChunks() { Flux<String> chunks = client.listBlobs(new ListBlobsOptions().setPrefix(shardPath)) .map(BlobItem::getName); if (userCursor == null) { return chunks; } else { return Flux.defer(() -> { AtomicBoolean pass = new AtomicBoolean(); return chunks.filter(chunkPath -> { if (pass.get()) { return true; } else { if (userCursor.getChunkPath().equals(chunkPath)) { pass.set(true); return true; } else { return false; } } }); }); } }
Source:
public List<?> predict(int tenantId, String userName, long modelId, List<String[]> data) throws MLModelHandlerException { if (!isValidModelId(tenantId, userName, modelId)) { String msg = String.format("Failed to build the model. Invalid model id: %s for tenant: %s and user: %s", modelId, tenantId, userName); throw new MLModelHandlerException(msg); } MLModel builtModel = retrieveModel(modelId); if (builtModel.getFeatures().size() != data.get(0).length) { String msg = String.format("Prediction failed from model [id] %s since the number of features of model" + " [%s] doesn't match the number of features in the input data [%s]", modelId, builtModel.getFeatures().size(), data.get(0).length); throw new MLModelHandlerException(msg); } for (Feature feature: builtModel.getFeatures()) { if (feature.getType().equals(FeatureType.NUMERICAL)) { int actualIndex = builtModel.getNewToOldIndicesList().indexOf(feature.getIndex()); for (String[] dataPoint: data) { if(!isNumeric(dataPoint[actualIndex])) { String msg = String.format("Invalid value: %s for the feature: %s", dataPoint[actualIndex], feature.getName()); throw new MLModelHandlerException(msg); } } } } Predictor predictor = new Predictor(modelId, builtModel, data); List<?> predictions = predictor.predict(); log.info(String.format("Prediction from model [id] %s was successful.", modelId)); return predictions; }

Target:
public List<?> predict(int tenantId, String userName, long modelId, List<String[]> data) throws MLModelHandlerException { if (!isValidModelId(tenantId, userName, modelId)) { String msg = String.format("Failed to build the model. Invalid model id: %s for tenant: %s and user: %s", modelId, tenantId, userName); throw new MLModelHandlerException(msg); } MLModel builtModel = retrieveModel(modelId); if (builtModel.getFeatures().size() != data.get(0).length) { String msg = String.format("Prediction failed from model [id] %s since the number of features of model" + " [%s] doesn't match the number of features in the input data [%s]", modelId, builtModel.getFeatures().size(), data.get(0).length); throw new MLModelHandlerException(msg); } for (Feature feature: builtModel.getFeatures()) { if (feature.getType().equals(FeatureType.NUMERICAL)) { int actualIndex = builtModel.getNewToOldIndicesList().indexOf(feature.getIndex()); for (String[] dataPoint: data) { if(!NumberUtils.isNumber(dataPoint[actualIndex])) { String msg = String.format("Invalid value: %s for the feature: %s at feature index: %s", dataPoint[actualIndex], feature.getName(), actualIndex); throw new MLModelHandlerException(msg); } } } } Predictor predictor = new Predictor(modelId, builtModel, data); List<?> predictions = predictor.predict(); log.info(String.format("Prediction from model [id] %s was successful.", modelId)); return predictions; }
Source:
public void isSameAllergen_shouldReturnTrueForSameNonCodedAllergen() { Concept concept = Context.getConceptService().getConceptByUuid(otherNonCodedConceptUuid); Assert.assertTrue(new Allergen(null, concept, "OTHER VALUE").isSameAllergen(new Allergen(null, concept, "OTHER VALUE"))); }

Target:
public void isSameAllergen_shouldReturnTrueForSameNonCodedAllergen() { Concept concept = Context.getConceptService().getConceptByUuid(Allergen.getOtherNonCodedConceptUuid()); Assert.assertTrue(new Allergen(null, concept, "OTHER VALUE").isSameAllergen(new Allergen(null, concept, "OTHER VALUE"))); }
Source:
public void testAutoDeclareFalse() throws Exception { RabbitTemplate template = context.getBean(RabbitTemplate.class); template.convertAndSend("testContainerWithAutoDeleteQueues", "anon2", "foo"); assertNotNull(queue.poll(10, TimeUnit.SECONDS)); SimpleMessageListenerContainer listenerContainer = context.getBean("container4", SimpleMessageListenerContainer.class); listenerContainer.stop(); RabbitAdmin admin = spy(TestUtils.getPropertyValue(listenerContainer, "rabbitAdmin", RabbitAdmin.class)); new DirectFieldAccessor(listenerContainer).setPropertyValue("rabbitAdmin", admin); listenerContainer = spy(listenerContainer); when(listenerContainer.createBlockingQueueConsumer()).thenReturn(mock(BlockingQueueConsumer.class)); listenerContainer.start(); verify(admin, never()).initialize(); listenerContainer.stop(); }

Target:
public void testAutoDeclareFalse() throws Exception { RabbitTemplate template = context.getBean(RabbitTemplate.class); template.convertAndSend("testContainerWithAutoDeleteQueues", "anon2", "foo"); assertNotNull(queue.poll(10, TimeUnit.SECONDS)); SimpleMessageListenerContainer listenerContainer = context.getBean("container4", SimpleMessageListenerContainer.class); listenerContainer.stop(); RabbitAdmin admin = spy(TestUtils.getPropertyValue(listenerContainer, "rabbitAdmin", RabbitAdmin.class)); new DirectFieldAccessor(listenerContainer).setPropertyValue("rabbitAdmin", admin); listenerContainer = spy(listenerContainer); BlockingQueueConsumer consumer = mock(BlockingQueueConsumer.class); doThrow(RuntimeException.class).when(consumer).start(); when(listenerContainer.createBlockingQueueConsumer()).thenReturn(consumer); listenerContainer.start(); listenerContainer.stop(); verify(admin, never()).initialize(); }