auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static STRtree buildRTree(LongArrayList addresses, List<List<Block>> channels, int geometryChannel, Optional<Integer> radiusChannel, Optional<Integer> partitionChannel) { STRtree rtree = new STRtree(); Operator relateOperator = OperatorFactoryLocal.getInstance().getOperator(Operator.Type.Relate); for (int position = 0; position < addresses.size(); position++) { long pageAddress = addresses.getLong(position); int blockIndex = decodeSliceIndex(pageAddress); int blockPosition = decodePosition(pageAddress); Block block = channels.get(geometryChannel).get(blockIndex); if (block.isNull(blockPosition)) { continue; } Slice slice = block.getSlice(blockPosition, 0, block.getSliceLength(blockPosition)); OGCGeometry ogcGeometry = deserialize(slice); verify(ogcGeometry != null); if (ogcGeometry.isEmpty()) { continue; } double radius = radiusChannel.map(channel -> DOUBLE.getDouble(channels.get(channel).get(blockIndex), blockPosition)).orElse(0.0); if (radius < 0) { continue; } if (!radiusChannel.isPresent()) { accelerateGeometry(ogcGeometry, relateOperator); } int partition = -1; if (partitionChannel.isPresent()) { Block partitionBlock = channels.get(partitionChannel.get()).get(blockIndex); partition = toIntExact(INTEGER.getLong(partitionBlock, blockPosition)); } rtree.insert(GeometryUtils.getJtsEnvelope(ogcGeometry, radius), new GeometryWithPosition(ogcGeometry, partition, position)); } rtree.build(); return rtree; }

Target:
private static STRtree buildRTree(LongArrayList addresses, List<List<Block>> channels, int geometryChannel, Optional<Integer> radiusChannel, Optional<Integer> partitionChannel) { STRtree rtree = new STRtree(); Operator relateOperator = OperatorFactoryLocal.getInstance().getOperator(Operator.Type.Relate); for (int position = 0; position < addresses.size(); position++) { long pageAddress = addresses.getLong(position); int blockIndex = decodeSliceIndex(pageAddress); int blockPosition = decodePosition(pageAddress); Block block = channels.get(geometryChannel).get(blockIndex); if (block.isNull(blockPosition)) { continue; } Slice slice = block.getSlice(blockPosition, 0, block.getSliceLength(blockPosition)); OGCGeometry ogcGeometry = deserialize(slice); verify(ogcGeometry != null); if (ogcGeometry.isEmpty()) { continue; } double radius = radiusChannel.map(channel -> DOUBLE.getDouble(channels.get(channel).get(blockIndex), blockPosition)).orElse(0.0); if (radius < 0) { continue; } if (!radiusChannel.isPresent()) { accelerateGeometry(ogcGeometry, relateOperator); } int partition = -1; if (partitionChannel.isPresent()) { Block partitionBlock = channels.get(partitionChannel.get()).get(blockIndex); partition = toIntExact(INTEGER.getLong(partitionBlock, blockPosition)); } rtree.insert(getJtsEnvelope(ogcGeometry, radius), new GeometryWithPosition(ogcGeometry, partition, position)); } rtree.build(); return rtree; }
Source:
public IntegrationFlow inTcpGateway() { return IntegrationFlows.from(Tcp.inboundGateway(server1())) .transform(new ObjectToStringTransformer()) .<String, String>transform(String::toUpperCase) .get(); }

Target:
public IntegrationFlow inTcpGateway() { return IntegrationFlows.from(Tcp.inboundGateway(server1())) .transform(Transformers.objectToString()) .<String, String>transform(String::toUpperCase) .get(); }
Source:
private void validateAnswer(Context context) { if (!isClicked) { isClicked = true; try { Phone phone = new Phone(mCustomEditText.getText().toString()); hideKeyboard(mCustomEditText); Validation.getInstance().removeInputError(mCustomEditText); String value = phone.getValue(); notifyAnswerChanged(value); } catch (InvalidPhoneException e) { Validation.getInstance().addinvalidInput(mCustomEditText, context.getString(R.string.dynamic_error_phone_format)); mCustomEditText.setError(context.getString(R.string.dynamic_error_phone_format)); } isClicked = false; } }

Target:
public void validateAnswer(Context context) { try { Phone phone = new Phone(mCustomEditText.getText().toString()); hideKeyboard(mCustomEditText); Validation.getInstance().removeInputError(mCustomEditText); String value = phone.getValue(); notifyAnswerChanged(value); } catch (InvalidPhoneException e) { Validation.getInstance().addinvalidInput(mCustomEditText, context.getString(R.string.dynamic_error_phone_format)); mCustomEditText.setError(context.getString(R.string.dynamic_error_phone_format)); } }
Source:
public static final boolean isStorageWritable() { return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED; }

Target:
public static final boolean isStorageWritable() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); }
Source:
Object convertSingle(Object value) { if (typeSystem.supportsAsNativeType(value.getClass())) { return typeSystem.getMappedToNativeTypeAdapter(value.getClass()).apply(value); } else { Map<String, Object> help = convertParameters(Collections.singletonMap("u", value)); return help.get("u"); } }

Target:
private Object convertSingle(Object value) { if (typeSystem.supportsAsNativeType(value.getClass())) { return typeSystem.getMappedToNativeTypeAdapter(value.getClass()).apply(value); } else { String fixedKey = "u"; return convertParameters(Collections.singletonMap(fixedKey, value)).get(fixedKey); } }
Source:
public void show(CollectedDataNode node) { FileDialog fileDialog = new FileDialog(getDisplay().getActiveShell(), SWT.SAVE); fileDialog.setText("Save"); fileDialog.setFilterPath("C:/"); String[] filterExt = { "*.txt", "*.doc", ".rtf", "*.*" }; fileDialog.setFilterExtensions(filterExt); String selected = fileDialog.open(); if (selected != null && selected.length() > 0) { PlotDataParser parser = new PlotDataParser(node); DataParserResult result = parser.parseEntries(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String data = gson.toJson(result); try (Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(selected), "UTF-8"))) { writer.write(data); } catch (IOException e) { e.printStackTrace(); } } }

Target:
public void show(CollectedDataNode node) { FileDialog fileDialog = new FileDialog(getDisplay().getActiveShell(), SWT.SAVE); fileDialog.setText("Export to JSON"); String[] filter = { "*.json", "*.*" }; fileDialog.setFilterExtensions(filter); String fileName = fileDialog.open(); if (fileName != null && fileName.length() > 0) { PlotDataParser parser = new PlotDataParser(node); DataParserResult result = parser.parseEntries(); List<PlotItem> dataset = result.dataset; Gson gson = new GsonBuilder().setPrettyPrinting().create(); String data = gson.toJson(dataset); try (Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8"))) { writer.write(data); } catch (IOException e) { e.printStackTrace(); } } }
Source:
protected void getTopicList() { if (getTopicListTask != null) { getTopicListTask.cancel(true); } getTopicListTask = new GetTopicListTask(getActivity(), courseData.getCourse().getId()) { @Override public void onSuccess(CourseTopics courseTopics) { final ArrayList<DiscussionTopic> allTopics = new ArrayList<>(); allTopics.addAll(courseTopics.getNonCoursewareTopics()); allTopics.addAll(courseTopics.getCoursewareTopics()); final TopicSpinnerAdapter adapter = new TopicSpinnerAdapter(container.getContext(), DiscussionTopicDepth.createFromDiscussionTopics(allTopics)); topicsSpinner.setAdapter(adapter); { if (!discussionTopic.isAllType() && !discussionTopic.isFollowingType()) { int selectedTopicIndex; if (discussionTopic.getIdentifier() == null) { selectedTopicIndex = adapter.getPosition(discussionTopic.getChildren().get(0)); } else { selectedTopicIndex = adapter.getPosition(discussionTopic); } if (selectedTopicIndex >= 0) { topicsSpinner.setSelection(selectedTopicIndex); } } } } @Override public void onException(Exception ex) { logger.error(ex); } }; getTopicListTask.setMessageCallback(null); getTopicListTask.execute(); }

Target:
protected void getTopicList() { if (getTopicListTask != null) { getTopicListTask.cancel(true); } getTopicListTask = new GetTopicListTask(getActivity(), courseData.getCourse().getId()) { @Override public void onSuccess(CourseTopics courseTopics) { final ArrayList<DiscussionTopic> allTopics = new ArrayList<>(); allTopics.addAll(courseTopics.getNonCoursewareTopics()); allTopics.addAll(courseTopics.getCoursewareTopics()); final TopicSpinnerAdapter adapter = new TopicSpinnerAdapter(container.getContext(), DiscussionTopicDepth.createFromDiscussionTopics(allTopics)); topicsSpinner.setAdapter(adapter); { if (!discussionTopic.isAllType() && !discussionTopic.isFollowingType()) { int selectedTopicIndex = -1; if (discussionTopic.getIdentifier() == null) { if (!discussionTopic.getChildren().isEmpty()) { selectedTopicIndex = adapter.getPosition(discussionTopic.getChildren().get(0)); } } else { selectedTopicIndex = adapter.getPosition(discussionTopic); } if (selectedTopicIndex >= 0) { topicsSpinner.setSelection(selectedTopicIndex); } } } } @Override public void onException(Exception ex) { logger.error(ex); } }; getTopicListTask.setMessageCallback(null); getTopicListTask.execute(); }
Source:
public String toString() { return id + ": " + msg; }

Target:
public String toString() { if (getTopic() .equals(ExtensionEventFactory.buildTopic(ExtensionEventFactory.EXTENSION_INSTALLED_EVENT_TOPIC, id))) { return "Extension '" + id + "' has been installed."; } else if (getTopic().equals( ExtensionEventFactory.buildTopic(ExtensionEventFactory.EXTENSION_UNINSTALLED_EVENT_TOPIC, id))) { return "Extension '" + id + "' has been uninstalled."; } else { return id + ": " + (msg != null ? msg : "Operation failed."); } }
Source:
public Object[] transform(String sourceData) throws FormatException { if (sourceData == null) { return null; } Tokenizer tokenizer = new Tokenizer(new StringReader(sourceData), m_csvPreference, m_strictquotes, m_escape, DEFAULT_COLUMN_LIMIT_SIZE, 0); CsvListReader csvReader = new CsvListReader(tokenizer, m_csvPreference); List<String> dataList; try { dataList = csvReader.read(); } catch (IOException | SuperCsvException e) { throw new FormatException("Fail to parse csv data", e); } finally { try { if (csvReader != null) csvReader.close(); } catch (IOException e) { throw new FormatException(e); } } String[] data = dataList.toArray(new String[0]); normalize(data); return data; }

Target:
public Object[] transform(String sourceData) throws FormatException { try { Object list[] = m_parser.parseLine(sourceData); if (list != null) { for (int i = 0; i < list.length; i++) { if ("NULL".equals(list[i]) || Constants.CSV_NULL.equals(list[i]) || Constants.QUOTED_CSV_NULL.equals(list[i])) { list[i] = null; } } } return list; } catch (IOException e) { throw new FormatException("failed to format " + sourceData, e); } }
Source:
static void validateFile( OrcWriteValidation writeValidation, OrcDataSource input, List<Type> types, DateTimeZone hiveStorageTimeZone, OrcEncoding orcEncoding, OrcReaderOptions orcReaderOptions) throws OrcCorruptionException { ImmutableMap.Builder<Integer, Type> readTypes = ImmutableMap.builder(); for (int columnIndex = 0; columnIndex < types.size(); columnIndex++) { readTypes.put(columnIndex, types.get(columnIndex)); } try { OrcReader orcReader = new OrcReader( input, orcEncoding, new StorageOrcFileTailSource(), new StorageStripeMetadataSource(), Optional.of(writeValidation), orcReaderOptions, false, new NoopOrcAggregatedMemoryContext()); try (OrcBatchRecordReader orcRecordReader = orcReader.createBatchRecordReader( readTypes.build(), OrcPredicate.TRUE, hiveStorageTimeZone, new NoopOrcAggregatedMemoryContext(), INITIAL_BATCH_SIZE)) { while (orcRecordReader.nextBatch() >= 0) { } } } catch (IOException e) { throw new OrcCorruptionException(e, input.getId(), "Validation failed"); } }

Target:
static void validateFile( OrcWriteValidation writeValidation, OrcDataSource input, List<Type> types, DateTimeZone hiveStorageTimeZone, OrcEncoding orcEncoding, OrcReaderOptions orcReaderOptions) throws OrcCorruptionException { ImmutableMap.Builder<Integer, Type> readTypes = ImmutableMap.builder(); for (int columnIndex = 0; columnIndex < types.size(); columnIndex++) { readTypes.put(columnIndex, types.get(columnIndex)); } try { OrcReader orcReader = new OrcReader( input, orcEncoding, new StorageOrcFileTailSource(), new StorageStripeMetadataSource(), Optional.of(writeValidation), NOOP_ORC_AGGREGATED_MEMORY_CONTEXT, orcReaderOptions, false); try (OrcBatchRecordReader orcRecordReader = orcReader.createBatchRecordReader( readTypes.build(), OrcPredicate.TRUE, hiveStorageTimeZone, NOOP_ORC_AGGREGATED_MEMORY_CONTEXT, INITIAL_BATCH_SIZE)) { while (orcRecordReader.nextBatch() >= 0) { } } } catch (IOException e) { throw new OrcCorruptionException(e, input.getId(), "Validation failed"); } }
Source:
public StreamsDatum(Object document, String id, DateTime timestamp) { this(document, id, timestamp, null); }

Target:
public StreamsDatum(Object document, String id, DateTime timestamp) { this(document, id, timestamp, null, new HashMap<String, Object>()); }
Source:
private void postConstruct() { CLASS_TO_MAPPER_MAP.put(MeterReads.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(MeterReadsGas.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(EventMessagesResponse.class, this.managementMapper); CLASS_TO_MAPPER_MAP.put(ActionResponse.class, this.commonMapper); CLASS_TO_MAPPER_MAP.put(FaultResponse.class, this.commonMapper); CLASS_TO_MAPPER_MAP.put(AlarmRegister.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(AdministrativeStatusTypeResponse.class, this.configurationMapper); CLASS_TO_MAPPER_MAP.put(PeriodicMeterReadsContainer.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(PeriodicMeterReadsContainerGas.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(GetAttributeValuesResponse.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(FirmwareVersionResponse.class, this.configurationMapper); CLASS_TO_MAPPER_MAP.put(UpdateFirmwareResponse.class, this.configurationMapper); CLASS_TO_MAPPER_MAP.put(AssociationLnObjectsResponseData.class, this.adhocMapper); CLASS_TO_MAPPER_MAP.put(GetConfigurationObjectResponse.class, this.configurationMapper); CLASS_TO_MAPPER_MAP.put(ProfileGenericDataResponse.class, this.monitoringMapper); }

Target:
private void postConstruct() { CLASS_TO_MAPPER_MAP.put(MeterReads.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(MeterReadsGas.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(EventMessagesResponse.class, this.managementMapper); CLASS_TO_MAPPER_MAP.put(ActionResponse.class, this.commonMapper); CLASS_TO_MAPPER_MAP.put(FaultResponse.class, this.commonMapper); CLASS_TO_MAPPER_MAP.put(AlarmRegister.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(AdministrativeStatusTypeResponse.class, this.configurationMapper); CLASS_TO_MAPPER_MAP.put(PeriodicMeterReadsContainer.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(PeriodicMeterReadsContainerGas.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(GetAttributeValuesResponse.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(FirmwareVersionResponse.class, this.configurationMapper); CLASS_TO_MAPPER_MAP.put(UpdateFirmwareResponse.class, this.configurationMapper); CLASS_TO_MAPPER_MAP.put(AssociationLnObjectsResponseData.class, this.adhocMapper); CLASS_TO_MAPPER_MAP.put(ProfileGenericDataResponse.class, this.monitoringMapper); }
Source:
public String computeNewVersionRange(String originalVersionRange, String originalReferencedVersion, String newReferencedVersion) { if (originalVersionRange == null) { return null; } VersionRange referencingVersionRange = VersionRange.valueOf(originalVersionRange); Version referencedVersion = parseBaseVersion(originalReferencedVersion); Version referencedNewVersion = parseBaseVersion(newReferencedVersion); referencingVersionRange = computeNewVersionRange(referencingVersionRange, referencedVersion, referencedNewVersion); return referencingVersionRange.toString(); }

Target:
public String computeNewVersionRange(String originalVersionRange, String originalReferencedVersion, String newReferencedVersion) { if (originalVersionRange == null) { return null; } VersionRange originalVersionRangeObject = VersionRange.valueOf(originalVersionRange); Version originalReferencedVersionObject = parseBaseVersion(originalReferencedVersion); Version newReferencedVersionObject = parseBaseVersion(newReferencedVersion); VersionRange newVersionRangeObject = computeNewVersionRange(originalVersionRangeObject, originalReferencedVersionObject, newReferencedVersionObject); return newVersionRangeObject.toString(); }
Source:
public void verifySuggestVideoOrArticleButtonNotClickable() { waitForElementByElement(submitButton); waitForElementNotClickableByElement(submitButton); PageObjectLogging.log("VerifySuggestVideoOrArticleButtonNotClickable", "Verify that 'Suggest Video' or 'Article' submit button button is disabled", true); }

Target:
public void verifySuggestVideoOrArticleButtonNotClickable() { waitForElementByElement(submitButton); waitForElementNotClickableByElement(submitButton); PageObjectLogging.log( "verifySuggestVideoOrArticleButtonNotClickable", "Verify that 'Suggest Video' or 'Article' submit button button is disabled", true ); }
Source:
public static IThreadDMData getThreadData(final int threadId) throws InterruptedException, ExecutionException, TimeoutException { final AsyncCompletionWaitor wait = new AsyncCompletionWaitor(); final DataRequestMonitor<IThreadDMData> rm = new DataRequestMonitor<IThreadDMData>( fSession.getExecutor(), null) { @Override protected void handleCompleted() { if (isSuccess()) { wait.setReturnInfo(getData()); } wait.waitFinished(getStatus()); } }; final IProcessDMContext processContext = DMContexts.getAncestorOfType( SyncUtil.getContainerContext(), IProcessDMContext.class); fProcessesService.getExecutor().submit(new Runnable() { @Override public void run() { IThreadDMContext threadDmc = fProcessesService .createThreadContext(processContext, Integer.toString(threadId)); fProcessesService.getExecutionData(threadDmc, rm); } }); wait.waitUntilDone(TestsPlugin.massageTimeout(2000)); assertTrue(wait.getMessage(), wait.isOK()); IThreadDMData threadData = (IThreadDMData) wait.getReturnInfo(); Assert.assertNotNull("Thread data not returned for thread id = " + threadId, threadData); wait.waitReset(); return threadData; }

Target:
public static IThreadDMData getThreadData(final int threadId) throws InterruptedException, ExecutionException, TimeoutException { final IProcessDMContext processContext = DMContexts.getAncestorOfType( SyncUtil.getContainerContext(), IProcessDMContext.class); Query<IThreadDMData> query = new Query<IThreadDMData>() { @Override protected void execute(DataRequestMonitor<IThreadDMData> rm) { IThreadDMContext threadDmc = fProcessesService .createThreadContext(processContext, Integer.toString(threadId)); fProcessesService.getExecutionData(threadDmc, rm); } }; fSession.getExecutor().execute(query); return query.get(500, TimeUnit.MILLISECONDS); }
Source:
public String toString() { if (isError()) { return "Error AcessToken [error=" + error + ", error_description=" + errorDescription + ", error_uri=" + errorUri + "]"; } else { return "AccessToken [access_token=" + accessToken + ", token_type=" + tokenType + "]"; } }

Target:
public String toString() { if (isError()) { return "Error AccessToken [error=" + error + ", error_description=" + errorDescription + ", error_uri=" + errorUri + "]"; } else { return "AccessToken [access_token=" + accessToken + ", token_type=" + tokenType + "]"; } }
Source:
public Collection<String> getNames() { return Collections.unmodifiableSet(names); }

Target:
public Collection<String> getNames() { final Set<String> names = new HashSet<>(named.keySet()); namedArgumentFinder.forEach(args -> names.addAll(args.getNames())); return Collections.unmodifiableSet(names); }
Source:
public ConstraintBasedAlgorithm(List<HardConstraint> hardConstraints, List<SoftConstraint> softConstraints, SoftConstraintWeightModel softConstraintWeightModel) { _hardConstraints = hardConstraints; _softConstraints = softConstraints; _softConstraintsWeightModel = softConstraintWeightModel; }

Target:
ConstraintBasedAlgorithm(List<HardConstraint> hardConstraints, List<SoftConstraint> softConstraints, SoftConstraintWeightModel softConstraintWeightModel) { _hardConstraints = hardConstraints; _softConstraints = softConstraints; _softConstraintsWeightModel = softConstraintWeightModel; }
Source:
public String ensureIndexed(List<Object> fieldNames, String indexName) { return IndexCreator.ensureIndexed(Index.setUp(fieldNames, indexName), database, datastore, queue); }

Target:
public String ensureIndexed(List<Object> fieldNames, String indexName) { return IndexCreator.ensureIndexed(Index.getInstance(fieldNames, indexName), database, datastore, queue); }
Source:
protected TickRateModulation doBusWork() { if( !this.canDoBusWork() ) { return TickRateModulation.IDLE; } final TileEntity te = this.getConnectedTE(); if( te != null && te.hasCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing() ) ) { try { final IFluidHandler fh = te.getCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing() ); final IMEMonitor<IAEFluidStack> inv = this.getProxy().getStorage().getInventory( this.getChannel() ); if( fh != null ) { for( int i = 0; i < this.getConfig().getSlots(); i++ ) { IAEItemStack stack = this.getConfig().getAEStackInSlot( i ); if( stack != null && stack.getDefinition() != null ) { IFluidHandlerItem ifh = stack.getDefinition().getCapability( CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null ); if( ifh == null ) { throw new NullPointerException( "IFluidHandlerItem is null" ); } AEFluidStack toExtract = AEFluidStack.fromFluidStack( ifh.drain( Integer.MAX_VALUE, false ) ); toExtract.setStackSize( this.calculateAmountToSend() ); IAEFluidStack out = inv.extractItems( toExtract, Actionable.SIMULATE, this.source ); if( out != null ) { int wasInserted = fh.fill( out.getFluidStack(), true ); if( wasInserted > 0 ) { inv.extractItems( toExtract, Actionable.MODULATE, this.source ); return TickRateModulation.FASTER; } } } } return TickRateModulation.SLOWER; } } catch( GridAccessException e ) { e.printStackTrace(); } } return TickRateModulation.SLEEP; }

Target:
protected TickRateModulation doBusWork() { if( !this.canDoBusWork() ) { return TickRateModulation.IDLE; } final TileEntity te = this.getConnectedTE(); if( te != null && te.hasCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing() ) ) { try { final IFluidHandler fh = te.getCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing() ); final IMEMonitor<IAEFluidStack> inv = this.getProxy().getStorage().getInventory( this.getChannel() ); if( fh != null ) { for( int i = 0; i < this.getConfig().getSlots(); i++ ) { IAEItemStack stack = this.getConfig().getAEStackInSlot( i ); if( stack != null && stack.getDefinition() != null ) { IFluidHandlerItem ifh = stack.getDefinition().getCapability( CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null ); if( ifh == null ) { throw new NullPointerException( "IFluidHandlerItem is null" ); } AEFluidStack toExtract = AEFluidStack.fromFluidStack( ifh.drain( Integer.MAX_VALUE, false ) ); toExtract.setStackSize( this.calculateAmountToSend() ); IAEFluidStack out = inv.extractItems( toExtract, Actionable.SIMULATE, this.source ); if( out != null ) { int wasInserted = fh.fill( out.getFluidStack(), true ); if( wasInserted > 0 ) { inv.extractItems( toExtract, Actionable.MODULATE, this.source ); return TickRateModulation.FASTER; } } } } return TickRateModulation.SLOWER; } } catch( GridAccessException e ) { } } return TickRateModulation.SLEEP; }
Source:
public String getUserData() { if (userData != null) { try { userData = URLDecoder.decode(userData, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new InvalidParameterValueException("Url decoding of userdata failed."); } } return userData; }

Target:
public String getUserData() { return userData; }
Source:
public void detectExposureTo3rdPartyInHREF() throws HttpMalformedHeaderException, URIException { String testURI = "<LINK_1>"; String body = "<html>\n<body>\n<h2>HTML Links</h2>\n" + "<p><a href=\"<LINK_0>\">Testing ZAP</a>" + "</p>\n" + "</body>\n</html>"; HttpMessage msg = createHttpMessageWithRespBody(body); msg.getRequestHeader().setURI(new URI(testURI, false)); rule.scanHttpRequestSend(msg, -1); assertEquals(2, alertsRaised.size()); }

Target:
public void detectExposureTo3rdPartyInHREF() throws HttpMalformedHeaderException, URIException { String testURI = "<LINK_1>"; String body = "<html>\n<body>\n<h2>HTML Links</h2>\n" + "<p><a href=\"<LINK_2>\">Testing ZAP</a>" + "</p>\n" + "</body>\n</html>"; HttpMessage msg = createHttpMessageWithRespBody(body); msg.getRequestHeader().setURI(new URI(testURI, false)); rule.scanHttpResponseReceive(msg, -1, new Source(body)); assertEquals(2, alertsRaised.size()); assertEquals(Alert.RISK_MEDIUM, alertsRaised.get(2 - 1).getRisk()); }
Source:
public void importMrrtReportTemplate(InputStream in) throws IOException { File tmp = File.createTempFile("mrrtTemplateFile", ".html"); OpenmrsUtil.copyFile(in, new FileOutputStream(tmp)); MrrtReportTemplate template = parser.parse(new FileInputStream(tmp)); File destinationFile = new File(radiologyProperties.getReportTemplateHome(), java.util.UUID.randomUUID() .toString()); template.setPath(destinationFile.getAbsolutePath()); saveMrrtReportTemplate(template); OpenmrsUtil.copyFile(new FileInputStream(tmp), new FileOutputStream(destinationFile)); in.close(); }

Target:
public void importMrrtReportTemplate(InputStream in) throws IOException { File tmp = File.createTempFile(java.util.UUID.randomUUID() .toString(), java.util.UUID.randomUUID() .toString()); OpenmrsUtil.copyFile(in, new FileOutputStream(tmp)); MrrtReportTemplate template = parser.parse(new FileInputStream(tmp)); File destinationFile = new File(radiologyProperties.getReportTemplateHome(), java.util.UUID.randomUUID() .toString()); template.setPath(destinationFile.getAbsolutePath()); saveMrrtReportTemplate(template); OpenmrsUtil.copyFile(new FileInputStream(tmp), new FileOutputStream(destinationFile)); in.close(); }
Source:
protected Map<Event, Position> analyzePosition(Position position) { Object alarms = position.getAttributes().get(Position.KEY_ALARM); Map<Event, Position> eventMap = new LinkedHashMap<>(); if (alarms != null) { String[] alarmList = alarms.toString().split(","); for (String alarm : alarmList) { Event event = new Event(Event.TYPE_ALARM, position.getDeviceId(), position.getId()); event.set(Position.KEY_ALARM, alarm); eventMap.put(event, position); } return eventMap; } return null; }

Target:
protected Map<Event, Position> analyzePosition(Position position) { Object alarms = position.getAttributes().get(Position.KEY_ALARM); if (alarms != null) { Map<Event, Position> eventMap = new LinkedHashMap<>(); String[] alarmList = alarms.toString().split(","); for (String alarm : alarmList) { Event event = new Event(Event.TYPE_ALARM, position.getDeviceId(), position.getId()); event.set(Position.KEY_ALARM, alarm); eventMap.put(event, position); } return eventMap; } return null; }
Source:
public PropertyGroupDescriptor(List<String> group) { this.group = group; }

Target:
public PropertyGroupDescriptor(List<String> group) { this.group = Collections.unmodifiableList(group); }
Source:
public void testSinglePartUnknownEncoding_throwsUnsupportedEncodingException() throws Exception { MimeMessage msg = parseWithoutRecurse(toStream( "From: <adam@example.org>\r\n" + "To: <eva@example.org>\r\n" + "Subject: Testmail\r\n" + "MIME-Version: 1.0\r\n" + "Content-type: text/plain\r\n" + "Content-Transfer-Encoding: utf-8\r\n" + "\r\n" + "dGhpcyBpcyBzb21lIG1vcmUgdGVzdCB0ZXh0Lg==\r\n")); checkAddresses(msg.getFrom(), "adam@example.org"); checkAddresses(msg.getRecipients(RecipientType.TO), "eva@example.org"); streamToString(MimeUtility.decodeBody(msg.getBody())); }

Target:
public void testSinglePartUnknownEncoding_throwsUnsupportedEncodingException() throws Exception { MimeMessage msg = parseWithoutRecurse(toStream( "From: <adam@example.org>\r\n" + "To: <eva@example.org>\r\n" + "Subject: Testmail\r\n" + "MIME-Version: 1.0\r\n" + "Content-type: text/plain\r\n" + "Content-Transfer-Encoding: utf-8\r\n" + "\r\n" + "dGhpcyBpcyBzb21lIG1vcmUgdGVzdCB0ZXh0Lg==\r\n")); MimeUtility.decodeBody(msg.getBody()); }
Source:
protected Evaluated<T> executeEvaluator(DefinitionEvaluator<T> evaluator, T definition, EvaluationContext context) throws EvaluationException { List<Integer> ownedIdSets = Context.getService(EvaluationService.class).persistIdSetsForContext(context); try { return evaluator.evaluate(definition, context); } finally { Context.getService(EvaluationService.class).deleteIdSets(ownedIdSets); } }

Target:
protected Evaluated<T> executeEvaluator(DefinitionEvaluator<T> evaluator, T definition, EvaluationContext context) throws EvaluationException { List<String> ownedIdSets = Context.getService(EvaluationService.class).startUsing(context); try { return evaluator.evaluate(definition, context); } finally { for (String idSetKey : ownedIdSets) { Context.getService(EvaluationService.class).stopUsing(idSetKey); } } }
Source:
public TaskData createTask(PrivilegeLevel level, Map<String, String> additionalAttributeValues) throws Exception { Assert.isLegal(additionalAttributeValues.containsKey(TaskAttribute.SUMMARY) && additionalAttributeValues.containsKey(TaskAttribute.DESCRIPTION), "need value for Summary and Description "); ITaskMapping initializationData = new TaskMapping() { @Override public String getProduct() { return "ManualTest"; } @Override public String getComponent() { return "ManualC1"; } }; BugzillaClient client = client(level); AbstractTaskDataHandler taskDataHandler = connector().getTaskDataHandler(); TaskAttributeMapper mapper = taskDataHandler.getAttributeMapper(repository()); TaskData taskData = new TaskData(mapper, repository().getConnectorKind(), repository().getRepositoryUrl(), ""); taskDataHandler.initializeTaskData(repository(), taskData, initializationData, null); for (String attributeKey : additionalAttributeValues.keySet()) { taskData.getRoot() .createMappedAttribute(attributeKey) .setValue(additionalAttributeValues.get(attributeKey)); } RepositoryResponse response = submitTask(taskData, client); String bugId = response.getTaskId(); return getTask(bugId, client); }

Target:
public TaskData createTask(PrivilegeLevel level, Map<String, String> additionalAttributeValues) throws Exception { Assert.isLegal(additionalAttributeValues.containsKey(TaskAttribute.SUMMARY), "need value for Summary"); Assert.isLegal(additionalAttributeValues.containsKey(TaskAttribute.DESCRIPTION), "need value for Description"); ITaskMapping initializationData = new TaskMapping() { @Override public String getProduct() { return "ManualTest"; } @Override public String getComponent() { return "ManualC1"; } }; BugzillaClient client = client(level); AbstractTaskDataHandler taskDataHandler = connector().getTaskDataHandler(); TaskAttributeMapper mapper = taskDataHandler.getAttributeMapper(repository()); TaskData taskData = new TaskData(mapper, repository().getConnectorKind(), repository().getRepositoryUrl(), ""); taskDataHandler.initializeTaskData(repository(), taskData, initializationData, null); for (String attributeKey : additionalAttributeValues.keySet()) { taskData.getRoot() .createMappedAttribute(attributeKey) .setValue(additionalAttributeValues.get(attributeKey)); } RepositoryResponse response = submitTask(taskData, client); String bugId = response.getTaskId(); return getTask(bugId, client); }
Source:
public static void setShowLogs(boolean showLogs) { Log.INITIALISED = true; SHOW_LOGS = showLogs; }

Target:
public static void setShowLogs(boolean showLogs) { Log.INITIALISED = true; Log.SHOW_LOGS = showLogs; }
Source:
@Override public boolean onCreateOptionsMenu(Menu menu) { mMapView.getMap().addDoneLoadingListener(() -> { mOperationalLayers = mMapView.getMap().getOperationalLayers(); for (int i = 0; i < mOperationalLayers.size(); i++) { menu.add(Menu.NONE, i, Menu.NONE, mOperationalLayers.get(i).getName()); menu.getItem(i).setCheckable(true); menu.getItem(i).setChecked(true); } menu.setGroupCheckable(0, true, false); }); return super.onCreateOptionsMenu(menu); }

Target:
@Override public boolean onCreateOptionsMenu(Menu menu) { mMapView.getMap().addDoneLoadingListener(() -> { mOperationalLayers = mMapView.getMap().getOperationalLayers(); for (int i = 0; i < mOperationalLayers.size(); i++) { menu.add(Menu.NONE, i, Menu.NONE, mOperationalLayers.get(i).getName()); menu.getItem(i).setCheckable(true); menu.getItem(i).setChecked(true); } }); return super.onCreateOptionsMenu(menu); }
Source:
public Builder closingWithStatus( Function<HttpHeaders, WebSocketCloseStatus> webSocketCloseStatusSupplier) { this.webSocketCloseStatusSupplier = Objects.requireNonNull( webSocketCloseStatusSupplier, "WebSocketCloseStatusSupplier must not be null"); return this; }

Target:
public Builder closingWithStatus( Function<HttpHeaders, WebSocketCloseStatus> webSocketCloseStatusSupplier) { this.webSocketCloseStatusSupplier = Objects.requireNonNull( webSocketCloseStatusSupplier, "webSocketCloseStatusSupplier must not be null"); return this; }
Source:
public void close() throws IOException { if(channel.isOpen()) { channel.force(true); channel.close(); } }

Target:
public void close() throws IOException { if(channel.isOpen()) { if (forceOnClose) { channel.force(true); } channel.close(); } }
Source:
public List<String> describeDatabases() { QueryResult result = execute(this.influxDBService.query(this.username, this.password, "SHOW+DATABASES")); List<List<Object>> databaseNames = result.getResults().get(0).getSeries().get(0).getValues(); List<String> databases = Lists.newArrayList(); if (databaseNames != null) { for (List<Object> database : databaseNames) { databases.add(database.get(0).toString()); } } return databases; }

Target:
public List<String> describeDatabases() { QueryResult result = execute(this.influxDBService.query(this.username, this.password, SHOW_DATABASE_COMMAND_ENCODED)); List<List<Object>> databaseNames = result.getResults().get(0).getSeries().get(0).getValues(); List<String> databases = Lists.newArrayList(); if (databaseNames != null) { for (List<Object> database : databaseNames) { databases.add(database.get(0).toString()); } } return databases; }
Source:
protected void onUserAction(String userActionName, Interactor interactor, Object... args) { switch (userActionName) { case UPLOAD_PORTRAIT: UserPortraitUploadInteractor userPortraitInteractor = (UserPortraitUploadInteractor) getInteractor(userActionName); Uri path = (Uri) args[0]; if (userId != 0) { userPortraitInteractor.start(new UserPortraitUploadEvent(path)); } break; case LOAD_CURRENT_USER: UserPortraitLoadInteractor userPortraitLoadInteractorCurrentUser = (UserPortraitLoadInteractor) getInteractor(userActionName); long currentUserId = SessionContext.isLoggedIn() ? SessionContext.getCurrentUser().getId() : 0; userPortraitLoadInteractorCurrentUser.start(currentUserId); break; default: UserPortraitLoadInteractor userPortraitLoadInteractor = (UserPortraitLoadInteractor) getInteractor(userActionName); if (portraitId != 0 && uuid != null) { userPortraitLoadInteractor.start(male, portraitId, uuid); } userPortraitLoadInteractor.start(userId); break; } }

Target:
protected void onUserAction(String userActionName, Interactor interactor, Object... args) { switch (userActionName) { case UPLOAD_PORTRAIT: UserPortraitUploadInteractor userPortraitInteractor = (UserPortraitUploadInteractor) getInteractor(userActionName); Uri path = (Uri) args[0]; if (userId != 0) { userPortraitInteractor.start(new UserPortraitUploadEvent(path)); } break; case LOAD_CURRENT_USER: UserPortraitLoadInteractor userPortraitLoadInteractorCurrentUser = (UserPortraitLoadInteractor) getInteractor(userActionName); long currentUserId = SessionContext.isLoggedIn() ? SessionContext.getCurrentUser().getId() : 0; userPortraitLoadInteractorCurrentUser.start(currentUserId); break; default: UserPortraitLoadInteractor userPortraitLoadInteractor = (UserPortraitLoadInteractor) getInteractor(userActionName); if (portraitId != 0 && uuid != null) { userPortraitLoadInteractor.start(male, portraitId, uuid); } else { userPortraitLoadInteractor.start(userId); } break; } }
Source:
private static void validateUpsertConfig(TableConfig tableConfig, Schema schema) { if (tableConfig.getUpsertMode() == UpsertConfig.Mode.NONE) { return; } if (schema.getPrimaryKeyColumns() == null || schema.getPrimaryKeyColumns().isEmpty()) { throw new IllegalStateException("Upsert table must have primary key columns in the schema."); } if (tableConfig.getRoutingConfig() == null || !tableConfig.getRoutingConfig().getInstanceSelectorType() .equalsIgnoreCase(RoutingConfig.REPLICA_GROUP_INSTANCE_SELECTOR_TYPE)) { throw new IllegalStateException("Upsert table must use replicaGroup as the routing config."); } if (tableConfig.getIndexingConfig() != null && tableConfig.getIndexingConfig().getStreamConfigs() != null) { StreamConfig streamConfig = new StreamConfig(tableConfig.getTableName(), tableConfig.getIndexingConfig().getStreamConfigs()); if (streamConfig.getConsumerTypes().size() != 1 || streamConfig.getConsumerTypes().get(0) != StreamConfig.ConsumerType.LOWLEVEL) { throw new IllegalStateException("Upsert table must use low-level streaming consumer type."); } } if (tableConfig.getTableType() != TableType.REALTIME) { throw new IllegalStateException("Upsert table is for realtime table only."); } }

Target:
protected static void validateUpsertConfig(TableConfig tableConfig, Schema schema) { if (tableConfig.getUpsertMode() == UpsertConfig.Mode.NONE) { return; } Preconditions .checkState(tableConfig.getTableType() == TableType.REALTIME, "Upsert table is for realtime table only."); Preconditions.checkState(CollectionUtils.isNotEmpty(schema.getPrimaryKeyColumns()), "Upsert table must have primary key columns in the schema"); Preconditions.checkState( tableConfig.getIndexingConfig() != null && tableConfig.getIndexingConfig().getStreamConfigs() != null, "streamConfig must exist in the table config"); StreamConfig streamConfig = new StreamConfig(tableConfig.getTableName(), tableConfig.getIndexingConfig().getStreamConfigs()); Preconditions.checkState(streamConfig.hasLowLevelConsumerType() && !streamConfig.hasHighLevelConsumerType(), "Upsert table must use low-level streaming consumer type"); Preconditions.checkState( tableConfig.getRoutingConfig() != null && RoutingConfig.REPLICA_GROUP_INSTANCE_SELECTOR_TYPE .equalsIgnoreCase(tableConfig.getRoutingConfig().getInstanceSelectorType()), "Upsert table must use replica-group (i.e. replicaGroup) based routing"); }
Source:
public long getRetryDelayMsFor( int dataType, long loadDurationMs, IOException exception, int errorCount) { int retryDelay = sharedPrefs.getInt("settings_retry_delay", 100);; if (!Utils.hasAnyConnection(context)) { resumeWhenNetworkConnected(); retryDelay = 1000 * sharedPrefs.getInt("settings_resume_within", 60); } if (BuildConfig.DEBUG) { Log.d(TAG, "Providing retry delay of " + retryDelay + "ms for: data type " + dataType + ", load duration: " + loadDurationMs + "ms, error count: " + errorCount + ", exception: " + exception.getClass() + ", message: " + exception.getMessage()); } return retryDelay; }

Target:
public long getRetryDelayMsFor( int dataType, long loadDurationMs, IOException exception, int errorCount) { int retryDelay = getSanitizedRetryDelaySettingsMs(); if (exception instanceof HttpDataSource.InvalidContentTypeException) { stateListener.onPlayerError(R.string.error_play_stream); return C.TIME_UNSET; } if (!Utils.hasAnyConnection(context)) { int resumeWithinS = sharedPrefs.getInt("settings_resume_within", 60); if (resumeWithinS > 0) { resumeWhenNetworkConnected(); retryDelay = 1000 * resumeWithinS + retryDelay; } } if (BuildConfig.DEBUG) { Log.d(TAG, "Providing retry delay of " + retryDelay + "ms " + "for: data type " + dataType + ", " + "load duration: " + loadDurationMs + "ms, " + "error count: " + errorCount + ", " + "exception " + exception.getClass() + ", " + "message: " + exception.getMessage()); } return retryDelay; }
Source:
public void setUp() { objectMapper = new ObjectMapper(); LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean(); validatorFactoryBean.setValidationMessageSource(messageSource); given(messageSource.getMessage(anyString(), any(Object[].class), any(Locale.class))) .willAnswer(i -> i.getArgumentAt(0, String.class)); mockMvc = MockMvcBuilders.standaloneSetup(controllersUnderTest()) .setViewResolvers(viewResolver()) .setControllerAdvice(controllerAdvice()) .setHandlerExceptionResolvers(uncheckedExceptionResolver()) .setValidator(validatorFactoryBean) .build(); }

Target:
public void setUp() { super.setUp(); given(messageSource.getMessage(anyString(), any(Object[].class), any(Locale.class))) .willAnswer(i -> i.getArgumentAt(0, String.class)); baseCandidateDto = CandidateDTO.builder().name(correctName).email(correctEmail).build(); correctCandidateDto = CandidateDTO.builder().name(correctName).email(correctEmail).phone(correctPhone) .referer(correctReferer).languageSkill(correctLanguageSkill) .description(correctDescription).build(); }
Source:
public void start(BundleContext context) throws Exception { super.start(context); fPlugin = this; try { fCommandLine = CliParserManager.getInstance().parse(Platform.getCommandLineArgs()); } catch (CliParserException e) { logError("Error parsing command line arguments", e); throw e; } }

Target:
public void start(BundleContext context) throws Exception { super.start(context); fPlugin = this; }
Source:
private Shape createRing(final int layer, final double degreeStart, final double degreeEnd, final Point2D center, final double scale) { Path result = new Path(); result.setFill(createColor(degreeStart, layer)); result.setFillRule(FillRule.EVEN_ODD); double arcSize = AbstractSunburstNode.calculateAngle(degreeStart, degreeEnd); boolean largeArc = arcSize > (AbstractSunburstNode.CIRCLEDEGREES / 2); double innerRadius = scale * (CENTER_RADIUS + (layer * RING_WIDTH)); double outerRadius = innerRadius + scale * RING_WIDTH; double angleAlpha = Math.toRadians(degreeStart); double angleAlphaNext = Math.toRadians(degreeEnd); double startX = center.getX() + innerRadius * Math.sin(angleAlpha); double startY = center.getY() - innerRadius * Math.cos(angleAlpha); MoveTo move1 = new MoveTo(startX, startY); LineTo line1To2 = createLine(outerRadius, center, angleAlpha); ArcTo arc2To3 = createArc(outerRadius, center, angleAlphaNext, true, largeArc); LineTo line3To4 = createLine(innerRadius, center, angleAlphaNext); ArcTo arc4To1 = createArc(innerRadius, center, angleAlpha, false, largeArc); result.getElements() .addAll(move1, line1To2, arc2To3, line3To4, arc4To1); return result; }

Target:
private Shape createRing(final int layer, final double degreeStart, final double degreeEnd, final Point2D center, final double scale) { Path result = new Path(); result.setFill(createColor(degreeStart, layer)); result.setFillRule(FillRule.EVEN_ODD); double arcSize = AbstractSunburstNode.calculateAngle(degreeStart, degreeEnd); boolean largeArc = arcSize > AbstractSunburstNode.CIRCLEDEGREES / 2; double innerRadius = scale * (CENTER_RADIUS + (layer * RING_WIDTH)); double outerRadius = innerRadius + scale * RING_WIDTH; double angleAlpha = Math.toRadians(degreeStart); double angleAlphaNext = Math.toRadians(degreeEnd); double startX = center.getX() + innerRadius * Math.sin(angleAlpha); double startY = center.getY() - innerRadius * Math.cos(angleAlpha); MoveTo move1 = new MoveTo(startX, startY); LineTo line1To2 = createLine(outerRadius, center, angleAlpha); ArcTo arc2To3 = createArc(outerRadius, center, angleAlphaNext, true, largeArc); LineTo line3To4 = createLine(innerRadius, center, angleAlphaNext); ArcTo arc4To1 = createArc(innerRadius, center, angleAlpha, false, largeArc); result.getElements() .addAll(move1, line1To2, arc2To3, line3To4, arc4To1); return result; }
Source:
public void componentThemeIsApplied_childThemeTextColorIsApplied() { open(); TestBenchElement myField = $(TestBenchElement.class).id(MY_POLYMER_ID); TestBenchElement input = myField.$(TestBenchElement.class) .id("vaadin-text-field-input-0"); Assert.assertEquals("Polymer text field should have red background", "rgba(255, 0, 0, 1)", input.getCssValue("background-color")); Assert.assertEquals("Polymer text field should have red background", "rgba(0, 128, 0, 1)", input.getCssValue("color")); }

Target:
public void componentThemeIsApplied_childThemeTextColorIsApplied() { open(); TestBenchElement myField = $(TestBenchElement.class).id(MY_POLYMER_ID); TestBenchElement input = myField.$(TestBenchElement.class) .id("vaadin-text-field-input-0"); Assert.assertEquals("Polymer text field should have red background", "rgba(255, 0, 0, 1)", input.getCssValue("background-color")); Assert.assertEquals("Text field should have color as green", "rgba(0, 128, 0, 1)", input.getCssValue("color")); }
Source:
public void saveOrUpdateShouldBeUnsuccessfulWhenChannelIdIsNotANumber() throws Exception { given(this.messageKeyResolver.resolveMessageOrDefault(COMMON_INVALID_INPUT_MESSAGE_KEY)).willReturn(COMMON_INVALID_INPUT_MESSAGE); given(this.messageKeyResolver.resolveMessageOrDefault(CHANNEL_NOT_FOUND_ERROR_MESSAGE_KEY)).willReturn(CHANNEL_NOT_FOUND_ERROR_MESSAGE); this.mockMvc.perform(post(REQUEST_URL_POST) .param("candidateId", STRING_VALUE_ONE) .param("position.id", STRING_VALUE_ONE).param("position.name", POSITION_NAME_DEVELOPER) .param("channel.id", TEXT).param("channel.name", CHANNEL_NAME_FACEBOOK) .param("description", DESCRIPTION)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(REDIRECT_URL_FIELD_ERROR)) .andExpect(flash().attribute("channelErrorMessage", CHANNEL_NOT_FOUND_ERROR_MESSAGE)); verifyZeroInteractions(applicationsService); then(this.candidateService).should().getCandidate(1L); then(this.positionService).should().getPositionDtoById(1L); then(this.channelService).should().getChannelDtoById(null); }

Target:
public void saveOrUpdateShouldBeUnsuccessfulWhenChannelIdIsNotANumber() throws Exception { given(this.candidateService.getCandidate(1L)).willReturn(new CandidateDTO()); given(this.positionService.getPositionDtoById(1L)).willReturn(positionDTO); given(this.channelService.getChannelDtoById(null)).willThrow(new AssertionError()); given(this.messageKeyResolver.resolveMessageOrDefault(COMMON_INVALID_INPUT_MESSAGE_KEY)).willReturn(COMMON_INVALID_INPUT_MESSAGE); given(this.messageKeyResolver.resolveMessageOrDefault(CHANNEL_NOT_FOUND_ERROR_MESSAGE_KEY)).willReturn(CHANNEL_NOT_FOUND_ERROR_MESSAGE); this.mockMvc.perform(post(REQUEST_URL_POST) .param("candidateId", STRING_VALUE_ONE) .param("position.id", STRING_VALUE_ONE).param("position.name", POSITION_NAME_DEVELOPER) .param("channel.id", TEXT).param("channel.name", CHANNEL_NAME_FACEBOOK) .param("description", DESCRIPTION)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(REDIRECT_URL_FIELD_ERROR)) .andExpect(flash().attributeCount(2)) .andExpect(flash().attribute("channelErrorMessage", CHANNEL_NOT_FOUND_ERROR_MESSAGE)); verifyZeroInteractions(applicationsService); then(this.candidateService).should().getCandidate(1L); then(this.positionService).should().getPositionDtoById(1L); then(this.channelService).should().getChannelDtoById(null); }