auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void test_PFS() { CompositeSearchKeywordResolver s = (CompositeSearchKeywordResolver) application.getSearchKeywordResolver(); s.add(new SearchKeywordResolver() { @Override public void resolve(SearchKeywordContext searchKeywordContext, UIComponent previous, String command) { } @Override public boolean matchKeyword(SearchExpressionContext searchExpressionContext, String command) { return command.startsWith("(") && command.endsWith(")"); } @Override public boolean isPassthrough(SearchExpressionContext searchExpressionContext, String command) { return true; } @Override public boolean isLeaf(SearchExpressionContext searchExpressionContext, String command) { return true; } }); UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); assertEquals("@(.myPanel #id)", resolveClientId(root, " @(.myPanel #id)")); SearchExpressionHandler handler = facesContext.getApplication().getSearchExpressionHandler(); SearchExpressionContext searchExpressionContext = SearchExpressionContext.createSearchExpressionContext(facesContext, null); Assert.assertTrue(handler.isValidExpression(searchExpressionContext, "@(.myPanel #id)")); Assert.assertFalse(handler.isValidExpression(searchExpressionContext, "@(.myPanel #id):test")); }

Target:
public void test_PFS() { CompositeSearchKeywordResolver s = (CompositeSearchKeywordResolver) application.getSearchKeywordResolver(); s.add(new SearchKeywordResolver() { @Override public void resolve(SearchKeywordContext searchKeywordContext, UIComponent previous, String keyword) { } @Override public boolean isResolverForKeyword(SearchExpressionContext searchExpressionContext, String keyword) { return keyword.startsWith("(") && keyword.endsWith(")"); } @Override public boolean isPassthrough(SearchExpressionContext searchExpressionContext, String keyword) { return true; } @Override public boolean isLeaf(SearchExpressionContext searchExpressionContext, String keyword) { return true; } }); UIComponent root = new UIPanel(); FacesContext.getCurrentInstance().getViewRoot().getChildren().add(root); assertEquals("@(.myPanel #id)", resolveClientId(root, " @(.myPanel #id)")); SearchExpressionHandler handler = facesContext.getApplication().getSearchExpressionHandler(); SearchExpressionContext searchExpressionContext = SearchExpressionContext.createSearchExpressionContext(facesContext, null); Assert.assertTrue(handler.isValidExpression(searchExpressionContext, "@(.myPanel #id)")); Assert.assertFalse(handler.isValidExpression(searchExpressionContext, "@(.myPanel #id):test")); }
Source:
public void testAUserCanCreateMeetingIfRoomIsAvailable() { HomeTabletPage home = new HomeTabletPage(); home.clickScheduleBtn(); schedule.createMeeting(organizer, subject, startTime, endTime, attendee, body, password); Assert.assertTrue(schedule.isMessageMeetingCreatedDisplayed()); }

Target:
public void testAUserCanCreateMeetingIfRoomIsAvailable() { String startTime = meetingData.get(0).get("Start time"); String endTime = meetingData.get(0).get("End time"); String attendee = meetingData.get(0).get("Attendee"); String body = meetingData.get(0).get("Body"); HomeTabletPage homePage = new HomeTabletPage(); SchedulePage schedulePage = homePage.clickScheduleBtn(); schedulePage.createMeeting(organizer, subject, startTime, endTime, attendee, body, password); Assert.assertTrue(schedulePage.isMessageMeetingCreatedDisplayed()); }
Source:
public void testGetVerifiedNegotiatedProposalWithUnrecogTransform() throws Exception { byte[] inputPacket = TestUtils.hexStringToByteArray(PROPOSAL_RAW_PACKET); mValidNegotiatedTransformSet[0] = new UnrecognizedTransform(-1, 1, new LinkedList<>()); Proposal.sTransformDecoder = new TransformDecoder() { @Override public Transform[] decodeTransforms(int count, ByteBuffer inputBuffer) throws IkeException { byte[] temp = new byte[inputBuffer.remaining()]; inputBuffer.get(temp); return mValidNegotiatedTransformSet; } }; IkeSaPayload respPayload = new IkeSaPayload(false, true, inputPacket); IkeSaPayload reqPayload = makeSaRequestPayload(); try { respPayload.getVerifiedNegotiatedProposal(reqPayload); fail("Expected to fail because negotiated proposal has unrecognized Transform."); } catch (NoValidProposalChosenException expected) { } }

Target:
public void testGetVerifiedNegotiatedProposalWithUnrecogTransform() throws Exception { byte[] inputPacket = TestUtils.hexStringToByteArray(PROPOSAL_RAW_PACKET); Transform[] negotiatedTransformSet = Arrays.copyOfRange( mValidNegotiatedTransformSet, 0, mValidNegotiatedTransformSet.length); negotiatedTransformSet[0] = new UnrecognizedTransform(-1, 1, new LinkedList<>()); Proposal.sTransformDecoder = getDummyTransformDecoder(negotiatedTransformSet); IkeSaPayload respPayload = new IkeSaPayload(false, true, inputPacket); IkeSaPayload reqPayload = makeSaRequestPayload(); try { respPayload.getVerifiedNegotiatedProposal(reqPayload); fail("Expected to fail because negotiated proposal has unrecognized Transform."); } catch (NoValidProposalChosenException expected) { } }
Source:
private void initiateDataCopyTasks() throws SemanticException { TaskTracker taskTracker = new TaskTracker(conf.getIntVar(HiveConf.ConfVars.REPL_APPROX_MAX_LOAD_TASKS)); List<Task<?>> childTasks = new ArrayList<>(); childTasks.addAll(work.externalTableCopyTasks(taskTracker, conf)); childTasks.addAll(work.managedTableCopyTasks(taskTracker, conf)); if (childTasks.isEmpty()) { finishRemainingTasks(); } else { DAGTraversal.traverse(childTasks, new AddDependencyToLeaves(TaskFactory.get(work, conf))); if (this.childTasks.isEmpty()) { this.childTasks = childTasks; } else { this.childTasks.addAll(childTasks); } } }

Target:
private void initiateDataCopyTasks() throws SemanticException { TaskTracker taskTracker = new TaskTracker(conf.getIntVar(HiveConf.ConfVars.REPL_APPROX_MAX_LOAD_TASKS)); if (childTasks == null) { childTasks = new ArrayList<>(); } childTasks.addAll(work.externalTableCopyTasks(taskTracker, conf)); childTasks.addAll(work.managedTableCopyTasks(taskTracker, conf)); if (childTasks.isEmpty()) { finishRemainingTasks(); } else { DAGTraversal.traverse(childTasks, new AddDependencyToLeaves(TaskFactory.get(work, conf))); } }
Source:
public void createUser(String userName) { try { DocumentModel userModel = userManager.getBareUserModel(); userModel.setProperty("user", "username", userName); userModel.setProperty("user", "password", userName); userManager.createUser(userModel); } catch (UserAlreadyExistsException e) { log.trace("User already exists", e); } }

Target:
public void createUser(String userName) { try { DocumentModel userModel = userManager.getBareUserModel(); userModel.setProperty("user", "username", userName); userManager.createUser(userModel); } catch (UserAlreadyExistsException e) { log.trace("User already exists", e); } }
Source:
public T getResource(){ return super.getProperties().toObject(itemClassType); }

Target:
public T getResource(){ return Utils.parse(responseBodyString, itemClassType); }
Source:
public void testOnCallDisconnectCauseChangedWithoutPermission() throws Throwable { assertHasActiveSubcriptionId(); assertThat(mOnCallDisconnectCauseChangedCalled).isFalse(); mHandler.post(() -> { mListener = new TestPhoneStateListener(); try { ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(mTelephonyManager, (tm) -> tm.listen(mListener, PhoneStateListener.LISTEN_CALL_DISCONNECT_CAUSES), "" ); fail("SecurityException should throw."); } catch (SecurityException expected) { synchronized (mLock) { mSecurityExceptionThrown = true; mLock.notify(); } } }); synchronized (mLock) { if (!mSecurityExceptionThrown) { mLock.wait(WAIT_TIME); } } assertThat(mSecurityExceptionThrown).isTrue(); assertThat(mOnCallDisconnectCauseChangedCalled).isFalse(); }

Target:
public void testOnCallDisconnectCauseChangedWithoutPermission() throws Throwable { assertHasActiveSubcriptionId(); assertThat(mOnCallDisconnectCauseChangedCalled).isFalse(); mHandler.post(() -> { mListener = new TestPhoneStateListener(); try { mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_CALL_DISCONNECT_CAUSES); fail("SecurityException should throw."); } catch (SecurityException expected) { synchronized (mLock) { mSecurityExceptionThrown = true; mLock.notify(); } } }); synchronized (mLock) { if (!mSecurityExceptionThrown) { mLock.wait(WAIT_TIME); } } assertThat(mSecurityExceptionThrown).isTrue(); assertThat(mOnCallDisconnectCauseChangedCalled).isFalse(); }
Source:
@Test void testFieldOnNonStructExpression() { final RelBuilder builder = RelBuilder.create(config().build()); IllegalStateException ex = assertThrows(IllegalStateException.class, () -> { builder.scan("EMP") .project( builder.field(builder.field("EMPNO"), "abc")) .build(); }, "Field should fail since we are trying access a field on expression with non-struct type"); assertThat(ex.getMessage(), allOf(containsString("Trying to access field"), containsString("in a type with no fields"))); }

Target:
@Test void testFieldOnNonStructExpression() { final RelBuilder builder = RelBuilder.create(config().build()); IllegalStateException ex = assertThrows(IllegalStateException.class, () -> { builder.scan("EMP") .project( builder.field(builder.field("EMPNO"), "abc")) .build(); }, "Field should fail since we are trying access a field on expression with non-struct type"); assertThat(ex.getMessage(), is("Trying to access field abc in a type with no fields: SMALLINT")); }
Source:
public void testCreateUserListInSpinner() { onBrickAtPosition(brickPosition).onVariableSpinner(R.id.insert_item_into_userlist_spinner) .performNewVariableInitial(newList); onBrickAtPosition(brickPosition).onVariableSpinner(R.id.insert_item_into_userlist_spinner) .checkShowsText(newList); }

Target:
public void testCreateUserListInSpinner() { onBrickAtPosition(brickPosition).onVariableSpinner(R.id.insert_item_into_userlist_spinner) .performNewVariableInitial(newList) .checkShowsText(newList); }
Source:
public void testScanConsumer() throws Exception { Scan scan = new Scan(); scan.setRowPrefixFilter(Bytes.toBytes(prefix)); SettableFuture<Integer> lock = SettableFuture.create(); getDefaultAsyncTable(executor).scan(scan, new ScanResultConsumer() { int count = 0; @Override public boolean onNext(Result result) { try { verify(result); count++; return true; } catch (Exception e) { lock.setException(e); return false; } } @Override public void onError(Throwable e) { lock.setException(e); } @Override public void onComplete() { lock.set(count); } }); Assert.assertEquals(2, lock.get().intValue()); }

Target:
public void testScanConsumer() throws Exception { Scan scan = new Scan(); scan.setRowPrefixFilter(Bytes.toBytes(prefix)); SettableFuture<Integer> lock = SettableFuture.create(); getDefaultAsyncTable(executor).scan(scan, new ScanResultConsumer() { int count = 0; @Override public boolean onNext(Result result) { try { verify(result); count++; return true; } catch (Exception e) { lock.setException(e); return false; } } @Override public void onError(Throwable e) { lock.setException(e); } @Override public void onComplete() { lock.set(count); } }); Assert.assertEquals(rowKeys.length, lock.get().intValue()); }
Source:
public void testInclusive() { InclusiveGateway gateway = new InclusiveGateway(); gateway.getGeneral().getName().setValue(NAME); gateway.getGeneral().getDocumentation().setValue(DOCUMENTATION); gateway.getExecutionSet().getDefaultRoute().setValue(DEFAULT_ROUTE); Node<View<BaseGateway>, ?> node = mockNode(UUID, gateway); when(propertyWriterFactory.of(any(org.eclipse.bpmn2.InclusiveGateway.class))).thenReturn(gatewayPropertyWriter); assertEquals(gatewayPropertyWriter, converter.toFlowElement(node)); verifyCommonValues(gatewayPropertyWriter, node); verify(gatewayPropertyWriter).setDefaultRoute(DEFAULT_ROUTE); verify(gatewayPropertyWriter).setGatewayDirection(node); }

Target:
public void testInclusive() { InclusiveGateway gateway = new InclusiveGateway(); gateway.getGeneral().getName().setValue(NAME); gateway.getGeneral().getDocumentation().setValue(DOCUMENTATION); gateway.getExecutionSet().getDefaultRoute().setValue(DEFAULT_ROUTE); Node<View<BaseGateway>, ?> node = newNode(UUID, gateway); when(propertyWriterFactory.of(any(org.eclipse.bpmn2.InclusiveGateway.class))).thenReturn(gatewayPropertyWriter); assertEquals(gatewayPropertyWriter, converter.toFlowElement(node)); verifyCommonValues(gatewayPropertyWriter, node); verify(gatewayPropertyWriter).setDefaultRoute(DEFAULT_ROUTE); verify(gatewayPropertyWriter).setGatewayDirection(node); }
Source:
public KafkaConsumerProxy(Consumer<K, V> kafkaConsumer, String systemName, String clientId, KafkaSystemConsumer.KafkaConsumerMessageSink messageSink, KafkaSystemConsumerMetrics samzaConsumerMetrics, String metricName) { this.kafkaConsumer = kafkaConsumer; this.systemName = systemName; this.sink = messageSink; this.kafkaConsumerMetrics = samzaConsumerMetrics; this.metricName = metricName; this.clientId = clientId; this.kafkaConsumerMetrics.registerClientProxy(metricName); consumerPollThread = new Thread(createProxyThreadRunnable()); consumerPollThread.setDaemon(true); consumerPollThread.setName( "Samza KafkaConsumerProxy Poll " + consumerPollThread.getName() + " - " + systemName); }

Target:
KafkaConsumerProxy(Consumer<K, V> kafkaConsumer, String systemName, String clientId, KafkaSystemConsumer.KafkaConsumerMessageSink messageSink, KafkaSystemConsumerMetrics samzaConsumerMetrics, String metricName) { this.kafkaConsumer = kafkaConsumer; this.systemName = systemName; this.sink = messageSink; this.kafkaConsumerMetrics = samzaConsumerMetrics; this.metricName = metricName; this.clientId = clientId; this.kafkaConsumerMetrics.registerClientProxy(metricName); consumerPollThread = new Thread(createProxyThreadRunnable()); consumerPollThread.setDaemon(true); consumerPollThread.setName( "Samza KafkaConsumerProxy Poll " + consumerPollThread.getName() + " - " + systemName); }
Source:
public void query_processing_error_707() throws Exception { FindRequest fr=new FindRequest(); fr.setQuery(query("{'$and':["+ " {'$or':["+ " {'field':'field1','op':'=','rvalue':'f1value'},"+ " {'array':'refchild.*.array','elemMatch':{"+ " '$and':["+ " {'field':'field1','op':'=','rvalue':'value1'},"+ " {'field':'field2','regex':'value2'}"+ " ]"+ " }"+ " }"+ " ]},"+ " {'field':'refchild.*.refparent.*.field2','op':'=','rvalue':true}"+ "]}")); fr.setProjection(projection("[{'field':'*'},{'field':'refchild'}]")); fr.setEntityVersion(new EntityVersion("root_loop","1.0.0.")); Response response=mediator.find(fr); System.out.println(response.getEntityData()); }

Target:
public void query_processing_error_707() throws Exception { FindRequest fr=new FindRequest(); fr.setQuery(query("{'$and':["+ " {'$or':["+ " {'field':'field1','op':'=','rvalue':'f1value'},"+ " {'array':'refchild.*.array','elemMatch':{"+ " '$and':["+ " {'field':'field1','op':'=','rvalue':'value1'},"+ " {'field':'field2','regex':'value2'}"+ " ]"+ " }"+ " }"+ " ]},"+ " {'field':'refchild.*.refparent.*.field2','op':'=','rvalue':true}"+ "]}")); fr.setProjection(projection("[{'field':'*'},{'field':'refchild'}]")); fr.setEntityVersion(new EntityVersion("root_loop","1.0.0.")); Response response=mediator.find(fr); System.out.println(response.getEntityData()); Assert.assertEquals(5,response.getMatchCount()); }
Source:
public PresenterWidget(boolean autoBind, EventBus eventBus, V view) { super(autoBind); if (view == null) { throw new IllegalArgumentException("view cannot be null"); } this.eventBus = eventBus; this.view = view; }

Target:
public PresenterWidget(boolean autoBind, EventBus eventBus, V view) { super(autoBind); assert view != null : "presenter view cannot be null"; this.eventBus = eventBus; this.view = view; }
Source:
private Button createAction(CarMenuItem item) { Context context = getContext(); Button button = new Button(context, null, 0, item.getStyleResId()); CharSequence title = item.getTitle(); button.setText(title); if (item.getIcon() != null) { Drawable icon = item.getIcon().loadDrawable(context); icon.setBounds(0, 0, mActionButtonIconBound, mActionButtonIconBound); button.setCompoundDrawables(icon, null, null, null); if (title != null && !TextUtils.isEmpty(title)) { button.setCompoundDrawablePadding(mActionButtonPadding); } } button.setEnabled(item.isEnabled()); button.setOnClickListener(v -> { CarMenuItem.OnClickListener onClickListener = item.getOnClickListener(); if (onClickListener != null) { onClickListener.onClick(item); } }); return button; }

Target:
private Button createAction(CarMenuItem item) { Context context = getContext(); Button button = new Button(context, null, 0, item.getStyleResId()); CharSequence title = item.getTitle(); button.setText(title); if (item.getIcon() != null) { Drawable icon = item.getIcon().loadDrawable(context); icon.setBounds(0, 0, mActionButtonIconBound, mActionButtonIconBound); button.setCompoundDrawables(icon, null, null, null); if (!TextUtils.isEmpty(title)) { button.setCompoundDrawablePadding(mActionButtonPadding); } } button.setEnabled(item.isEnabled()); button.setOnClickListener(v -> { CarMenuItem.OnClickListener onClickListener = item.getOnClickListener(); if (onClickListener != null) { onClickListener.onClick(item); } }); return button; }
Source:
public void addLacComplete(int rc, LedgerHandle lh, Object ctx) { if (rc != BKException.Code.OK) { LOG.warn("LastAddConfirmedUpdate failed: " + BKException.getMessage(rc)); } else { LOG.debug("Callback LAC Updated for: ", lh.getId()); } }

Target:
public void addLacComplete(int rc, LedgerHandle lh, Object ctx) { if (rc != BKException.Code.OK) { LOG.warn("LastAddConfirmedUpdate failed: ", BKException.getMessage(rc)); } else { LOG.debug("Callback LAC Updated for: ", lh.getId()); } }
Source:
private ReportMetadataInfo populateReportMetadataInfo(ReportMetadataJson reportResponse) { if (reportResponse == null) { return null; } ReportMetadataInfo reportMetadataInfo = new ReportMetadataInfo(); reportMetadataInfo.setId(reportResponse.getId()); reportMetadataInfo.setTitle(reportResponse.getTitle()); reportMetadataInfo.setColumns(reportResponse.getColumns()); reportMetadataInfo.setFilters(reportResponse.getFilters()); return reportMetadataInfo; }

Target:
private ReportMetadataInfo populateReportMetadataInfo(ReportMetadataJson reportResponse) { ReportMetadataInfo reportMetadataInfo = null; if (reportResponse != null) { reportMetadataInfo = new ReportMetadataInfo(reportResponse.getId(), reportResponse.getTitle(), reportResponse.getColumns(), reportResponse.getFilters()); } return reportMetadataInfo; }
Source:
public void testSomeUser2() { List<Integer> lightData = Lists.newArrayList(); final URL userCSVFile = Resources.getResource("insights/bedlightduration/lightDataUser2.csv"); try { final String csvString = Resources.toString(userCSVFile, Charsets.UTF_8); final String[] lightDataStringList = csvString.replaceAll("\\s+","").split(","); for (String lightDataString : lightDataStringList) { lightData.add(Integer.parseInt(lightDataString)); } } catch (IOException ioexception) { ioexception.printStackTrace(); } List<Long> timeStamps = Lists.newArrayList(); final URL timeStampCSVFile = Resources.getResource("insights/bedlightduration/timeStampUser2.csv"); try { final String csvString = Resources.toString(timeStampCSVFile, Charsets.UTF_8); final String[] timeStampStringList = csvString.replaceAll("\\s+","").replaceAll("L","").split(","); for (String timeStampString : timeStampStringList) { timeStamps.add(Long.parseLong(timeStampString)); } } catch (IOException ioexception) { ioexception.printStackTrace(); } final List<DeviceData> deviceData = Lists.newArrayList(); for (int i = 0; i < lightData.size(); i++) { final int myHour = new DateTime(timeStamps.get(i), DateTimeZone.forOffsetMillis(-25200000)).getHourOfDay(); if (myHour > 21 || myHour < 4) { deviceData.add(createNewDeviceData(lightData.get(i), new DateTime(timeStamps.get(i)))); } } final int avgLightOn = BedLightDuration.getInsightsHelper(deviceData); assertThat(avgLightOn, is(0)); }

Target:
public void testSomeUser2() throws IOException{ final List<Integer> lightData = readLightData("insights/bedlightduration/lightDataUser2.csv"); final List<Long> timeStamps = readTimeStamps("insights/bedlightduration/timeStampUser2.csv"); final List<DeviceData> deviceData = Lists.newArrayList(); for (int i = 0; i < lightData.size(); i++) { final int myHour = new DateTime(timeStamps.get(i), DateTimeZone.forOffsetMillis(-25200000)).getHourOfDay(); if (myHour > 21 || myHour < 4) { deviceData.add(createNewDeviceData(lightData.get(i), new DateTime(timeStamps.get(i)))); } } final int avgLightOn = BedLightDuration.getInsightsHelper(deviceData); assertThat(avgLightOn, is(0)); }
Source:
public void loadSchemaWithFiltering(Reader reader, final Database db, final DdlProceduresToLoad whichProcs, SQLParser.FileInfo fileInfo) throws VoltCompiler.VoltCompilerException { final LineReaderAdapter lineReader = new LineReaderAdapter(reader); DDLParserCallback callback = new DDLParserCallback() { @Override public void statement(String statement, int lineNum) throws VoltCompiler.VoltCompilerException { try { if (statement == null || statement.trim().isEmpty()) { return; } doExecuteStatement(statement.trim() + ";", lineNum); } catch (Exception e) { throw m_compiler.new VoltCompilerException(e); } } @Override public void batch(String batch, int batchEndLineNumber) throws VoltCompiler.VoltCompilerException { try { String[] parts = batch.split(";"); int currLine = batchEndLineNumber - parts.length; for (String s : parts) { if (!s.trim().isEmpty()) { doExecuteStatement(s.trim() + ";", currLine++); } } } catch (Exception e) { throw m_compiler.new VoltCompilerException(e); } } private void doExecuteStatement(String statement, int lineNum) throws VoltCompiler.VoltCompilerException { if (statement.startsWith("LOAD")) { return; } DDLStatement stmt = new DDLStatement(statement, lineNum); executeStatement(db, whichProcs, stmt); } }; try { SQLCommand.executeScriptFromReader(fileInfo, lineReader, callback); } catch (Exception e) { throw m_compiler.new VoltCompilerException(e); } try { reader.close(); } catch (IOException e) { throw m_compiler.new VoltCompilerException("Error closing schema file"); } m_tracker.addExtraClasses(m_classMatcher.getMatchedClassList()); m_classMatcher.clear(); }

Target:
public void loadSchemaWithFiltering(Reader reader, final Database db, final DdlProceduresToLoad whichProcs, SQLParser.FileInfo fileInfo) throws VoltCompiler.VoltCompilerException { final LineReaderAdapter lineReader = new LineReaderAdapter(reader); DDLParserCallback callback = new DDLParserCallback() { @Override public void statement(String statement, int lineNum) throws VoltCompiler.VoltCompilerException { try { if (statement == null || statement.trim().isEmpty()) { return; } doExecuteStatement(statement.trim() + ";", lineNum); } catch (Exception e) { throw m_compiler.new VoltCompilerException(e); } } @Override public void batch(String batch, int batchEndLineNumber) throws VoltCompiler.VoltCompilerException { try { String[] parts = batch.split(";"); int currLine = batchEndLineNumber - parts.length; for (String s : parts) { if (!s.trim().isEmpty()) { doExecuteStatement(s.trim() + ";", currLine++); } } } catch (Exception e) { throw m_compiler.new VoltCompilerException(e); } } private void doExecuteStatement(String statement, int lineNum) throws VoltCompiler.VoltCompilerException { if (statement.toUpperCase().startsWith("LOAD")) { return; } DDLStatement stmt = new DDLStatement(statement, lineNum); processVoltDBStatements(db, whichProcs, stmt); } }; try { SQLCommand.executeScriptFromReader(fileInfo, lineReader, callback); } catch (Exception e) { throw m_compiler.new VoltCompilerException(e); } finally { lineReader.close(); } m_tracker.addExtraClasses(m_classMatcher.getMatchedClassList()); m_classMatcher.clear(); }
Source:
protected void updateSamples() { calculateProbes(samples, dynamicLatencyProbeInterval); if (!StorageService.instance.isGossipActive()) return; schedulePings(samples); }

Target:
protected void updateSamples() { long updateIntervalMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - lastUpdateSamplesNanos); lastUpdateSamplesNanos = System.nanoTime(); calculateProbes(samples, updateIntervalMillis); if (!StorageService.instance.isGossipActive()) return; scheduleProbes(samples); }
Source:
public ModelAndView registerUser(@ModelAttribute Users user) { user.setUserStatus("A"); java.util.Date date = Calendar.getInstance().getTime(); user.setLastModifieddate(date); user.setRegistrationDate(date); System.out.println("9999"+user.getUserpii()); user.setUserId(user.getUserpii().getUserId()); user.getUserpii().setDateOfBirth(date); userService.insertRow(user); return new ModelAndView("user_creation", "user", new Users()); }

Target:
public ModelAndView registerUser(@ModelAttribute Users user) { user.setUserStatus("Inactive"); java.util.Date date = Calendar.getInstance().getTime(); user.setLastModifieddate(date); user.setRegistrationDate(date); System.out.println("9999"+user.getUserpii()); user.setUserId(user.getUserpii().getUserId()); user.getUserpii().setDateOfBirth(date); userService.insertRow(user); return new ModelAndView("user_creation", "user", new Users()); }
Source:
private Map<String, String> filterHeaders(Map<String, String> headers, Set<String> filteredHeaderNames) { if (filteredHeaderNames.isEmpty()) { return ImmutableMap.of(); } return headers.entrySet().stream() .filter(e -> filteredHeaderNames.stream().anyMatch(h -> h.equalsIgnoreCase(e.getKey()))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); }

Target:
private Map<String, String> filterHeaders(Map<String, String> headers, Set<String> filteredHeaderNames) { if (filteredHeaderNames.isEmpty()) { return ImmutableMap.of(); } return headers.entrySet().stream() .filter(e -> filteredHeaderNames.contains(e.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); }
Source:
private static String getObaRegionName() { String regionName = null; ObaRegion region = Application.get().getCurrentRegion(); if (region != null && region.getName() != null) { regionName = region.getName(); } else if (Application.get().getCustomApiUrl() != null) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA-1"); digest.update(Application.get().getCustomApiUrl().getBytes()); regionName = Application.getHex(digest.digest()); } catch (Exception e) { regionName = Application.get().getString(R.string.analytics_label_custom_url); } } else { regionName = Application.get().getString(R.string.analytics_label_custom_url); } return regionName; }

Target:
private static String getObaRegionName() { String regionName = null; ObaRegion region = Application.get().getCurrentRegion(); if (region != null && region.getName() != null) { regionName = region.getName(); } else if (Application.get().getCustomApiUrl() != null) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA-1"); digest.update(Application.get().getCustomApiUrl().getBytes()); regionName = Application.get().getString(R.string.analytics_label_custom_url) + ": " + Application.getHex(digest.digest()); } catch (Exception e) { regionName = Application.get().getString(R.string.analytics_label_custom_url); } } else { regionName = Application.get().getString(R.string.analytics_label_custom_url); } return regionName; }
Source:
public void close() { synchronized (this) { closed.set(true); if (currentLogWatch != null) { currentLogWatch.close(); } } }

Target:
public void close() { synchronized (this) { closed = true; if (currentLogWatch != null) { currentLogWatch.close(); } } }
Source:
public void removeNode(final @Nonnull Node node) throws IOException { if (node == nodes.get(node.getNodeName())) { Queue.withLock(new Runnable() { @Override public void run() { Computer c = node.toComputer(); if (c != null) { c.recordTermination(); c.disconnect(OfflineCause.create(hudson.model.Messages._Hudson_NodeBeingRemoved())); for(Executor executor: c.getAllExecutors()){ executor.interrupt(Result.ABORTED, new CauseOfInterruption() { @Override public String getShortDescription() { return "Node was removed by " + User.current().getId(); } }); } } if (node == nodes.remove(node.getNodeName())) { jenkins.updateComputerList(); jenkins.trimLabels(); } } }); Util.deleteRecursive(new File(getNodesDir(), node.getNodeName())); NodeListener.fireOnDeleted(node); } }

Target:
public void removeNode(final @Nonnull Node node) throws IOException { if (node == nodes.get(node.getNodeName())) { Queue.withLock(new Runnable() { @Override public void run() { Computer c = node.toComputer(); if (c != null) { c.recordTermination(); c.disconnect(OfflineCause.create(hudson.model.Messages._Hudson_NodeBeingRemoved())); for(Executor executor: c.getAllExecutors()){ executor.interrupt(Result.ABORTED, new CauseOfInterruption() { @Override public String getShortDescription() { return "Node was removed by " + (User.current() == null ? "(no user)" : User.current().getId()); } }); } } if (node == nodes.remove(node.getNodeName())) { jenkins.updateComputerList(); jenkins.trimLabels(); } } }); Util.deleteRecursive(new File(getNodesDir(), node.getNodeName())); NodeListener.fireOnDeleted(node); } }
Source:
private void setupListener(AbstractMessageListenerContainer container, String queue) { Listeners listenersForQueue = this.listeners.get(queue); if (listenersForQueue == null) { this.listeners.put(queue, new Listeners(container.getMessageListener())); } else { listenersForQueue.listeners.add(container.getMessageListener()); } }

Target:
private void setupListener(AbstractMessageListenerContainer container, String queue) { this.listeners.computeIfAbsent(queue, v -> new Listeners()).listeners.add(container.getMessageListener()); }
Source:
Class getInputClass() { return inputClass; }

Target:
Class<? extends Input> getInputClass() { return inputClass; }
Source:
public List<BinaryContent> transform( Metacard metacard, String transformerId, Map<String, Serializable> requestProperties) throws CatalogTransformerException { if (metacard == null) { throw new IllegalArgumentException("Metacard is null."); } List<MultiMetacardTransformer> multiMetacardTransformers = frameworkProperties .getTransformerLocator() .findMultiMetacardTransformersByFilter( "(|" + "(" + Constants.SERVICE_SHORTNAME + "=" + transformerId + ")" + "(" + Constants.SERVICE_ID + "=" + transformerId + ")" + ")"); if (CollectionUtils.isEmpty(multiMetacardTransformers)) { throw new IllegalArgumentException("Transformer " + transformerId + " not found"); } return multiMetacardTransformers .get(0) .transform(Collections.singletonList(metacard), requestProperties); }

Target:
public List<BinaryContent> transform( Metacard metacard, String transformerId, Map<String, Serializable> requestProperties) throws CatalogTransformerException { return frameworkProperties .getTransform() .transform(Collections.singletonList(metacard), transformerId, requestProperties); }
Source:
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { if (viewType == TYPE_PARENT) { return onCreateParentViewHolder(viewGroup); } else if (viewType == TYPE_CHILD) { return onCreateChildViewHolder(viewGroup); } else { return null; } }

Target:
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { if (viewType == TYPE_PARENT) { return onCreateParentViewHolder(viewGroup); } else if (viewType == TYPE_CHILD) { return onCreateChildViewHolder(viewGroup); } else { throw new IllegalStateException("Incorrect ViewType found"); } }
Source:
public Boolean checkThatServerExists(String serverName) { List<WebElement> webElements = loadPageDriverWait.until( visibilityOfAllElementsLocatedBy( By.xpath(" for (WebElement we : webElements) { if (we.getText().equals(serverName)) { return true; } } return false; }

Target:
public boolean checkThatServerExists(String serverName) { List<WebElement> webElements = loadPageDriverWait.until( visibilityOfAllElementsLocatedBy( By.xpath(" for (WebElement we : webElements) { if (we.getText().equals(serverName)) { return true; } } return false; }
Source:
public int compare(Object obj1, Object obj2) { ItemType type1 = ItemTypeHelper.getOrderByItemType(obj1); ItemType type2 = ItemTypeHelper.getOrderByItemType(obj2); int cmp = Integer.compare(type1.getVal(), type2.getVal()); if (cmp != 0) { return cmp; } switch (type1) { case NoValue: case Null: return 0; case Boolean: return Boolean.compare((Boolean) obj1, (Boolean) obj2); case Number: return Double.compare(((Number) obj1).doubleValue(), ((Number) obj2).doubleValue()); case String: return ((String) obj1).compareTo((String) obj2); case ArrayNode: case ObjectNode: try{ UInt128 hash1 = DistinctHash.getHash(obj1); UInt128 hash2 = DistinctHash.getHash(obj2); return hash1.compareTo(hash2); } catch (IOException e) { throw new IllegalStateException(String.format("Exception for getting has %s", e)); } default: throw new ClassCastException(String.format("Unexpected type: %s", type1.toString())); } }

Target:
public int compare(Object obj1, Object obj2) { ItemType type1 = ItemTypeHelper.getOrderByItemType(obj1); ItemType type2 = ItemTypeHelper.getOrderByItemType(obj2); int cmp = Integer.compare(type1.getVal(), type2.getVal()); if (cmp != 0) { return cmp; } switch (type1) { case NoValue: case Null: return 0; case Boolean: return Boolean.compare((Boolean) obj1, (Boolean) obj2); case Number: return Double.compare(((Number) obj1).doubleValue(), ((Number) obj2).doubleValue()); case String: return ((String) obj1).compareTo((String) obj2); case ArrayNode: case ObjectNode: try{ UInt128 hash1 = DistinctHash.getHash(obj1); UInt128 hash2 = DistinctHash.getHash(obj2); return hash1.compareTo(hash2); } catch (IOException e) { throw new IllegalStateException(String.format("Getting hash exception for type %s ", type1.toString()), e); } default: throw new ClassCastException(String.format("Unexpected type: %s", type1.toString())); } }
Source:
public static Deferred<TSMeta> parseFromColumn(final TSDB tsdb, final KeyValue column, final boolean load_uidmetas) { if (column.value() == null || column.value().length < 1) { throw new IllegalArgumentException("Empty column value"); } final TSMeta parsedMeta = JSON.parseToObject(column.value(), TSMeta.class); if (parsedMeta.tsuid == null || parsedMeta.tsuid.isEmpty()) { parsedMeta.tsuid = UniqueId.uidToString(column.key()); } Deferred<TSMeta> meta = getFromStorage(tsdb, UniqueId.stringToUid(parsedMeta.tsuid)); if (!load_uidmetas) { return meta; } return meta.addCallbackDeferring(new LoadUIDs(tsdb, parsedMeta.tsuid)); }

Target:
public static Deferred<TSMeta> parseFromColumn(final TSDB tsdb, final KeyValue column, final boolean load_uidmetas) { if (column.value() == null || column.value().length < 1) { throw new IllegalArgumentException("Empty column value"); } final TSMeta parsed_meta = JSON.parseToObject(column.value(), TSMeta.class); if (parsed_meta.tsuid == null || parsed_meta.tsuid.isEmpty()) { parsed_meta.tsuid = UniqueId.uidToString(column.key()); } Deferred<TSMeta> meta = getFromStorage(tsdb, UniqueId.stringToUid(parsed_meta.tsuid)); if (!load_uidmetas) { return meta; } return meta.addCallbackDeferring(new LoadUIDs(tsdb, parsed_meta.tsuid)); }
Source:
public static PGType get(DataType type) { if (type instanceof CollectionType) { DataType<?> innerType = ((CollectionType) type).innerType(); if (innerType instanceof CollectionType) { return JsonType.INSTANCE; } else if (innerType.id() == ObjectType.ID) { return PGArray.JSON_ARRAY; } } else if (type.id() == ObjectType.ID) { return JsonType.INSTANCE; } PGType pgType = CRATE_TO_PG_TYPES.get(type); if (pgType == null) { throw new IllegalArgumentException( String.format(Locale.ENGLISH, "No type mapping from '%s' to pg_type", type.getName())); } return pgType; }

Target:
public static PGType get(DataType type) { if (type instanceof CollectionType) { DataType<?> innerType = ((CollectionType) type).innerType(); if (DataTypes.isCollectionType(innerType) || innerType.id() == ObjectType.ID) { return JsonType.INSTANCE; } } else if (type.id() == ObjectType.ID) { return JsonType.INSTANCE; } PGType pgType = CRATE_TO_PG_TYPES.get(type); if (pgType == null) { throw new IllegalArgumentException( String.format(Locale.ENGLISH, "No type mapping from '%s' to pg_type", type.getName())); } return pgType; }
Source:
public void testFlushedIfAppendFailedWithBucketClosedException() throws Exception { sink = new HDFSEventSink() { @Override BucketWriter initializeBucketWriter(String realPath, String realName, String lookupPath, HDFSWriter hdfsWriter, WriterCallback closeCallback) { BucketWriter bw = Mockito.spy(super.initializeBucketWriter(realPath, realName, lookupPath, hdfsWriter, closeCallback)); try { Mockito.doCallRealMethod() .doThrow(BucketClosedException.class) .when(bw).append(Mockito.any(Event.class)); } catch (IOException | InterruptedException e) { Assert.fail("This shouldn't happen, as append() is called during mocking."); } return bw; } }; Context context = new Context(ImmutableMap.of("hdfs.path", testPath)); Configurables.configure(sink, context); MemoryChannel channel = new MemoryChannel(); Configurables.configure(channel, new Context()); sink.setChannel(channel); sink.start(); Transaction txn = channel.getTransaction(); txn.begin(); channel.put(EventBuilder.withBody("test".getBytes())); channel.put(EventBuilder.withBody("test".getBytes())); txn.commit(); txn.close(); sink.process(); Map<String, BucketWriter> bucketWriterMap = sink.getSfWriters(); Assert.assertEquals(1, bucketWriterMap.size()); BucketWriter bw = bucketWriterMap.values().iterator().next(); Mockito.verify(bw, Mockito.times(1)).flush(); sink.stop(); }

Target:
public void testFlushedIfAppendFailedWithBucketClosedException() throws Exception { final Set<BucketWriter> bucketWriters = new HashSet<>(); sink = new HDFSEventSink() { @Override BucketWriter initializeBucketWriter(String realPath, String realName, String lookupPath, HDFSWriter hdfsWriter, WriterCallback closeCallback) { BucketWriter bw = Mockito.spy(super.initializeBucketWriter(realPath, realName, lookupPath, hdfsWriter, closeCallback)); try { Mockito.doCallRealMethod() .doThrow(BucketClosedException.class) .when(bw).append(Mockito.any(Event.class)); } catch (IOException | InterruptedException e) { Assert.fail("This shouldn't happen, as append() is called during mocking."); } bucketWriters.add(bw); return bw; } }; Context context = new Context(ImmutableMap.of("hdfs.path", testPath)); Configurables.configure(sink, context); Channel channel = Mockito.spy(new MemoryChannel()); Configurables.configure(channel, new Context()); final Iterator<Event> events = Iterators.forArray( EventBuilder.withBody("test1".getBytes()), EventBuilder.withBody("test2".getBytes())); Mockito.doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return events.hasNext() ? events.next() : null; } }).when(channel).take(); sink.setChannel(channel); sink.start(); sink.process(); Mockito.verify(channel, Mockito.times(3)).take(); FileSystem fs = FileSystem.get(new Configuration()); int fileCount = 0; for (RemoteIterator<LocatedFileStatus> i = fs.listFiles(new Path(testPath), false); i.hasNext(); i.next()) { fileCount++; } Assert.assertEquals(2, fileCount); Assert.assertEquals(2, bucketWriters.size()); for (BucketWriter bw : bucketWriters) { Mockito.verify(bw, Mockito.times(1)).flush(); } sink.stop(); }
Source:
private static CorfuRuntime getRuntimeAndConnect(String configurationString) { return CorfuRuntime.fromParameters(CorfuRuntime.CorfuRuntimeParameters.builder() .useFastLoader(false) .cacheDisabled(true) .tlsEnabled(true) .keyStore("/config/cluster-manager/corfu/private/keystore.jks") .ksPasswordFile("/config/cluster-manager/corfu/private/keystore.password") .trustStore("/config/cluster-manager/corfu/public/truststore.jks") .tsPasswordFile("/config/cluster-manager/corfu/public/truststore.password") .build()) .parseConfigurationString(configurationString) .connect(); }

Target:
private static CorfuRuntime getRuntimeAndConnect(String configurationString) { return CorfuRuntime.fromParameters(CorfuRuntime.CorfuRuntimeParameters.builder() .useFastLoader(false) .cacheDisabled(true) .tlsEnabled(false) .build()) .parseConfigurationString(configurationString) .connect(); }
Source:
public static void main( String[] args ) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { if (args.length == 0) { SelectMethod(); } else if (args.length == 1) { RunMethod(args[0]); return; } else { ShowUsage(); } System.out.println(""); System.out.print("Press <Return> to finish ..."); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ int i = Integer.parseInt(br.readLine()); }catch(Exception ex) { } }

Target:
public static void main( String[] args ) { if (args.length == 0) { SelectMethod(); } else if (args.length == 1) { RunMethod(args[0]); return; } else { ShowUsage(); } System.out.println(""); System.out.print("Press <Return> to finish ..."); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ int i = Integer.parseInt(br.readLine()); }catch(Exception ex) { } }
Source:
public void testWrap() { IntObjectMap<Object> map = new SynchronizedIntObjectHashMap<>(); StreamIdSupplier s = new StreamIdSupplier(Integer.MAX_VALUE - 3); assertEquals(2147483646, s.nextStreamId(map)); assertEquals(0, s.nextStreamId(map)); assertEquals(2, s.nextStreamId(map)); s = new StreamIdSupplier(Integer.MAX_VALUE - 2); assertEquals(2147483647, s.nextStreamId(map)); assertEquals(1, s.nextStreamId(map)); assertEquals(3, s.nextStreamId(map)); }

Target:
public void testWrap() { IntObjectMap<Object> map = new SynchronizedIntObjectHashMap<>(); StreamIdSupplier s = new StreamIdSupplier(Integer.MAX_VALUE - 3); assertEquals(2147483646, s.nextStreamId(map)); assertEquals(2, s.nextStreamId(map)); assertEquals(4, s.nextStreamId(map)); s = new StreamIdSupplier(Integer.MAX_VALUE - 2); assertEquals(2147483647, s.nextStreamId(map)); assertEquals(1, s.nextStreamId(map)); assertEquals(3, s.nextStreamId(map)); }
Source:
private void validateAuth(DescriptorProperties properties) { properties.validateString(CONNECTOR_USERNAME, true); properties.validateString(CONNECTOR_PASSWORD, true); }

Target:
private void validateAuth(DescriptorProperties properties) { if (properties.containsKey(CONNECTOR_USERNAME) || properties.containsKey(CONNECTOR_PASSWORD)) { properties.validateString(CONNECTOR_USERNAME, false, 1); properties.validateString(CONNECTOR_PASSWORD, false, 1); } }
Source:
public SSHKeyAuthenticatorImpl(final SSHKeyStoreService keyStoreService, final Instance<WorkbenchUserManager> workbenchUserManagerInstance) { this.keyStoreService = keyStoreService; if (!workbenchUserManagerInstance.isUnsatisfied() && !workbenchUserManagerInstance.isAmbiguous()) { this.userManager = workbenchUserManagerInstance.get(); } else { LOGGER.warn("Cannot find any implmenentation of 'WorkbenchUserManager'. Loading default implemntation from SSH module"); this.userManager = this::getUser; } }

Target:
public SSHKeyAuthenticatorImpl(final SSHKeyStoreService keyStoreService, final Instance<WorkbenchUserManager> workbenchUserManagerInstance) { this.keyStoreService = keyStoreService; if (!workbenchUserManagerInstance.isUnsatisfied() && !workbenchUserManagerInstance.isAmbiguous()) { this.userManager = workbenchUserManagerInstance.get(); } else { LOGGER.warn("Cannot find any implementation of 'WorkbenchUserManager'. Loading default implementation on SSH module"); this.userManager = this::getUser; } }
Source:
protected void onSetUpAfterOpeningDesignerPerspective() throws Exception { sessionAirdResource = new UIResource(designerProject, "/", REPRESENTATIONS_RESOURCE_NAME); localSession = designerPerspective.openSessionFromFile(sessionAirdResource, true); session = localSession.getOpenedSession(); uiTableRepresentation = localSession.getLocalSessionBrowser().perCategory().selectViewpoint("manualAird").selectRepresentation("manualAirdTable") .selectRepresentationInstance("manualAirdTable", UITableRepresentation.class).open(); dTable = uiTableRepresentation.getTable(); tableEditor = uiTableRepresentation.getEditor(); uiTreeRepresentation = localSession.getLocalSessionBrowser().perCategory().selectViewpoint("manualAird").selectRepresentation("manualAirdTree") .selectRepresentationInstance("manualAirdTree", UITreeRepresentation.class).open(); treeEditor = uiTreeRepresentation.getEditor(); airdResourceUri = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(sessionAirdResource.getFullPath())).getRawLocationURI(); }

Target:
protected void onSetUpAfterOpeningDesignerPerspective() throws Exception { sessionAirdResource = new UIResource(designerProject, "/", REPRESENTATIONS_RESOURCE_NAME); localSession = designerPerspective.openSessionFromFile(sessionAirdResource, true); session = localSession.getOpenedSession(); tableEditor = openRepresentation(localSession.getOpenedSession(), "manualAirdTable", "manualAirdTable", DTable.class); tableTree = tableEditor.bot().tree(); treeEditor = openRepresentation(localSession.getOpenedSession(), "manualAirdTree", "manualAirdTree", DTree.class); airdResourceUri = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(sessionAirdResource.getFullPath())).getRawLocationURI(); }
Source:
public QueryContext checkForDerivativeContextAndReturn(int newScope) { QueryContext newContext = potentialSpawnedContext; potentialSpawnedContext = null; if(potentialSpawnedContext == null) { newContext = new QueryContext(this);} newContext.contextScope = newScope; if(dominates(newContext.contextScope, this.contextScope)) { this.reportContextEscalation(this, newContext, "New"); return newContext; } else { return this; } }

Target:
public QueryContext checkForDerivativeContextAndReturn(int newScope) { QueryContext newContext; potentialSpawnedContext = null; newContext = new QueryContext(this); newContext.contextScope = newScope; if (dominates(newContext.contextScope, this.contextScope)) { this.reportContextEscalation(newContext, "New"); return newContext; } else { return this; } }
Source:
public void testRebalanceThreadPoolSize() { GridStringLogger gridStringLogger = new GridStringLogger(); gridStringLogger.logLength(1024 * 100); IgniteConfiguration cci = Config.getServerConfiguration().setClientMode(true); cci.setRebalanceThreadPoolSize(cci.getSystemThreadPoolSize()); cci.setGridLogger(gridStringLogger); try ( Ignite si = Ignition.start(Config.getServerConfiguration()); Ignite ci = Ignition.start(cci);) { Set<ClusterNode> collect = si.cluster().nodes().stream().filter(new Predicate<ClusterNode>() { @Override public boolean test(ClusterNode clusterNode) { return clusterNode.isClient(); } }).collect(Collectors.toSet()); String log = gridStringLogger.toString(); boolean containsMessage = log.contains("Setting the rebalance pool size has no effect on the client mode"); Assert.assertTrue(containsMessage); Assert.assertEquals(1, collect.size()); } catch (Exception e) { Assert.fail(); } }

Target:
public void testRebalanceThreadPoolSize() { GridStringLogger gridStringLogger = new GridStringLogger(); gridStringLogger.logLength(1024 * 100); IgniteConfiguration cci = Config.getServerConfiguration().setClientMode(true); cci.setRebalanceThreadPoolSize(cci.getSystemThreadPoolSize()); cci.setGridLogger(gridStringLogger); try ( Ignite si = Ignition.start(Config.getServerConfiguration()); Ignite ci = Ignition.start(cci);) { Set<ClusterNode> collect = si.cluster().nodes().stream() .filter(new Predicate<ClusterNode>() { @Override public boolean test(ClusterNode clusterNode) { return clusterNode.isClient(); } }) .collect(Collectors.toSet()); String log = gridStringLogger.toString(); boolean containsMessage = log.contains("Setting the rebalance pool size has no effect on the client mode"); Assert.assertTrue(containsMessage); Assert.assertEquals(1, collect.size()); } }
Source:
public void setUp() { mockedConfig1 = createMockConfig("Config1"); mockedConfig2 = createMockConfig("Config2"); availableConfigs = new ArrayList<Config>(); availableConfigs.add(mockedConfig1); availableConfigs.add(mockedConfig2); PythonInterface mockPythonInterface = mock(PythonInterface.class); when(mockPythonInterface.getActionDefinitions()).thenReturn(availableConfigs); configLoader = new ConfigLoader(mockPythonInterface); }

Target:
public void setUp() { mockedConfig1 = createMockConfig("Config1"); mockedConfig2 = createMockConfig("Config2"); availableConfigs = new ArrayList<Config>(); availableConfigs.add(mockedConfig1); availableConfigs.add(mockedConfig2); mockPythonInterface = mock(PythonInterface.class); when(mockPythonInterface.getActionDefinitions()).thenReturn(availableConfigs); configLoader = new ConfigLoader(mockPythonInterface); }