method2testcases stringlengths 118 3.08k |
|---|
### Question:
DecomposeJsonUtil implements Serializable { public static VnfResource jsonToVnfResource(String jsonString) throws JsonDecomposingException { try { return OBJECT_MAPPER.readValue(jsonString, VnfResource.class); } catch (IOException e) { throw new JsonDecomposingException("Exception while converting json to vnf resource", e); } } private DecomposeJsonUtil(); static ServiceDecomposition jsonToServiceDecomposition(String jsonString); static ServiceDecomposition jsonToServiceDecomposition(String jsonString, String serviceInstanceId); static VnfResource jsonToVnfResource(String jsonString); static NetworkResource jsonToNetworkResource(String jsonString); static AllottedResource jsonToAllottedResource(String jsonString); static ConfigResource jsonToConfigResource(String jsonString); }### Answer:
@Test public void testJsonToVnfResource() throws JsonDecomposingException { vnfResource = createVnfResourceData(); VnfResource vnfResourceObj = DecomposeJsonUtil.jsonToVnfResource(vnfResource.toString()); assertEquals(vnfResource.getResourceId(), vnfResourceObj.getResourceId()); }
@Test public void testJsonToVnfResource_JsonDecomposingException() throws JsonDecomposingException { expectedException.expect(JsonDecomposingException.class); networkResource = createNetworkResourceData(); VnfResource vnfResourceObj = DecomposeJsonUtil.jsonToVnfResource(networkResource.toString()); } |
### Question:
DecomposeJsonUtil implements Serializable { public static NetworkResource jsonToNetworkResource(String jsonString) throws JsonDecomposingException { try { return OBJECT_MAPPER.readValue(jsonString, NetworkResource.class); } catch (IOException e) { throw new JsonDecomposingException("Exception while converting json to network resource", e); } } private DecomposeJsonUtil(); static ServiceDecomposition jsonToServiceDecomposition(String jsonString); static ServiceDecomposition jsonToServiceDecomposition(String jsonString, String serviceInstanceId); static VnfResource jsonToVnfResource(String jsonString); static NetworkResource jsonToNetworkResource(String jsonString); static AllottedResource jsonToAllottedResource(String jsonString); static ConfigResource jsonToConfigResource(String jsonString); }### Answer:
@Test public void testJsonToNetworkResource() throws JsonDecomposingException { networkResource = createNetworkResourceData(); NetworkResource networkResourceObj = DecomposeJsonUtil.jsonToNetworkResource(networkResource.toString()); assertEquals(networkResource.getResourceId(), networkResourceObj.getResourceId()); }
@Test public void testJsonToNetworkResource_JsonDecomposingException() throws JsonDecomposingException { expectedException.expect(JsonDecomposingException.class); vnfResource = createVnfResourceData(); NetworkResource networkResourceObj = DecomposeJsonUtil.jsonToNetworkResource(vnfResource.toString()); } |
### Question:
RelativeScaleFactor extends ScaleFactor { @Override public int apply(int currentSize, Action action) { int newSize = Math.round(currentSize * new Double(getFactor()).floatValue()); if(action instanceof ScaleInAction) { newSize = Math.round(currentSize * new Double(Math.pow(getFactor(), -1)).floatValue()); if(newSize < 1) { newSize = 1; } } return newSize; } RelativeScaleFactor(double factor); @Override int apply(int currentSize, Action action); }### Answer:
@Test public void testRelativeFactorApplyWithScaleIn() { System.out.println("testRelativeFactorApply"); RelativeScaleFactor factor; factor = new RelativeScaleFactor(2); assertEquals("New scaling size is incorrect", 5, factor.apply(10, new ScaleInAction())); assertEquals("New scaling size is incorrect", 2, factor.apply(4, new ScaleInAction())); assertEquals("New scaling size is incorrect", 1, factor.apply(2, new ScaleInAction())); assertEquals("New size is less than 1 after scaling in", 1, factor.apply(1, new ScaleInAction())); }
@Test public void testRelativeFactorApplyWithScaleOut() { System.out.println("testRelativeFactorApply"); RelativeScaleFactor factor; factor = new RelativeScaleFactor(2); assertEquals("New scaling size is incorrect", 2, factor.apply(1, new ScaleOutAction())); assertEquals("New scaling size is incorrect", 4, factor.apply(2, new ScaleOutAction())); assertEquals("New scaling size is incorrect", 10, factor.apply(5, new ScaleOutAction())); } |
### Question:
AbsoluteScaleConstraint extends ScaleConstraint { public boolean evaluate(int scaledSize) { return (scaledSize > getValue()); } AbsoluteScaleConstraint(int constraint); boolean evaluate(int scaledSize); }### Answer:
@Test public void testAbsoluteConstraintExceeded() { System.out.println("testAbsoluteConstraintExceeded"); AbsoluteScaleConstraint constraint; constraint = new AbsoluteScaleConstraint(10); assertFalse("Constraint should not be exceeded by 1", constraint.evaluate(1)); assertFalse("Constraint should not be exceeded by 5", constraint.evaluate(5)); assertFalse("Constraint should not be exceeded by 10", constraint.evaluate(10)); assertTrue("Constraint should be exceeded by 20", constraint.evaluate(20)); } |
### Question:
MetricThresholdAbove extends MetricThreshold { @Override public boolean evaluate(MetricValue value) { return value.convertTo(getThreshold().getUnit()).getValue() > getThreshold().getValue(); } MetricThresholdAbove(MetricValue threshold); @Override boolean evaluate(MetricValue value); }### Answer:
@Test public void testThresholdEvaluation() { System.out.println("testThresholdEvaluation"); MetricValue thresholdValue = new MetricValue(); thresholdValue.setValue(10); thresholdValue.setUnit(MetricUnit.GIGABYTES); MetricThresholdAbove threshold = new MetricThresholdAbove(thresholdValue); MetricValue value = new MetricValue(); value.setValue(20); value.setUnit(MetricUnit.GIGABYTES); assertTrue("The value is below the threshold", threshold.evaluate(value)); }
@Test public void testThresholdEvaluationWithUnitConversion() { System.out.println("testThresholdEvaluationWithUnitConversion"); MetricValue thresholdValue = new MetricValue(); thresholdValue.setValue(20); thresholdValue.setUnit(MetricUnit.MEGABYTES); MetricThresholdAbove threshold = new MetricThresholdAbove(thresholdValue); MetricValue value = new MetricValue(); value.setValue(1); value.setUnit(MetricUnit.GIGABYTES); assertTrue("The value is below the threshold", threshold.evaluate(value)); } |
### Question:
MetricThresholdBelow extends MetricThreshold { @Override public boolean evaluate(MetricValue value) { return value.convertTo(getThreshold().getUnit()).getValue() < getThreshold().getValue(); } MetricThresholdBelow(MetricValue threshold); @Override boolean evaluate(MetricValue value); }### Answer:
@Test public void testThresholdEvaluation() { System.out.println("testThresholdEvaluation"); MetricValue thresholdValue = new MetricValue(); thresholdValue.setValue(10); thresholdValue.setUnit(MetricUnit.GIGABYTES); MetricThresholdBelow threshold = new MetricThresholdBelow(thresholdValue); MetricValue value = new MetricValue(); value.setValue(1); value.setUnit(MetricUnit.GIGABYTES); assertTrue("The value is below the threshold", threshold.evaluate(value)); }
@Test public void testThresholdEvaluationWithUnitConversion() { System.out.println("testThresholdEvaluationWithUnitConversion"); MetricValue thresholdValue = new MetricValue(); thresholdValue.setValue(10); thresholdValue.setUnit(MetricUnit.GIGABYTES); MetricThresholdBelow threshold = new MetricThresholdBelow(thresholdValue); MetricValue value = new MetricValue(); value.setValue(500); value.setUnit(MetricUnit.MEGABYTES); assertTrue("The value is below the threshold", threshold.evaluate(value)); } |
### Question:
PolicyRulesEvaluator extends AbstractEvaluator<PolicyRules, InfrastructureAdaptor, MetricReadingProvider> { @Override public synchronized void evaluate(MetricReadingProvider provider) { routeReadingToEvaluators(provider); } PolicyRulesEvaluator(final PolicyRules rules,
final InfrastructureAdaptor adaptor); @Override synchronized void evaluate(MetricReadingProvider provider); }### Answer:
@Test public void testAllNullNoExceptionThrown() { System.out.println("testAllNullNoExceptionThrown"); try { PolicyRulesEvaluator evaluator = new PolicyRulesEvaluator(null, null); evaluator.evaluate(null); } catch(Exception e) { fail("No excetion should be thrown by PolicyRulesEvaluator"); } }
@Test public void testEvaluateNoRulesWithoutWildcard() { System.out.println("testEvaluateNoRulesWithoutWildcard"); InfrastructureAdaptor mockAdaptor = mock(InfrastructureAdaptor.class); MetricReadingProvider mockProvider = mock(MetricReadingProvider.class); PolicyRules fakeRules = new PolicyRules() {}; try { PolicyRulesEvaluator evaluator = new PolicyRulesEvaluator(fakeRules, mockAdaptor); evaluator.evaluate(mockProvider); } catch(Exception e) { fail("No excetion should be thrown by PolicyRulesEvaluator"); } } |
### Question:
DefaultMetricsReader implements MetricsReader { @Override public List<MetricName> readableNames() { return Arrays.asList(readableNames); } DefaultMetricsReader(); @Override List<MetricName> readableNames(); @Override MetricValue readValue(MetricName name); }### Answer:
@Test public void testGetReadableNames() { System.out.println("testGetReadableNames"); DefaultMetricsReader reader = new DefaultMetricsReader(); List<MetricName> names = reader.readableNames(); assertThat(names, containsInAnyOrder( MetricName.CPU_UTILIZATION, MetricName.HEAP_SIZE, MetricName.HEAP_UTILIZATION, MetricName.OPERATOR_LATENCY, MetricName.QUEUE_LENGTH)); } |
### Question:
DefaultMetricsReader implements MetricsReader { private MetricValue readCpuUtilization() { int availableProcessors = operatingSystemMXBean.getAvailableProcessors(); long stUpTime = runtimeMXBean.getUptime(); long stProcessCpuTime = operatingSystemMXBean.getProcessCpuTime(); try { Thread.sleep(100); } catch (Exception ex) { } long edUpTime = runtimeMXBean.getUptime(); long edProcessCpuTime = operatingSystemMXBean.getProcessCpuTime(); long elapsedCpu = edProcessCpuTime - stProcessCpuTime; long elapsedTime = edUpTime - stUpTime; double cpuUsage = Math.min(100F, elapsedCpu / (elapsedTime * 10000F * availableProcessors)); return MetricValue.percent(cpuUsage); } DefaultMetricsReader(); @Override List<MetricName> readableNames(); @Override MetricValue readValue(MetricName name); }### Answer:
@Test public void testReadCpuUtilization() { System.out.println("testReadCpuUtilization"); DefaultMetricsReader reader = new DefaultMetricsReader(); MetricValue value = reader.readValue(MetricName.CPU_UTILIZATION); assertThat(value, notNullValue()); assertThat(value.getUnit(), equalTo(MetricUnit.PERCENT)); assertThat(value.getValue(), greaterThanOrEqualTo(0.0)); assertThat(value.getValue(), lessThanOrEqualTo(100.0)); } |
### Question:
DefaultMetricsReader implements MetricsReader { private MetricValue readHeapSize() { Map<String, Metric> metrics = memoryMetricSet.getMetrics(); MetricValue value = null; if (metrics.containsKey(MEMORY_HEAP_SIZE_KEY)) { value = MetricValue.bytes( ((Long) ((Gauge) metrics.get(MEMORY_HEAP_SIZE_KEY)).getValue()).intValue()); } return value; } DefaultMetricsReader(); @Override List<MetricName> readableNames(); @Override MetricValue readValue(MetricName name); }### Answer:
@Test public void testReadHeapSize() { System.out.println("testReadHeapSize"); DefaultMetricsReader reader = new DefaultMetricsReader(); MetricValue value = reader.readValue(MetricName.HEAP_SIZE); assertThat(value, notNullValue()); assertThat(value.getUnit(), equalTo(MetricUnit.BYTES)); assertThat(value.getValue(), greaterThanOrEqualTo(0.0)); } |
### Question:
DefaultMetricsReader implements MetricsReader { private MetricValue readHeapUtilization() { Map<String, Metric> metrics = memoryMetricSet.getMetrics(); MetricValue value = null; if (metrics.containsKey(MEMORY_HEAP_UTIL_KEY)) { value = MetricValue.percent( (Double) ((Gauge) metrics.get(MEMORY_HEAP_UTIL_KEY)).getValue()); } return value; } DefaultMetricsReader(); @Override List<MetricName> readableNames(); @Override MetricValue readValue(MetricName name); }### Answer:
@Test public void testReadHeapUtilization() { System.out.println("testReadHeapUtilization"); DefaultMetricsReader reader = new DefaultMetricsReader(); MetricValue value = reader.readValue(MetricName.HEAP_UTILIZATION); assertThat(value, notNullValue()); assertThat(value.getUnit(), equalTo(MetricUnit.PERCENT)); assertThat(value.getValue(), greaterThanOrEqualTo(0.0)); assertThat(value.getValue(), lessThanOrEqualTo(100.0)); } |
### Question:
DefaultMetricsReader implements MetricsReader { private MetricValue readOperatorLatency() { MetricValue value = null; Timer operatorLatency = metricRegistry .timer(MetricName.OPERATOR_LATENCY.getName()); if (operatorLatency != null) { value = MetricValue.millis(Double.valueOf( operatorLatency.getSnapshot().getMean() / 1000000).intValue()); } return value; } DefaultMetricsReader(); @Override List<MetricName> readableNames(); @Override MetricValue readValue(MetricName name); }### Answer:
@Test public void testReadOperatorLatency() { System.out.println("testReadOperatorLatency"); DefaultMetricsReader reader = new DefaultMetricsReader(); MetricValue value = reader.readValue(MetricName.OPERATOR_LATENCY); assertThat(value, notNullValue()); assertThat(value.getUnit(), equalTo(MetricUnit.MILLISECONDS)); assertThat(value.getValue(), greaterThanOrEqualTo(0.0)); } |
### Question:
DefaultMetricsReader implements MetricsReader { private MetricValue readQueueLength() { MetricValue value = null; Counter queueLength = metricRegistry .counter(MetricName.QUEUE_LENGTH.getName()); if (queueLength != null) { value = MetricValue.tuples(Long.valueOf( queueLength.getCount()).intValue()); } return value; } DefaultMetricsReader(); @Override List<MetricName> readableNames(); @Override MetricValue readValue(MetricName name); }### Answer:
@Test public void testReadQueueLength() { System.out.println("testReadQueueLength"); DefaultMetricsReader reader = new DefaultMetricsReader(); MetricValue value = reader.readValue(MetricName.QUEUE_LENGTH); assertThat(value, notNullValue()); assertThat(value.getUnit(), equalTo(MetricUnit.TUPLES)); assertThat(value.getValue(), greaterThanOrEqualTo(0.0)); } |
### Question:
AbsoluteScaleFactor extends ScaleFactor { @Override public int apply(int currentSize, Action action) { int newSize = currentSize + (new Double(getFactor())).intValue(); if(action instanceof ScaleInAction) { newSize = currentSize - (new Double(getFactor())).intValue(); if(newSize < 1) { newSize = 1; } } return newSize; } AbsoluteScaleFactor(int factor); @Override int apply(int currentSize, Action action); }### Answer:
@Test public void testAbsoluteFactorApplyWithScaleOut() { System.out.println("testAbsoluteFactorApply"); AbsoluteScaleFactor factor; factor = new AbsoluteScaleFactor(10); assertEquals("New scaling size is incorrect", 11, factor.apply(1, new ScaleOutAction())); assertEquals("New scaling size is incorrect", 20, factor.apply(10, new ScaleOutAction())); assertEquals("New scaling size is incorrect", 15, factor.apply(5, new ScaleOutAction())); } |
### Question:
Cryptography { public static String md5(String message) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] messageDigest = md.digest(message.getBytes()); BigInteger number = new BigInteger(1, messageDigest); String hashtext = number.toString(16); return hashtext; } catch (NoSuchAlgorithmException e) { return ""; } } static String md5(String message); }### Answer:
@Test public void md5() { String result = Cryptography.md5("test"); Assert.assertEquals(result, "98f6bcd4621d373cade4e832627b4f6"); } |
### Question:
CourseDAOMemory implements CourseDAO { @Override public List<Course> findAll() { return new ArrayList<>(courseList); } CourseDAOMemory(); @Override Course find(int courseId); @Override void save(Course course); @Override void delete(int courseId); @Override List<Course> findAll(); @Override int nextId(); }### Answer:
@Test public void findAll() { } |
### Question:
CourseDAOMemory implements CourseDAO { @Override public int nextId() { autoIncrementId++; return autoIncrementId; } CourseDAOMemory(); @Override Course find(int courseId); @Override void save(Course course); @Override void delete(int courseId); @Override List<Course> findAll(); @Override int nextId(); }### Answer:
@Test public void nextId() { } |
### Question:
Time { public static Time createTime(int year, int month, int date, int hour, int minutes, int seconds) { if (year < 0 || month > 12 || month < 0 || date < 0 || date > 31 || hour < 0 || hour > 24 || minutes < 0 || minutes > 60 || seconds < 0 || seconds > 60) { throw new IllegalArgumentException(""); } return new Time(year, month, date, hour, minutes, seconds); } Time(); private Time(int year, int month, int date, int hour, int minutes, int seconds); static Time createTime(int year, int month, int date, int hour, int minutes, int seconds); static Time getTimeByCalendar(Calendar calendar); boolean isBefore(Time when); String getReadableTime(); String getDateReadable(); String getTimeReadable(); int getDate(); void setDate(int date); int getMonth(); void setMonth(int month); int getYear(); void setYear(int year); int getMinutes(); void setMinutes(int minutes); int getHour(); void setHour(int hour); int getSecond(); void setSecond(int second); }### Answer:
@Test(expected = IllegalArgumentException.class) public void isBefore_illegal_input() { Time time1 = Time.createTime(2020, 11, 44, 21, -1, 00); } |
### Question:
Time { public void setSecond(int second) { if (second < 0 || second > 60) throw new IllegalArgumentException(); this.second = second; } Time(); private Time(int year, int month, int date, int hour, int minutes, int seconds); static Time createTime(int year, int month, int date, int hour, int minutes, int seconds); static Time getTimeByCalendar(Calendar calendar); boolean isBefore(Time when); String getReadableTime(); String getDateReadable(); String getTimeReadable(); int getDate(); void setDate(int date); int getMonth(); void setMonth(int month); int getYear(); void setYear(int year); int getMinutes(); void setMinutes(int minutes); int getHour(); void setHour(int hour); int getSecond(); void setSecond(int second); }### Answer:
@Test(expected = IllegalArgumentException.class) public void setSecond() { time.setSecond(22); time.setSecond(65); } |
### Question:
Time { public void setHour(int hour) { if (hour < 0 || hour > 24) throw new IllegalArgumentException(); this.hour = hour; } Time(); private Time(int year, int month, int date, int hour, int minutes, int seconds); static Time createTime(int year, int month, int date, int hour, int minutes, int seconds); static Time getTimeByCalendar(Calendar calendar); boolean isBefore(Time when); String getReadableTime(); String getDateReadable(); String getTimeReadable(); int getDate(); void setDate(int date); int getMonth(); void setMonth(int month); int getYear(); void setYear(int year); int getMinutes(); void setMinutes(int minutes); int getHour(); void setHour(int hour); int getSecond(); void setSecond(int second); }### Answer:
@Test(expected = IllegalArgumentException.class) public void setHour() { time.setHour(12); time.setHour(65); } |
### Question:
Time { public void setMinutes(int minutes) { if (minutes < 0 || minutes > 60) throw new IllegalArgumentException(); this.minutes = minutes; } Time(); private Time(int year, int month, int date, int hour, int minutes, int seconds); static Time createTime(int year, int month, int date, int hour, int minutes, int seconds); static Time getTimeByCalendar(Calendar calendar); boolean isBefore(Time when); String getReadableTime(); String getDateReadable(); String getTimeReadable(); int getDate(); void setDate(int date); int getMonth(); void setMonth(int month); int getYear(); void setYear(int year); int getMinutes(); void setMinutes(int minutes); int getHour(); void setHour(int hour); int getSecond(); void setSecond(int second); }### Answer:
@Test(expected = IllegalArgumentException.class) public void setMinutes() { time.setMinutes(22); time.setMinutes(65); } |
### Question:
Time { public void setYear(int year) { if (year < 0) throw new IllegalArgumentException(); this.year = year; } Time(); private Time(int year, int month, int date, int hour, int minutes, int seconds); static Time createTime(int year, int month, int date, int hour, int minutes, int seconds); static Time getTimeByCalendar(Calendar calendar); boolean isBefore(Time when); String getReadableTime(); String getDateReadable(); String getTimeReadable(); int getDate(); void setDate(int date); int getMonth(); void setMonth(int month); int getYear(); void setYear(int year); int getMinutes(); void setMinutes(int minutes); int getHour(); void setHour(int hour); int getSecond(); void setSecond(int second); }### Answer:
@Test(expected = IllegalArgumentException.class) public void setYear() { time.setYear(1999); time.setSecond(-1); } |
### Question:
Time { public void setMonth(int month) { if (month < 0 || month > 12) throw new IllegalArgumentException(); this.month = month; } Time(); private Time(int year, int month, int date, int hour, int minutes, int seconds); static Time createTime(int year, int month, int date, int hour, int minutes, int seconds); static Time getTimeByCalendar(Calendar calendar); boolean isBefore(Time when); String getReadableTime(); String getDateReadable(); String getTimeReadable(); int getDate(); void setDate(int date); int getMonth(); void setMonth(int month); int getYear(); void setYear(int year); int getMinutes(); void setMinutes(int minutes); int getHour(); void setHour(int hour); int getSecond(); void setSecond(int second); }### Answer:
@Test(expected = IllegalArgumentException.class) public void setMonth() { time.setMonth(11); time.setMonth(33); } |
### Question:
Time { public void setDate(int date) { if (date <= 0 || date > 31) { throw new IllegalArgumentException(); } this.date = date; } Time(); private Time(int year, int month, int date, int hour, int minutes, int seconds); static Time createTime(int year, int month, int date, int hour, int minutes, int seconds); static Time getTimeByCalendar(Calendar calendar); boolean isBefore(Time when); String getReadableTime(); String getDateReadable(); String getTimeReadable(); int getDate(); void setDate(int date); int getMonth(); void setMonth(int month); int getYear(); void setYear(int year); int getMinutes(); void setMinutes(int minutes); int getHour(); void setHour(int hour); int getSecond(); void setSecond(int second); }### Answer:
@Test(expected = IllegalArgumentException.class) public void setDate() { time.setSecond(22); time.setSecond(65); } |
### Question:
Time { public static Time getTimeByCalendar(Calendar calendar) { int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); return Time.createTime(year, month, day, hour, minute, second); } Time(); private Time(int year, int month, int date, int hour, int minutes, int seconds); static Time createTime(int year, int month, int date, int hour, int minutes, int seconds); static Time getTimeByCalendar(Calendar calendar); boolean isBefore(Time when); String getReadableTime(); String getDateReadable(); String getTimeReadable(); int getDate(); void setDate(int date); int getMonth(); void setMonth(int month); int getYear(); void setYear(int year); int getMinutes(); void setMinutes(int minutes); int getHour(); void setHour(int hour); int getSecond(); void setSecond(int second); }### Answer:
@Test public void create_time_from_calendar(){ Time timeByCalendar = Time.getTimeByCalendar(Calendar.getInstance()); System.out.println("t"); } |
### Question:
RegexUtil { public static boolean isEmail(String mail) { return mail.matches(mailRegex); } static boolean isEmail(String mail); static final String mailRegex; }### Answer:
@Test public void check_for_valid_email() { String email = "zafeiris@aueb.gr"; Assert.assertTrue(RegexUtil.isEmail(email)); }
@Test public void check_for_invalid_email() { String email = "dsafewreg@"; Assert.assertFalse(RegexUtil.isEmail(email)); } |
### Question:
CourseAddEditPresenter { public void setUpMode() { Integer selectedCourseId = view.getSelectedCourseId(); if (selectedCourseId == -1) { view.setUpAddMode(); } else { Course course = courseDAO.find(selectedCourseId); view.setUpEditMode(course); } } CourseAddEditPresenter(CourseAddEditView view, CourseDAO courseDAO); void setUpMode(); void onClickSaveCourse(); void onClickDeleteCourse(); }### Answer:
@Test public void shouldCallSetUpAddMode() { when(courseAddEditView.getSelectedCourseId()).thenReturn(-1); presenterUnderTest.setUpMode(); verify(courseAddEditView).setUpAddMode(); }
@Test public void shouldCallSetUpEditMode() { Course course = new Course("test", "test", 1, 1); course.setId(1); when(courseDAO.find(1)).thenReturn(course); when(courseAddEditView.getSelectedCourseId()).thenReturn(1); presenterUnderTest.setUpMode(); verify(courseAddEditView).setUpEditMode(course); } |
### Question:
CourseAddEditPresenter { public void onClickSaveCourse() { if (view.getCourseName().isEmpty() || view.getCourseDescription().isEmpty() || view.getCourseSemester() == -1 || view.getCourseECTS() == -1) { view.showEmptyFieldsDetected(); return; } Course course = new Course(view.getCourseName(), view.getCourseDescription(), view.getCourseECTS(), view.getCourseSemester()); if (view.getSelectedCourseId() == -1) { courseDAO.save(course); view.onSuccessfulAddCourse(); } else { course.setId(view.getSelectedCourseId()); courseDAO.save(course); view.onSuccessfulEditCourse(); } } CourseAddEditPresenter(CourseAddEditView view, CourseDAO courseDAO); void setUpMode(); void onClickSaveCourse(); void onClickDeleteCourse(); }### Answer:
@Test public void onClickSaveCourse() { } |
### Question:
CourseAddEditPresenter { public void onClickDeleteCourse() { courseDAO.delete(view.getSelectedCourseId()); view.onSuccessfulDeleteCourse(); } CourseAddEditPresenter(CourseAddEditView view, CourseDAO courseDAO); void setUpMode(); void onClickSaveCourse(); void onClickDeleteCourse(); }### Answer:
@Test public void onClickDeleteCourse() { } |
### Question:
CourseDAOMemory implements CourseDAO { @Override public Course find(int courseId) { for (Course c : courseList) { if (c.getId() == courseId) return c; } return null; } CourseDAOMemory(); @Override Course find(int courseId); @Override void save(Course course); @Override void delete(int courseId); @Override List<Course> findAll(); @Override int nextId(); }### Answer:
@Test public void find() { } |
### Question:
CourseDAOMemory implements CourseDAO { @Override public void save(Course course) { delete(course.getId()); course.setId(nextId()); courseList.add(course); } CourseDAOMemory(); @Override Course find(int courseId); @Override void save(Course course); @Override void delete(int courseId); @Override List<Course> findAll(); @Override int nextId(); }### Answer:
@Test public void save() { Course course = new Course("TEST", "TEST", 1, 1); daoMemory.save(course); List<Course> all = daoMemory.findAll(); assertTrue(all.contains(course)); } |
### Question:
CourseDAOMemory implements CourseDAO { @Override public void delete(int courseId) { for (Course c : courseList) { if (c.getId() == courseId) { courseList.remove(c); break; } } } CourseDAOMemory(); @Override Course find(int courseId); @Override void save(Course course); @Override void delete(int courseId); @Override List<Course> findAll(); @Override int nextId(); }### Answer:
@Test public void delete() { Course course = new Course("TEST", "TEST", 1, 1); daoMemory.save(course); daoMemory.delete(course.getId()); assertTrue(daoMemory.findAll().isEmpty()); } |
### Question:
Benchmark { public static <T extends QueryMatch> BenchmarkResults<T> run(Monitor monitor, Iterable<InputDocument> documents, int batchsize, MatcherFactory<T> matcherFactory) throws IOException { BenchmarkResults<T> results = new BenchmarkResults<>(); for (DocumentBatch batch : batchDocuments(documents, batchsize)) { Matches<T> matches = monitor.match(batch, matcherFactory); results.add(matches); } return results; } private Benchmark(); static BenchmarkResults<T> run(Monitor monitor, Iterable<InputDocument> documents,
int batchsize, MatcherFactory<T> matcherFactory); static Iterable<DocumentBatch> batchDocuments(Iterable<InputDocument> documents, int batchsize); static BenchmarkResults<PresearcherMatch> timePresearcher(Monitor monitor, int batchsize, Iterable<InputDocument> documents); static ValidatorResults<T> validate(Monitor monitor, Iterable<ValidatorDocument<T>> documents,
MatcherFactory<T> matcherFactory); }### Answer:
@Test public void testBasicBenchmarking() throws IOException { List<InputDocument> docs = ImmutableList.of( InputDocument.builder("doc1").addField("f", "some text about the world", STANDARD).build(), InputDocument.builder("doc2").addField("f", "some text about cheese", STANDARD).build() ); BenchmarkResults<QueryMatch> results = Benchmark.run(monitor, docs, 1, SimpleMatcher.FACTORY); assertThat(results.getTimer().getCount()).isEqualTo(2); } |
### Question:
InputDocument { public static Builder builder(String id) { return new Builder(id); } protected InputDocument(String id, Document luceneDocument, PerFieldAnalyzerWrapper analyzers); static Builder builder(String id); String getId(); Document getDocument(); PerFieldAnalyzerWrapper getAnalyzers(); static void checkFieldName(String fieldName); static final String ID_FIELD; }### Answer:
@Test public void testCannotAddReservedFieldName() { expected.expect(IllegalArgumentException.class); expected.expectMessage("reserved"); InputDocument.builder("id").addField(InputDocument.ID_FIELD, "test", new StandardAnalyzer()).build(); }
@Test public void testCannotAddReservedFieldObject() { expected.expect(IllegalArgumentException.class); expected.expectMessage("reserved"); InputDocument.builder("id").addField(new StringField(InputDocument.ID_FIELD, "", Field.Store.YES)).build(); }
@Test public void testOmitNorms() throws Exception { FieldType type = new FieldType(); type.setOmitNorms(true); type.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); Field f = new Field("text", "this is some text that will have a length norm greater than 0", type); InputDocument doc = InputDocument.builder("id") .setDefaultAnalyzer(new StandardAnalyzer()) .addField(f).build(); try (Monitor monitor = new Monitor(new LuceneQueryParser("text"), new MatchAllPresearcher())) { monitor.update(new MonitorQuery("q", "length")); Matches<ExplainingMatch> matches = monitor.match(doc, ExplainingMatcher.FACTORY); DocumentMatches<ExplainingMatch> m = matches.getMatches("id"); for (ExplainingMatch e : m) { Explanation expl = e.getExplanation(); assertThat(expl.toString()).contains("norms omitted"); } } } |
### Question:
ExplainingMatcher extends CandidateMatcher<ExplainingMatch> { public ExplainingMatcher(DocumentBatch docs) { super(docs); } ExplainingMatcher(DocumentBatch docs); @Override void doMatchQuery(String queryId, Query matchQuery, Map<String, String> metadata); @Override ExplainingMatch resolve(ExplainingMatch match1, ExplainingMatch match2); static final MatcherFactory<ExplainingMatch> FACTORY; }### Answer:
@Test public void testExplainingMatcher() throws IOException, UpdateException { try (Monitor monitor = new Monitor(new LuceneQueryParser("field"), new MatchAllPresearcher())) { monitor.update(new MonitorQuery("1", "test"), new MonitorQuery("2", "wibble")); InputDocument doc1 = InputDocument.builder("doc1").addField("field", "test", new StandardAnalyzer()).build(); Matches<ExplainingMatch> matches = monitor.match(doc1, ExplainingMatcher.FACTORY); assertThat(matches.matches("1", "doc1")).isNotNull(); assertThat(matches.matches("1", "doc1").getExplanation()).isNotNull(); } } |
### Question:
SimpleMatcher extends CollectingMatcher<QueryMatch> { public SimpleMatcher(DocumentBatch docs) { super(docs); } SimpleMatcher(DocumentBatch docs); @Override QueryMatch resolve(QueryMatch match1, QueryMatch match2); static final MatcherFactory<QueryMatch> FACTORY; }### Answer:
@Test public void testSimpleMatcher() throws IOException, UpdateException { try (Monitor monitor = new Monitor(new LuceneQueryParser("field"), new MatchAllPresearcher())) { monitor.update(new MonitorQuery("1", "test"), new MonitorQuery("2", "wibble")); InputDocument doc1 = InputDocument.builder("doc1").addField("field", "test", new StandardAnalyzer()).build(); Matches<QueryMatch> matches = monitor.match(doc1, SimpleMatcher.FACTORY); assertThat(matches.matches("1", "doc1")).isNotNull(); } } |
### Question:
ConcurrentQueryLoader implements Closeable { public void add(MonitorQuery mq) throws InterruptedException { if (shutdown) throw new IllegalStateException("ConcurrentQueryLoader has been shutdown, cannot add new queries"); this.queue.put(mq); } ConcurrentQueryLoader(Monitor monitor, List<QueryError> errors); ConcurrentQueryLoader(Monitor monitor, List<QueryError> errors, int threads, int queueSize); void add(MonitorQuery mq); @Override void close(); static final int DEFAULT_QUEUE_SIZE; }### Answer:
@Test public void testLoading() throws Exception { try (Monitor monitor = new Monitor(new LuceneQueryParser("f"), new MatchAllPresearcher())) { List<QueryError> errors = new ArrayList<>(); try (ConcurrentQueryLoader loader = new ConcurrentQueryLoader(monitor, errors)) { for (int i = 0; i < 2000; i++) { loader.add(new MonitorQuery(Integer.toString(i), "\"test " + i + "\"")); } assertThat(errors).isEmpty(); } assertThat(monitor.getQueryCount()).isEqualTo(2000); } }
@Test public void testErrorHandling() throws Exception { try (Monitor monitor = new Monitor(new LuceneQueryParser("f"), new MatchAllPresearcher())) { List<QueryError> errors = new ArrayList<>(); try (ConcurrentQueryLoader loader = new ConcurrentQueryLoader(monitor, errors)) { for (int i = 0; i < 2000; i++) { String query = "test" + i; if (i % 200 == 0) query += " ["; loader.add(new MonitorQuery(Integer.toString(i), query)); } } assertThat(errors).hasSize(10); assertThat(monitor.getQueryCount()).isEqualTo(1990); } } |
### Question:
Benchmark { public static BenchmarkResults<PresearcherMatch> timePresearcher(Monitor monitor, int batchsize, Iterable<InputDocument> documents) throws IOException { return run(monitor, documents, batchsize, PresearcherMatcher.FACTORY); } private Benchmark(); static BenchmarkResults<T> run(Monitor monitor, Iterable<InputDocument> documents,
int batchsize, MatcherFactory<T> matcherFactory); static Iterable<DocumentBatch> batchDocuments(Iterable<InputDocument> documents, int batchsize); static BenchmarkResults<PresearcherMatch> timePresearcher(Monitor monitor, int batchsize, Iterable<InputDocument> documents); static ValidatorResults<T> validate(Monitor monitor, Iterable<ValidatorDocument<T>> documents,
MatcherFactory<T> matcherFactory); }### Answer:
@Test public void testPresearcherBenchmarking() throws IOException { List<InputDocument> docs = ImmutableList.of( InputDocument.builder("doc1").addField("f", "some text about the world", STANDARD).build(), InputDocument.builder("doc2").addField("f", "some text about cheese", STANDARD).build() ); BenchmarkResults<PresearcherMatch> results = Benchmark.timePresearcher(monitor, 2, docs); assertThat(results.getTimer().getCount()).isEqualTo(1); assertThat(results.getTimer().getMeanRate()).isGreaterThan(0); } |
### Question:
QueryTermFilter { public BytesRefHash getTerms(String field) { BytesRefHash existing = termsHash.get(field); if (existing != null) return existing; return new BytesRefHash(); } QueryTermFilter(IndexReader reader); BytesRefHash getTerms(String field); }### Answer:
@Test public void testFiltersAreRemoved() throws IOException { QueryIndex qi = new QueryIndex(); qi.commit(indexable("1", "term")); assertThat(qi.termFilters).hasSize(1); qi.commit(indexable("2", "term2")); assertThat(qi.termFilters).hasSize(1); QueryTermFilter tf = Iterables.getFirst(qi.termFilters.values(), null); assertThat(tf).isNotNull(); assertThat(tf.getTerms(FIELD).size()).isEqualTo(2); } |
### Question:
SlowLog implements Iterable<SlowLog.Entry> { @Override public String toString() { StringBuilder sb = new StringBuilder("Limit: ").append(limit).append("\n"); for (Entry entry : slowQueries) { sb.append("\t").append(entry.queryId).append(" [").append(entry.time).append("ns]\n"); } return sb.toString(); } void setLimit(long limit); long getLimit(); void addQuery(String query, long time); void addAll(Iterable<SlowLog.Entry> queries); @Override Iterator<Entry> iterator(); @Override String toString(); }### Answer:
@Test public void testSlowLog() throws IOException, UpdateException { try (Monitor monitor = new Monitor(new SlowQueryParser(250), new MatchAllPresearcher())) { monitor.update(new MonitorQuery("1", "slow"), new MonitorQuery("2", "fast"), new MonitorQuery("3", "slow")); InputDocument doc1 = InputDocument.builder("doc1").build(); Matches<QueryMatch> matches = monitor.match(doc1, SimpleMatcher.FACTORY); System.out.println(matches.getSlowLog()); assertThat(matches.getSlowLog().toString()) .contains("1 [") .contains("3 [") .doesNotContain("2 ["); monitor.setSlowLogLimit(1); assertThat(monitor.match(doc1, SimpleMatcher.FACTORY).getSlowLog().toString()) .contains("1 [") .contains("2 [") .contains("3 ["); monitor.setSlowLogLimit(2000000000000L); assertThat(monitor.match(doc1, SimpleMatcher.FACTORY).getSlowLog()) .isEmpty(); } } |
### Question:
ForceNoBulkScoringQuery extends Query { @Override public int hashCode() { return Objects.hash(inner); } ForceNoBulkScoringQuery(Query inner); @Override Query rewrite(IndexReader reader); @Override boolean equals(Object o); @Override int hashCode(); Query getWrappedQuery(); @Override Weight createWeight(IndexSearcher searcher, boolean needsScores, float boost); @Override String toString(String s); }### Answer:
@Test public void testEquality() { TermQuery tq1 = new TermQuery(new Term("f", "t")); TermQuery tq2 = new TermQuery(new Term("f", "t2")); TermQuery tq3 = new TermQuery(new Term("f", "t2")); assertThat(new ForceNoBulkScoringQuery(tq1)) .isEqualTo(new ForceNoBulkScoringQuery(tq1)); assertThat(new ForceNoBulkScoringQuery(tq1)) .isNotEqualTo(new ForceNoBulkScoringQuery(tq2)); assertThat(new ForceNoBulkScoringQuery(tq2)) .isEqualTo(new ForceNoBulkScoringQuery(tq3)); assertThat(new ForceNoBulkScoringQuery(tq2).hashCode()) .isEqualTo(new ForceNoBulkScoringQuery(tq3).hashCode()); assertThat(new ForceNoBulkScoringQuery(tq1).hashCode()) .isNotEqualTo(new ForceNoBulkScoringQuery(tq2).hashCode()); } |
### Question:
ForceNoBulkScoringQuery extends Query { @Override public Query rewrite(IndexReader reader) throws IOException { Query rewritten = inner.rewrite(reader); if (rewritten != inner) return new ForceNoBulkScoringQuery(rewritten); return super.rewrite(reader); } ForceNoBulkScoringQuery(Query inner); @Override Query rewrite(IndexReader reader); @Override boolean equals(Object o); @Override int hashCode(); Query getWrappedQuery(); @Override Weight createWeight(IndexSearcher searcher, boolean needsScores, float boost); @Override String toString(String s); }### Answer:
@Test public void testRewrite() throws IOException { try (Directory dir = new RAMDirectory(); IndexWriter iw = new IndexWriter(dir, new IndexWriterConfig(new StandardAnalyzer()))) { Document doc = new Document(); doc.add(new TextField("field", "term1 term2 term3 term4", Field.Store.NO)); iw.addDocument(doc); iw.commit(); IndexReader reader = DirectoryReader.open(dir); PrefixQuery pq = new PrefixQuery(new Term("field", "term")); ForceNoBulkScoringQuery q = new ForceNoBulkScoringQuery(pq); assertThat(q.getWrappedQuery()).isEqualTo(pq); Query rewritten = q.rewrite(reader); assertThat(rewritten).isInstanceOf(ForceNoBulkScoringQuery.class); Query inner = ((ForceNoBulkScoringQuery) rewritten).getWrappedQuery(); assertThat(inner).isNotEqualTo(pq); } } |
### Question:
UserServiceImpl implements UserService { public User getUserInfoById(Long userId) { return userDao.queryUserById(userId); } User getUserInfoById(Long userId); Long getUserCounts(); List<User> getUserList(); List<User> getUserListByTime(Long startTime, Long endTime); int updateUserEmail(String email, String password); int updateUserPwd(String email, String old_password,String new_password); int updateUserImg(String email, String imgUrl); int updateUserInfo(User user); User user_login(String email, String passsword); int user_regist(String email, String password, String user_name); User check_email(String email); int insertToUserRecord_click(long uid, long aid); User adminUserLogin(Long userId, String password); int setController(int module_id, long user_id); }### Answer:
@Test public void getUserInfoById() throws Exception { Long userid = 10003l; User user_info = userDao.queryUserById(userid); System.out.println(user_info); } |
### Question:
UserServiceImpl implements UserService { public Long getUserCounts() { return userDao.getUserCounts(); } User getUserInfoById(Long userId); Long getUserCounts(); List<User> getUserList(); List<User> getUserListByTime(Long startTime, Long endTime); int updateUserEmail(String email, String password); int updateUserPwd(String email, String old_password,String new_password); int updateUserImg(String email, String imgUrl); int updateUserInfo(User user); User user_login(String email, String passsword); int user_regist(String email, String password, String user_name); User check_email(String email); int insertToUserRecord_click(long uid, long aid); User adminUserLogin(Long userId, String password); int setController(int module_id, long user_id); }### Answer:
@Test public void getUserCounts() throws Exception { System.out.println(userDao.getUserCounts()); } |
### Question:
UserServiceImpl implements UserService { public List<User> getUserList() { return userDao.getUserList(); } User getUserInfoById(Long userId); Long getUserCounts(); List<User> getUserList(); List<User> getUserListByTime(Long startTime, Long endTime); int updateUserEmail(String email, String password); int updateUserPwd(String email, String old_password,String new_password); int updateUserImg(String email, String imgUrl); int updateUserInfo(User user); User user_login(String email, String passsword); int user_regist(String email, String password, String user_name); User check_email(String email); int insertToUserRecord_click(long uid, long aid); User adminUserLogin(Long userId, String password); int setController(int module_id, long user_id); }### Answer:
@Test public void getUserList() throws Exception { System.out.println(userDao.getUserList()); } |
### Question:
UserServiceImpl implements UserService { public List<User> getUserListByTime(Long startTime, Long endTime) { return null; } User getUserInfoById(Long userId); Long getUserCounts(); List<User> getUserList(); List<User> getUserListByTime(Long startTime, Long endTime); int updateUserEmail(String email, String password); int updateUserPwd(String email, String old_password,String new_password); int updateUserImg(String email, String imgUrl); int updateUserInfo(User user); User user_login(String email, String passsword); int user_regist(String email, String password, String user_name); User check_email(String email); int insertToUserRecord_click(long uid, long aid); User adminUserLogin(Long userId, String password); int setController(int module_id, long user_id); }### Answer:
@Test public void getUserListByTime() throws Exception { } |
### Question:
UserServiceImpl implements UserService { public int updateUserEmail(String email, String password) { return 0; } User getUserInfoById(Long userId); Long getUserCounts(); List<User> getUserList(); List<User> getUserListByTime(Long startTime, Long endTime); int updateUserEmail(String email, String password); int updateUserPwd(String email, String old_password,String new_password); int updateUserImg(String email, String imgUrl); int updateUserInfo(User user); User user_login(String email, String passsword); int user_regist(String email, String password, String user_name); User check_email(String email); int insertToUserRecord_click(long uid, long aid); User adminUserLogin(Long userId, String password); int setController(int module_id, long user_id); }### Answer:
@Test public void updateUserEmail() throws Exception { } |
### Question:
UserServiceImpl implements UserService { public int updateUserPwd(String email, String old_password,String new_password) { return userDao.updateUserPwd(old_password, new_password, email); } User getUserInfoById(Long userId); Long getUserCounts(); List<User> getUserList(); List<User> getUserListByTime(Long startTime, Long endTime); int updateUserEmail(String email, String password); int updateUserPwd(String email, String old_password,String new_password); int updateUserImg(String email, String imgUrl); int updateUserInfo(User user); User user_login(String email, String passsword); int user_regist(String email, String password, String user_name); User check_email(String email); int insertToUserRecord_click(long uid, long aid); User adminUserLogin(Long userId, String password); int setController(int module_id, long user_id); }### Answer:
@Test public void updateUserPwd() throws Exception { System.out.println(userDao.updateUserPwd("123456","1234567","gangshi@han.cn")); } |
### Question:
UserServiceImpl implements UserService { public int updateUserImg(String email, String imgUrl) { return userDao.updateUserImg(imgUrl, email); } User getUserInfoById(Long userId); Long getUserCounts(); List<User> getUserList(); List<User> getUserListByTime(Long startTime, Long endTime); int updateUserEmail(String email, String password); int updateUserPwd(String email, String old_password,String new_password); int updateUserImg(String email, String imgUrl); int updateUserInfo(User user); User user_login(String email, String passsword); int user_regist(String email, String password, String user_name); User check_email(String email); int insertToUserRecord_click(long uid, long aid); User adminUserLogin(Long userId, String password); int setController(int module_id, long user_id); }### Answer:
@Test public void updateUserImg() throws Exception { System.out.println(userDao.updateUserImg("https: } |
### Question:
UserServiceImpl implements UserService { public int updateUserInfo(User user) { return userDao.updateUserInfo(user.getUser_id(), user.getUser_name(), user.getUser_email(), user.getUser_age(), user.getUser_gender(), user.getUser_homeTown_province(), user.getUser_homeTown_city(), user.getUser_homeTown_district(), user.getUser_homeTown_town(), user.getUser_homeTown_detail(), user.getUser_phoneNumber() ); } User getUserInfoById(Long userId); Long getUserCounts(); List<User> getUserList(); List<User> getUserListByTime(Long startTime, Long endTime); int updateUserEmail(String email, String password); int updateUserPwd(String email, String old_password,String new_password); int updateUserImg(String email, String imgUrl); int updateUserInfo(User user); User user_login(String email, String passsword); int user_regist(String email, String password, String user_name); User check_email(String email); int insertToUserRecord_click(long uid, long aid); User adminUserLogin(Long userId, String password); int setController(int module_id, long user_id); }### Answer:
@Test public void updateUserInfo() throws Exception { } |
### Question:
SolidityNode { private void getBlock() { long blockNum = ID.incrementAndGet(); while (flag) { try { if (blockNum > remoteBlockNum.get()) { sleep(BLOCK_PRODUCED_INTERVAL); remoteBlockNum.set(getLastSolidityBlockNum()); continue; } Block block = getBlockByNum(blockNum); blockQueue.put(block); blockNum = ID.incrementAndGet(); } catch (Exception e) { logger.error("Failed to get block {}, reason: {}.", blockNum, e.getMessage()); sleep(exceptionSleepTime); } } } SolidityNode(Manager dbManager); static void main(String[] args); void sleep(long time); }### Answer:
@Test public void testSolidityGrpcCall() { DatabaseGrpcClient databaseGrpcClient = null; String addr = Args.getInstance().getTrustNodeAddr(); try { databaseGrpcClient = new DatabaseGrpcClient(addr); } catch (Exception e) { logger.error("Failed to create database grpc client {}", addr); } Assert.assertNotNull(databaseGrpcClient); DynamicProperties dynamicProperties = databaseGrpcClient.getDynamicProperties(); Assert.assertNotNull(dynamicProperties); Block genesisBlock = databaseGrpcClient.getBlock(0); Assert.assertNotNull(genesisBlock); Assert.assertFalse(genesisBlock.getTransactionsList().isEmpty()); }
@Test public void testSolidityGrpcCall() { DatabaseGrpcClient databaseGrpcClient = null; String addr = Args.getInstance().getTrustNodeAddr(); try { databaseGrpcClient = new DatabaseGrpcClient(addr); } catch (Exception e) { logger.error("Failed to create database grpc client {}", addr); } Assert.assertNotNull(databaseGrpcClient); DynamicProperties dynamicProperties = databaseGrpcClient.getDynamicProperties(); Assert.assertNotNull(dynamicProperties); Block genisisBlock = databaseGrpcClient.getBlock(0); Assert.assertNotNull(genisisBlock); Assert.assertFalse(genisisBlock.getTransactionsList().isEmpty()); } |
### Question:
NodeManager implements EventHandler { public List<NodeHandler> dumpActiveNodes() { List<NodeHandler> handlers = new ArrayList<>(); for (NodeHandler handler : this.nodeHandlerMap.values()) { if (isNodeAlive(handler)) { handlers.add(handler); } } return handlers; } @Autowired NodeManager(ChainBaseManager chainBaseManager); ScheduledExecutorService getPongTimer(); @Override void channelActivated(); boolean isNodeAlive(NodeHandler nodeHandler); void setMessageSender(Consumer<UdpEvent> messageSender); NodeHandler getNodeHandler(Node n); boolean hasNodeHandler(Node n); NodeTable getTable(); NodeStatistics getNodeStatistics(Node n); @Override void handleEvent(UdpEvent udpEvent); void sendOutbound(UdpEvent udpEvent); List<NodeHandler> getNodes(Predicate<NodeHandler> predicate, int limit); List<NodeHandler> dumpActiveNodes(); Node getPublicHomeNode(); void close(); }### Answer:
@Test public void dumpActiveNodesTest() { Node node1 = new Node(new byte[64], "128.0.0.1", 18888, 18888); Node node2 = new Node(new byte[64], "128.0.0.2", 18888, 18888); Node node3 = new Node(new byte[64], "128.0.0.3", 18888, 18888); NodeHandler nodeHandler1 = nodeManager.getNodeHandler(node1); NodeHandler nodeHandler2 = nodeManager.getNodeHandler(node2); NodeHandler nodeHandler3 = nodeManager.getNodeHandler(node3); nodeHandler1.changeState(NodeHandler.State.ALIVE); nodeHandler2.changeState(NodeHandler.State.ACTIVE); nodeHandler3.changeState(NodeHandler.State.NONACTIVE); int activeNodes = nodeManager.dumpActiveNodes().size(); Assert.assertEquals(2, activeNodes); } |
### Question:
MetricsUtil { public static void counterInc(String key) { try { if (CommonParameter.getInstance().isNodeMetricsEnable()) { metricRegistry.counter(key).inc(1L); } } catch (Exception e) { logger.warn("inc counter failed, key:{}", key); } } static void init(); static Histogram getHistogram(String key); static SortedMap<String, Histogram> getHistograms(String key); static void histogramUpdate(String key, long value); static Meter getMeter(String name); static SortedMap<String, Meter> getMeters(String key); static void meterMark(String key); static void meterMark(String key, long value); static Counter getCounter(String name); static SortedMap<String, Counter> getCounters(String name); static void counterInc(String key); static RateInfo getRateInfo(String key); }### Answer:
@Test public void testCounterInc() { MetricsUtil.counterInc(test1); } |
### Question:
TimeComparator implements Comparator<NodeEntry> { @Override public int compare(NodeEntry e1, NodeEntry e2) { long t1 = e1.getModified(); long t2 = e2.getModified(); if (t1 < t2) { return 1; } else if (t1 > t2) { return -1; } else { return 0; } } @Override int compare(NodeEntry e1, NodeEntry e2); }### Answer:
@Test public void test() throws InterruptedException { Node node1 = Node.instanceOf("127.0.0.1:10001"); NodeEntry ne1 = new NodeEntry(node1); Thread.sleep(1); Node node2 = Node.instanceOf("127.0.0.1:10002"); NodeEntry ne2 = new NodeEntry(node2); TimeComparator tc = new TimeComparator(); int result = tc.compare(ne1, ne2); Assert.assertEquals(1, result); } |
### Question:
NodeTable { public synchronized Node addNode(Node n) { NodeEntry e = new NodeEntry(node.getId(), n); if (nodes.contains(e)) { nodes.forEach(nodeEntry -> { if (nodeEntry.equals(e)) { nodeEntry.touch(); } }); return null; } NodeEntry lastSeen = buckets[getBucketId(e)].addNode(e); if (lastSeen != null) { return lastSeen.getNode(); } if (!nodes.contains(e)) { nodes.add(e); } return null; } NodeTable(Node n); Node getNode(); final void initialize(); synchronized Node addNode(Node n); synchronized void dropNode(Node n); synchronized boolean contains(Node n); synchronized void touchNode(Node n); int getBucketsCount(); synchronized NodeBucket[] getBuckets(); int getBucketId(NodeEntry e); synchronized int getNodesCount(); synchronized List<NodeEntry> getAllNodes(); synchronized List<Node> getClosestNodes(byte[] targetId); }### Answer:
@Test public void addNodeTest() { Node node = new Node(ids.get(0), ips[0], 18888, 18888); Assert.assertEquals(0, nodeTable.getNodesCount()); nodeTable.addNode(node); Assert.assertEquals(1, nodeTable.getNodesCount()); Assert.assertTrue(nodeTable.contains(node)); }
@Test public void addNode_bucketFullTest() throws Exception { for (int i = 0; i < KademliaOptions.BUCKET_SIZE; i++) { TimeUnit.MILLISECONDS.sleep(10); addNode(new Node(ids.get(i), ips[i], 18888, 18888)); } Node lastSeen = nodeTable.addNode(new Node(ids.get(16), ips[16], 18888, 18888)); Assert.assertTrue(null != lastSeen); Assert.assertEquals(ips[15], lastSeen.getHost()); } |
### Question:
LiteFnQueryHttpFilter implements Filter { public static Set<String> getFilterPaths() { return filterPaths; } static Set<String> getFilterPaths(); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain); @Override void destroy(); }### Answer:
@Test public void testHttpFilter() { Set<String> urlPathSets = LiteFnQueryHttpFilter.getFilterPaths(); urlPathSets.forEach(urlPath -> { if (urlPath.contains("/walletsolidity")) { fullHttpPort = Args.getInstance().getSolidityHttpPort(); } else if (urlPath.contains("/walletpbft")) { fullHttpPort = Args.getInstance().getPBFTHttpPort(); } else { fullHttpPort = Args.getInstance().getFullNodeHttpPort(); } String url = String.format("http: Args.getInstance().setLiteFullNode(true); Args.getInstance().setOpenHistoryQueryWhenLiteFN(false); String response = sendGetRequest(url); Assert.assertEquals("this API is closed because this node is a lite fullnode", response); Args.getInstance().setLiteFullNode(false); Args.getInstance().setOpenHistoryQueryWhenLiteFN(true); response = sendGetRequest(url); Assert.assertNotEquals("this API is closed because this node is a lite fullnode", response); Args.getInstance().setLiteFullNode(false); Args.getInstance().setOpenHistoryQueryWhenLiteFN(true); response = sendGetRequest(url); Assert.assertNotEquals("this API is closed because this node is a lite fullnode", response); }); } |
### Question:
RuntimeData { public RuntimeData(Object o) { if (o instanceof HttpServletRequest) { address = ((HttpServletRequest) o).getRemoteAddr(); } else if (o instanceof ServerCall) { try { address = ((ServerCall) o).getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR).toString(); } catch (Exception npe) { logger.warn("the address get from the runtime data is a null value unexpected."); } } if (address == null) { logger.warn("assign the address with an empty string."); address = ""; } } RuntimeData(Object o); String getRemoteAddr(); }### Answer:
@Test public void testRuntimeData() { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); RuntimeData data = new RuntimeData(request); Assert.assertTrue("".equals(data.getRemoteAddr())); ServerCall object = Mockito.mock(ServerCall.class); RuntimeData data1 = new RuntimeData(object); Assert.assertTrue("".equals(data1.getRemoteAddr())); Object o = new Object(); RuntimeData data2 = new RuntimeData(o); Assert.assertTrue("".equals(data2.getRemoteAddr())); } |
### Question:
NodeTable { public synchronized void dropNode(Node n) { NodeEntry e = new NodeEntry(node.getId(), n); buckets[getBucketId(e)].dropNode(e); nodes.remove(e); } NodeTable(Node n); Node getNode(); final void initialize(); synchronized Node addNode(Node n); synchronized void dropNode(Node n); synchronized boolean contains(Node n); synchronized void touchNode(Node n); int getBucketsCount(); synchronized NodeBucket[] getBuckets(); int getBucketId(NodeEntry e); synchronized int getNodesCount(); synchronized List<NodeEntry> getAllNodes(); synchronized List<Node> getClosestNodes(byte[] targetId); }### Answer:
@Test public void dropNodeTest() { Node node = new Node(ids.get(0), ips[0], 18888, 18888); nodeTable.addNode(node); Assert.assertTrue(nodeTable.contains(node)); nodeTable.dropNode(node); Assert.assertTrue(!nodeTable.contains(node)); } |
### Question:
SyncBlockChainMsgHandler implements TronMsgHandler { @Override public void processMessage(PeerConnection peer, TronMessage msg) throws P2pException { SyncBlockChainMessage syncBlockChainMessage = (SyncBlockChainMessage) msg; check(peer, syncBlockChainMessage); long remainNum = 0; List<BlockId> summaryChainIds = syncBlockChainMessage.getBlockIds(); LinkedList<BlockId> blockIds = getLostBlockIds(summaryChainIds); if (blockIds.size() == 1) { peer.setNeedSyncFromUs(false); } else { peer.setNeedSyncFromUs(true); remainNum = tronNetDelegate.getHeadBlockId().getNum() - blockIds.peekLast().getNum(); } peer.setLastSyncBlockId(blockIds.peekLast()); peer.setRemainNum(remainNum); peer.sendMessage(new ChainInventoryMessage(blockIds, remainNum)); } @Override void processMessage(PeerConnection peer, TronMessage msg); }### Answer:
@Test public void testProcessMessage() { try { handler.processMessage(peer, new SyncBlockChainMessage(new ArrayList<>())); } catch (P2pException e) { Assert.assertTrue(e.getMessage().equals("SyncBlockChain blockIds is empty")); } } |
### Question:
InventoryMsgHandler implements TronMsgHandler { @Override public void processMessage(PeerConnection peer, TronMessage msg) { InventoryMessage inventoryMessage = (InventoryMessage) msg; InventoryType type = inventoryMessage.getInventoryType(); if (!check(peer, inventoryMessage)) { return; } for (Sha256Hash id : inventoryMessage.getHashList()) { Item item = new Item(id, type); peer.getAdvInvReceive().put(item, System.currentTimeMillis()); advService.addInv(item); } } @Override void processMessage(PeerConnection peer, TronMessage msg); }### Answer:
@Test public void testProcessMessage() { InventoryMessage msg = new InventoryMessage(new ArrayList<>(), InventoryType.TRX); peer.setNeedSyncFromPeer(true); peer.setNeedSyncFromUs(true); handler.processMessage(peer, msg); peer.setNeedSyncFromPeer(true); peer.setNeedSyncFromUs(false); handler.processMessage(peer, msg); peer.setNeedSyncFromPeer(false); peer.setNeedSyncFromUs(true); handler.processMessage(peer, msg); } |
### Question:
NodeTable { public int getBucketsCount() { int i = 0; for (NodeBucket b : buckets) { if (b.getNodesCount() > 0) { i++; } } return i; } NodeTable(Node n); Node getNode(); final void initialize(); synchronized Node addNode(Node n); synchronized void dropNode(Node n); synchronized boolean contains(Node n); synchronized void touchNode(Node n); int getBucketsCount(); synchronized NodeBucket[] getBuckets(); int getBucketId(NodeEntry e); synchronized int getNodesCount(); synchronized List<NodeEntry> getAllNodes(); synchronized List<Node> getClosestNodes(byte[] targetId); }### Answer:
@Test public void getBucketsCountTest() { Assert.assertEquals(0, nodeTable.getBucketsCount()); Node node = new Node(ids.get(0), ips[0], 18888, 18888); nodeTable.addNode(node); Assert.assertEquals(1, nodeTable.getBucketsCount()); } |
### Question:
NodeTable { public synchronized void touchNode(Node n) { NodeEntry e = new NodeEntry(node.getId(), n); for (NodeBucket b : buckets) { if (b.getNodes().contains(e)) { b.getNodes().get(b.getNodes().indexOf(e)).touch(); break; } } } NodeTable(Node n); Node getNode(); final void initialize(); synchronized Node addNode(Node n); synchronized void dropNode(Node n); synchronized boolean contains(Node n); synchronized void touchNode(Node n); int getBucketsCount(); synchronized NodeBucket[] getBuckets(); int getBucketId(NodeEntry e); synchronized int getNodesCount(); synchronized List<NodeEntry> getAllNodes(); synchronized List<Node> getClosestNodes(byte[] targetId); }### Answer:
@Test public void touchNodeTest() throws Exception { Node node = new Node(ids.get(0), ips[0], 18888, 18888); nodeTable.addNode(node); long firstTouchTime = nodeTable.getAllNodes().get(0).getModified(); TimeUnit.MILLISECONDS.sleep(10); nodeTable.touchNode(node); long lastTouchTime = nodeTable.getAllNodes().get(0).getModified(); Assert.assertTrue(firstTouchTime < lastTouchTime); } |
### Question:
NodeTable { public synchronized boolean contains(Node n) { NodeEntry e = new NodeEntry(node.getId(), n); for (NodeBucket b : buckets) { if (b.getNodes().contains(e)) { return true; } } return false; } NodeTable(Node n); Node getNode(); final void initialize(); synchronized Node addNode(Node n); synchronized void dropNode(Node n); synchronized boolean contains(Node n); synchronized void touchNode(Node n); int getBucketsCount(); synchronized NodeBucket[] getBuckets(); int getBucketId(NodeEntry e); synchronized int getNodesCount(); synchronized List<NodeEntry> getAllNodes(); synchronized List<Node> getClosestNodes(byte[] targetId); }### Answer:
@Test public void containsTest() { Node node = new Node(ids.get(0), ips[0], 18888, 18888); Assert.assertTrue(!nodeTable.contains(node)); nodeTable.addNode(node); Assert.assertTrue(nodeTable.contains(node)); } |
### Question:
Reputation { public int getScore() { return getNodeActiveScore() + getPacketLossRateScore() + getNetLatencyScore() + getHandshakeScore() + getTcpFlowScore() + getDisconnectionScore(); } Reputation(NodeStatistics nodeStatistics); int getScore(); }### Answer:
@Test public void testGetScore() { Assert.assertEquals(0, reputation.getScore()); nodeStatistics.messageStatistics.discoverInPong.add(3); Assert.assertEquals(100, reputation.getScore()); nodeStatistics.messageStatistics.discoverOutPing.add(3); Assert.assertEquals(200, reputation.getScore()); nodeStatistics.messageStatistics.discoverOutPing.add(1); Assert.assertEquals(150, reputation.getScore()); nodeStatistics.tcpFlow.add(10240 * 5); Assert.assertEquals(155, reputation.getScore()); nodeStatistics.discoverMessageLatency.add(100); Assert.assertEquals(165, reputation.getScore()); nodeStatistics.notifyDisconnect(); Assert.assertEquals(155, reputation.getScore()); } |
### Question:
NodeManager implements EventHandler { public boolean isNodeAlive(NodeHandler nodeHandler) { return nodeHandler.getState().equals(State.ALIVE) || nodeHandler.getState().equals(State.ACTIVE) || nodeHandler.getState().equals(State.EVICTCANDIDATE); } @Autowired NodeManager(ChainBaseManager chainBaseManager); ScheduledExecutorService getPongTimer(); @Override void channelActivated(); boolean isNodeAlive(NodeHandler nodeHandler); void setMessageSender(Consumer<UdpEvent> messageSender); NodeHandler getNodeHandler(Node n); boolean hasNodeHandler(Node n); NodeTable getTable(); NodeStatistics getNodeStatistics(Node n); @Override void handleEvent(UdpEvent udpEvent); void sendOutbound(UdpEvent udpEvent); List<NodeHandler> getNodes(Predicate<NodeHandler> predicate, int limit); List<NodeHandler> dumpActiveNodes(); Node getPublicHomeNode(); void close(); }### Answer:
@Test public void isNodeAliveTest() { Node node = new Node(new byte[64], "128.0.0.1", 18888, 18888); nodeManager.getTable().addNode(node); NodeHandler nodeHandler = new NodeHandler(node, nodeManager); nodeHandler.changeState(NodeHandler.State.ACTIVE); Assert.assertTrue(nodeManager.isNodeAlive(nodeHandler)); nodeHandler.changeState(NodeHandler.State.ALIVE); Assert.assertTrue(nodeManager.isNodeAlive(nodeHandler)); nodeHandler.changeState(NodeHandler.State.EVICTCANDIDATE); Assert.assertTrue(nodeManager.isNodeAlive(nodeHandler)); } |
### Question:
EmailNotification implements NotificationPlugin { public void sendNotification(ResourceMessage resourceMessage, EntityNotification entityNotification) throws FalconException { try { message.addRecipients(Message.RecipientType.TO, NotificationUtil.getToAddress(entityNotification.getTo())); if (resourceMessage.getAction().equals("wf-instance-succeeded")) { sendSuccessNotification(resourceMessage); } else if ((resourceMessage.getAction().equals("wf-instance-failed"))) { sendFailureNotification(resourceMessage); } Transport.send(message); } catch (MessagingException e) { throw new FalconException("Error occurred while sending email message using SMTP:" +e); } } EmailNotification(); void sendNotification(ResourceMessage resourceMessage, EntityNotification entityNotification); }### Answer:
@Test public void testSendNotification() throws Exception { String notificationType = "email"; String emailTo = "falcon_to@localhost"; Notification notification = new Notification(); notification.setType(notificationType); notification.setTo(emailTo); NotificationPlugin pluginType = NotificationHandler.getNotificationType(notification.getType()); Assert.assertNotNull(pluginType); pluginType.sendNotification(resourceMessage, notification); mailServer.waitForIncomingEmail(5000, 1); Message[] messages = mailServer.getReceivedMessages(); Assert.assertNotNull(messages); Assert.assertEquals(messages[0].getFrom()[0].toString(), EMAIL_FROM); Assert.assertEquals(messages[0].getAllRecipients()[0].toString(), emailTo); Assert.assertEquals(messages[0].getSubject(), "Falcon Instance Succeeded : Workflow id:001-oozie-wf " + "Name:pig-process Type:process"); } |
### Question:
ConfigurationStore implements FalconService { public synchronized void publish(EntityType type, Entity entity) throws FalconException { try { if (get(type, entity.getName()) == null) { persist(type, entity); onAdd(entity); dictionary.get(type).put(entity.getName(), entity); } else { throw new EntityAlreadyExistsException( entity.toShortString() + " already registered with configuration store. " + "Can't be submitted again. Try removing before submitting."); } } catch (IOException e) { throw new StoreAccessException(e); } AUDIT.info(type + "/" + entity.getName() + " is published into config store"); } private ConfigurationStore(); static ConfigurationStore get(); FileSystem getFs(); Path getStorePath(); @Override void init(); void registerListener(ConfigurationChangeListener listener); void unregisterListener(ConfigurationChangeListener listener); synchronized void publish(EntityType type, Entity entity); synchronized void update(EntityType type, Entity entity); synchronized void initiateUpdate(Entity entity); @SuppressWarnings("unchecked") T get(EntityType type, String name); Collection<String> getEntities(EntityType type); synchronized boolean remove(EntityType type, String name); void cleanupUpdateInit(); @Override String getName(); @Override void destroy(); static final EntityType[] ENTITY_DELETE_ORDER; }### Answer:
@Test public void testPublish() throws Exception { Process process = new Process(); process.setName("hello"); store.publish(EntityType.PROCESS, process); Process p = store.get(EntityType.PROCESS, "hello"); Assert.assertEquals(p, process); Assert.assertEquals(p.getVersion(), 0); store.registerListener(listener); process.setName("world"); try { store.publish(EntityType.PROCESS, process); throw new AssertionError("Expected exception"); } catch(FalconException expected) { } store.unregisterListener(listener); } |
### Question:
ConfigurationStore implements FalconService { public static ConfigurationStore get() { return STORE; } private ConfigurationStore(); static ConfigurationStore get(); FileSystem getFs(); Path getStorePath(); @Override void init(); void registerListener(ConfigurationChangeListener listener); void unregisterListener(ConfigurationChangeListener listener); synchronized void publish(EntityType type, Entity entity); synchronized void update(EntityType type, Entity entity); synchronized void initiateUpdate(Entity entity); @SuppressWarnings("unchecked") T get(EntityType type, String name); Collection<String> getEntities(EntityType type); synchronized boolean remove(EntityType type, String name); void cleanupUpdateInit(); @Override String getName(); @Override void destroy(); static final EntityType[] ENTITY_DELETE_ORDER; }### Answer:
@Test public void testGet() throws Exception { Process p = store.get(EntityType.PROCESS, "notfound"); Assert.assertNull(p); } |
### Question:
ConfigurationStore implements FalconService { public synchronized boolean remove(EntityType type, String name) throws FalconException { Map<String, Entity> entityMap = dictionary.get(type); if (entityMap.containsKey(name)) { try { archive(type, name); Entity entity = entityMap.get(name); onRemove(entity); entityMap.remove(name); } catch (IOException e) { throw new StoreAccessException(e); } AUDIT.info(type + " " + name + " is removed from config store"); return true; } return false; } private ConfigurationStore(); static ConfigurationStore get(); FileSystem getFs(); Path getStorePath(); @Override void init(); void registerListener(ConfigurationChangeListener listener); void unregisterListener(ConfigurationChangeListener listener); synchronized void publish(EntityType type, Entity entity); synchronized void update(EntityType type, Entity entity); synchronized void initiateUpdate(Entity entity); @SuppressWarnings("unchecked") T get(EntityType type, String name); Collection<String> getEntities(EntityType type); synchronized boolean remove(EntityType type, String name); void cleanupUpdateInit(); @Override String getName(); @Override void destroy(); static final EntityType[] ENTITY_DELETE_ORDER; }### Answer:
@Test public void testRemove() throws Exception { Process process = new Process(); process.setName("remove"); store.publish(EntityType.PROCESS, process); Process p = store.get(EntityType.PROCESS, "remove"); Assert.assertEquals(p, process); store.remove(EntityType.PROCESS, "remove"); p = store.get(EntityType.PROCESS, "remove"); Assert.assertNull(p); store.publish(EntityType.PROCESS, process); store.registerListener(listener); try { store.remove(EntityType.PROCESS, "remove"); throw new AssertionError("Expected exception"); } catch(FalconException expected) { } store.unregisterListener(listener); } |
### Question:
FeedLocationStore implements ConfigurationChangeListener { @Override public void onChange(Entity oldEntity, Entity newEntity) throws FalconException { onRemove(oldEntity); onAdd(newEntity); } private FeedLocationStore(); static FeedLocationStore get(); @Override void onAdd(Entity entity); @Override void onRemove(Entity entity); @Override void onChange(Entity oldEntity, Entity newEntity); @Override void onReload(Entity entity); Collection<FeedLookupResult.FeedProperties> reverseLookup(String path); }### Answer:
@Test public void testOnChange() throws FalconException{ Feed f1 = createFeed("f1"); f1.getLocations().getLocations().add(createLocation(LocationType.DATA, "/projects/cas/data/hourly/2014/09/09/09")); store.publish(EntityType.FEED, f1); Feed f2 = createFeed("f1"); f2.getLocations().getLocations().add(createLocation(LocationType.DATA, "/projects/cas/data/monthly")); store.initiateUpdate(f2); store.update(EntityType.FEED, f2); store.cleanupUpdateInit(); Feed f3 = createFeed("f2"); f3.getLocations().getLocations().add(createLocation(LocationType.STATS, "/projects/cas/data/hourly/2014/09/09/09")); store.publish(EntityType.FEED, f3); } |
### Question:
FileSystemStorage extends Configured implements Storage { @Override public TYPE getType() { return TYPE.FILESYSTEM; } FileSystemStorage(Feed feed); protected FileSystemStorage(String storageUrl, Locations locations); protected FileSystemStorage(String storageUrl, List<Location> locations); protected FileSystemStorage(String uriTemplate); @Override TYPE getType(); String getStorageUrl(); List<Location> getLocations(); @Override String getUriTemplate(); @Override String getUriTemplate(LocationType locationType); String getUriTemplate(LocationType locationType, List<Location> locationList); Path getWorkingDir(); @Override boolean isIdentical(Storage toCompareAgainst); static Location getLocation(List<Location> locations, LocationType type); @Override void validateACL(AccessControlList acl); @Override StringBuilder evict(String retentionLimit, String timeZone, Path logFilePath); @Override @SuppressWarnings("MagicConstant") List<FeedInstanceStatus> getListing(Feed feed, String clusterName, LocationType locationType,
Date start, Date end); @Override FeedInstanceStatus.AvailabilityStatus getInstanceAvailabilityStatus(Feed feed, String clusterName,
LocationType locationType,
Date instanceTime); FileStatus getFileStatus(FileSystem fileSystem, Path feedInstancePath); Configuration getConf(); @Override String toString(); static final String FEED_PATH_SEP; static final String LOCATION_TYPE_SEP; static final String FILE_SYSTEM_URL; }### Answer:
@Test public void testGetType() throws Exception { final Location location = new Location(); location.setPath("/foo/bar"); location.setType(LocationType.DATA); List<Location> locations = new ArrayList<Location>(); locations.add(location); FileSystemStorage storage = new FileSystemStorage(FileSystemStorage.FILE_SYSTEM_URL, locations); Assert.assertEquals(storage.getType(), Storage.TYPE.FILESYSTEM); } |
### Question:
ClusterEntityParser extends EntityParser<Cluster> { @Override public void validate(Cluster cluster) throws ValidationException { validateScheme(cluster, Interfacetype.READONLY); validateScheme(cluster, Interfacetype.WRITE); validateScheme(cluster, Interfacetype.WORKFLOW); if (ClusterHelper.getInterface(cluster, Interfacetype.MESSAGING) != null) { validateScheme(cluster, Interfacetype.MESSAGING); } if (CatalogServiceFactory.isEnabled() && ClusterHelper.getInterface(cluster, Interfacetype.REGISTRY) != null) { validateScheme(cluster, Interfacetype.REGISTRY); } validateACL(cluster); if (!EntityUtil.responsibleFor(cluster.getColo())) { return; } validateReadInterface(cluster); validateWriteInterface(cluster); validateExecuteInterface(cluster); validateWorkflowInterface(cluster); validateMessagingInterface(cluster); validateRegistryInterface(cluster); validateLocations(cluster); validateProperties(cluster); validateSparkMasterInterface(cluster); } ClusterEntityParser(); @Override void validate(Cluster cluster); }### Answer:
@Test(expectedExceptions = ValidationException.class, expectedExceptionsMessageRegExp = ".*java.net.UnknownHostException.*") public void testParseClusterWithBadWriteInterface() throws Exception { InputStream stream = this.getClass().getResourceAsStream("/config/cluster/cluster-bad-write-endpoint.xml"); Cluster cluster = parser.parse(stream); parser.validate(cluster); } |
### Question:
ChainableMonitoringPlugin extends AbstractFalconAspect implements MonitoringPlugin, AlertingPlugin, AuditingPlugin { @Override public void audit(AuditMessage auditMessage) { for (AuditingPlugin plugin : auditingPlugins) { try { plugin.audit(auditMessage); } catch (Exception e) { LOG.debug("Unable to publish auditMessage to {}", plugin.getClass(), e); } } } ChainableMonitoringPlugin(); @Override void monitor(ResourceMessage message); @Override void publishMessage(ResourceMessage message); @Override void publishAlert(AlertMessage alertMessage); @Override void alert(AlertMessage alertMessage); @Override void publishAudit(AuditMessage auditMessage); @Override void audit(AuditMessage auditMessage); }### Answer:
@Test public void testPlugin() throws Exception { GenericAlert.instrumentFailedInstance("cluster", "process", "agg-coord", "120:df", "ef-id", "wf-user", "1", "DELETE", "now", "error", "none", 1242); GenericAlert.alertJMSMessageConsumerFailed("test-alert", new Exception("test")); GenericAlert.audit(FalconTestUtil.TEST_USER_1, "127.0.0.1", "localhost", "test-action", "127.0.0.1", SchemaHelper.formatDateUTC(new Date())); } |
### Question:
CatalogStorage extends Configured implements Storage { @Override public TYPE getType() { return TYPE.TABLE; } protected CatalogStorage(Feed feed); CatalogStorage(Cluster cluster, CatalogTable table); protected CatalogStorage(String catalogUrl, CatalogTable table); protected CatalogStorage(String catalogUrl, String tableUri); protected CatalogStorage(String uriTemplate); protected CatalogStorage(String uriTemplate, Configuration conf); String getCatalogUrl(); String getDatabase(); String getTable(); Map<String, String> getPartitions(); String getPartitionValue(String key); boolean hasPartition(String key); List<String> getDatedPartitionKeys(); String toPartitionFilter(); String toPartitionAsPath(); @Override TYPE getType(); @Override String getUriTemplate(); @Override String getUriTemplate(LocationType locationType); @Override boolean isIdentical(Storage toCompareAgainst); @Override void validateACL(AccessControlList acl); @Override List<FeedInstanceStatus> getListing(Feed feed, String clusterName, LocationType locationType,
Date start, Date end); @Override FeedInstanceStatus.AvailabilityStatus getInstanceAvailabilityStatus(Feed feed, String clusterName,
LocationType locationType, Date instanceTime); @Override StringBuilder evict(String retentionLimit, String timeZone, Path logFilePath); @Override String toString(); static final String PARTITION_SEPARATOR; static final String PARTITION_KEYVAL_SEPARATOR; static final String INPUT_PATH_SEPARATOR; static final String OUTPUT_PATH_SEPARATOR; static final String PARTITION_VALUE_QUOTE; static final String CATALOG_URL; }### Answer:
@Test public void testGetType() throws Exception { String table = "catalog:clicksdb:clicks#ds=${YEAR}-${MONTH}-${DAY};region=us"; CatalogStorage storage = new CatalogStorage(CatalogStorage.CATALOG_URL, table); Assert.assertEquals(Storage.TYPE.TABLE, storage.getType()); Assert.assertNotNull(storage.getConf()); } |
### Question:
ProxyUserService implements FalconService { @Override public String getName() { return SERVICE_NAME; } @Override String getName(); @Override void init(); void validate(String proxyUser, String proxyHost, String doAsUser); @Override void destroy(); static final String SERVICE_NAME; }### Answer:
@Test public void testGetName() throws Exception { proxyUserService.init(); Assert.assertEquals(proxyUserService.getName(), ProxyUserService.SERVICE_NAME); } |
### Question:
ProxyUserService implements FalconService { private void validateGroup(String proxyUser, String user, Set<String> validGroups) throws IOException { if (validGroups != null) { List<String> userGroups = Services.get().<GroupsService>getService(GroupsService.SERVICE_NAME) .getGroups(user); for (String g : validGroups) { if (userGroups.contains(g)) { return; } } throw new AccessControlException( MessageFormat.format("Unauthorized proxyuser [{0}] for user [{1}], not in proxyuser groups", proxyUser, user)); } } @Override String getName(); @Override void init(); void validate(String proxyUser, String proxyHost, String doAsUser); @Override void destroy(); static final String SERVICE_NAME; }### Answer:
@Test public void testValidateGroup() throws Exception { RuntimeProperties.get().setProperty("falcon.service.ProxyUserService.proxyuser.foo.hosts", "*"); RuntimeProperties.get().setProperty("falcon.service.ProxyUserService.proxyuser.foo.groups", getGroup()); proxyUserService.init(); proxyUserService.validate("foo", "localhost", System.getProperty("user.name")); } |
### Question:
GroupsService implements FalconService { @Override public String getName() { return SERVICE_NAME; } @Override void init(); @Override void destroy(); @Override String getName(); List<String> getGroups(String user); static final String SERVICE_NAME; }### Answer:
@Test public void testGetName() throws Exception { Assert.assertEquals(service.getName(), GroupsService.SERVICE_NAME); } |
### Question:
GroupsService implements FalconService { public List<String> getGroups(String user) throws IOException { return hGroups.getGroups(user); } @Override void init(); @Override void destroy(); @Override String getName(); List<String> getGroups(String user); static final String SERVICE_NAME; }### Answer:
@Test public void testGroupsService() throws Exception { List<String> g = service.getGroups(System.getProperty("user.name")); Assert.assertNotSame(g.size(), 0); } |
### Question:
AuthenticationInitializationService implements FalconService { @Override public String getName() { return SERVICE_NAME; } @Override String getName(); @Override void init(); @Override void destroy(); }### Answer:
@Test public void testGetName() { Assert.assertEquals("Authentication initialization service", authenticationService.getName()); } |
### Question:
SecurityUtil { public static String getAuthenticationType() { return StartupProperties.get().getProperty( AUTHENTICATION_TYPE, PseudoAuthenticationHandler.TYPE); } private SecurityUtil(); static String getAuthenticationType(); static boolean isSecurityEnabled(); static String getLocalHostName(); static boolean isAuthorizationEnabled(); static boolean isCSRFFilterEnabled(); static AuthorizationProvider getAuthorizationProvider(); static void tryProxy(Entity entity, final String doAsUser); static final String AUTHENTICATION_TYPE; static final String NN_PRINCIPAL; static final String RM_PRINCIPAL; static final String HIVE_METASTORE_KERBEROS_PRINCIPAL; static final String METASTORE_USE_THRIFT_SASL; static final String METASTORE_PRINCIPAL; }### Answer:
@Test public void testDefaultGetAuthenticationType() throws Exception { Assert.assertEquals(SecurityUtil.getAuthenticationType(), "simple"); }
@Test public void testGetAuthenticationType() throws Exception { try { StartupProperties.get().setProperty(SecurityUtil.AUTHENTICATION_TYPE, "kerberos"); Assert.assertEquals(SecurityUtil.getAuthenticationType(), "kerberos"); } finally { StartupProperties.get().setProperty(SecurityUtil.AUTHENTICATION_TYPE, "simple"); } } |
### Question:
SecurityUtil { public static boolean isSecurityEnabled() { String authenticationType = StartupProperties.get().getProperty( AUTHENTICATION_TYPE, PseudoAuthenticationHandler.TYPE); final boolean useKerberos; if (authenticationType == null || PseudoAuthenticationHandler.TYPE.equals(authenticationType)) { useKerberos = false; } else if (KerberosAuthenticationHandler.TYPE.equals(authenticationType)) { useKerberos = true; } else { throw new IllegalArgumentException("Invalid attribute value for " + AUTHENTICATION_TYPE + " of " + authenticationType); } return useKerberos; } private SecurityUtil(); static String getAuthenticationType(); static boolean isSecurityEnabled(); static String getLocalHostName(); static boolean isAuthorizationEnabled(); static boolean isCSRFFilterEnabled(); static AuthorizationProvider getAuthorizationProvider(); static void tryProxy(Entity entity, final String doAsUser); static final String AUTHENTICATION_TYPE; static final String NN_PRINCIPAL; static final String RM_PRINCIPAL; static final String HIVE_METASTORE_KERBEROS_PRINCIPAL; static final String METASTORE_USE_THRIFT_SASL; static final String METASTORE_PRINCIPAL; }### Answer:
@Test public void testIsSecurityEnabledByDefault() throws Exception { Assert.assertFalse(SecurityUtil.isSecurityEnabled()); }
@Test public void testIsSecurityEnabled() throws Exception { try { StartupProperties.get().setProperty(SecurityUtil.AUTHENTICATION_TYPE, "kerberos"); Assert.assertTrue(SecurityUtil.isSecurityEnabled()); } finally { StartupProperties.get().setProperty(SecurityUtil.AUTHENTICATION_TYPE, "simple"); } } |
### Question:
SecurityUtil { public static boolean isAuthorizationEnabled() { return Boolean.valueOf(StartupProperties.get().getProperty( "falcon.security.authorization.enabled", "false")); } private SecurityUtil(); static String getAuthenticationType(); static boolean isSecurityEnabled(); static String getLocalHostName(); static boolean isAuthorizationEnabled(); static boolean isCSRFFilterEnabled(); static AuthorizationProvider getAuthorizationProvider(); static void tryProxy(Entity entity, final String doAsUser); static final String AUTHENTICATION_TYPE; static final String NN_PRINCIPAL; static final String RM_PRINCIPAL; static final String HIVE_METASTORE_KERBEROS_PRINCIPAL; static final String METASTORE_USE_THRIFT_SASL; static final String METASTORE_PRINCIPAL; }### Answer:
@Test public void testIsAuthorizationEnabledByDefault() throws Exception { Assert.assertFalse(SecurityUtil.isAuthorizationEnabled()); }
@Test public void testIsAuthorizationEnabled() throws Exception { try { StartupProperties.get().setProperty("falcon.security.authorization.enabled", "true"); Assert.assertTrue(SecurityUtil.isAuthorizationEnabled()); } finally { StartupProperties.get().setProperty("falcon.security.authorization.enabled", "false"); } } |
### Question:
SecurityUtil { public static AuthorizationProvider getAuthorizationProvider() throws FalconException { String providerClassName = StartupProperties.get().getProperty( "falcon.security.authorization.provider", "org.apache.falcon.security.DefaultAuthorizationProvider"); return ReflectionUtils.getInstanceByClassName(providerClassName); } private SecurityUtil(); static String getAuthenticationType(); static boolean isSecurityEnabled(); static String getLocalHostName(); static boolean isAuthorizationEnabled(); static boolean isCSRFFilterEnabled(); static AuthorizationProvider getAuthorizationProvider(); static void tryProxy(Entity entity, final String doAsUser); static final String AUTHENTICATION_TYPE; static final String NN_PRINCIPAL; static final String RM_PRINCIPAL; static final String HIVE_METASTORE_KERBEROS_PRINCIPAL; static final String METASTORE_USE_THRIFT_SASL; static final String METASTORE_PRINCIPAL; }### Answer:
@Test public void testGetAuthorizationProviderByDefault() throws Exception { Assert.assertNotNull(SecurityUtil.getAuthorizationProvider()); Assert.assertEquals(SecurityUtil.getAuthorizationProvider().getClass(), DefaultAuthorizationProvider.class); } |
### Question:
SecurityUtil { public static boolean isCSRFFilterEnabled() { return Boolean.valueOf(StartupProperties.get().getProperty( "falcon.security.csrf.enabled", "false")); } private SecurityUtil(); static String getAuthenticationType(); static boolean isSecurityEnabled(); static String getLocalHostName(); static boolean isAuthorizationEnabled(); static boolean isCSRFFilterEnabled(); static AuthorizationProvider getAuthorizationProvider(); static void tryProxy(Entity entity, final String doAsUser); static final String AUTHENTICATION_TYPE; static final String NN_PRINCIPAL; static final String RM_PRINCIPAL; static final String HIVE_METASTORE_KERBEROS_PRINCIPAL; static final String METASTORE_USE_THRIFT_SASL; static final String METASTORE_PRINCIPAL; }### Answer:
@Test public void testIsCSRFFilterEnabledByDefault() throws Exception { Assert.assertFalse(SecurityUtil.isCSRFFilterEnabled()); }
@Test public void testIsCSRFFilterEnabled() throws Exception { try { StartupProperties.get().setProperty("falcon.security.csrf.enabled", "true"); Assert.assertTrue(SecurityUtil.isCSRFFilterEnabled()); } finally { StartupProperties.get().setProperty("falcon.security.csrf.enabled", "false"); } } |
### Question:
CurrentUser { public static String getUser() { CurrentUser user = CURRENT_USER.get(); if (user == null || user.proxyUser == null) { throw new IllegalStateException("No user logged into the system"); } else { return user.proxyUser; } } private CurrentUser(String authenticatedUser); static void authenticate(final String user); static void proxyDoAsUser(final String doAsUser, final String proxyHost); static void proxy(final String aclOwner, final String aclGroup); static void clear(); static boolean isAuthenticated(); static String getAuthenticatedUser(); static UserGroupInformation getAuthenticatedUGI(); static String getUser(); static UserGroupInformation createProxyUGI(String proxyUser); static UserGroupInformation getProxyUGI(); static Set<String> getGroupNames(); static String getPrimaryGroupName(); }### Answer:
@Test(threadPoolSize = 10, invocationCount = 10, timeOut = 10000) public void testGetUser() throws Exception { String id = Long.toString(System.nanoTime()); CurrentUser.authenticate(id); Assert.assertEquals(CurrentUser.getAuthenticatedUser(), id); Assert.assertEquals(CurrentUser.getUser(), id); }
@Test (expectedExceptions = IllegalStateException.class) public void testGetUserInvalid() throws Exception { CurrentUser.getUser(); } |
### Question:
CurrentUser { public static void authenticate(final String user) { if (StringUtils.isEmpty(user)) { throw new IllegalStateException("Bad user name sent for authentication"); } LOG.info("Logging in {}", user); CurrentUser currentUser = new CurrentUser(user); CURRENT_USER.set(currentUser); } private CurrentUser(String authenticatedUser); static void authenticate(final String user); static void proxyDoAsUser(final String doAsUser, final String proxyHost); static void proxy(final String aclOwner, final String aclGroup); static void clear(); static boolean isAuthenticated(); static String getAuthenticatedUser(); static UserGroupInformation getAuthenticatedUGI(); static String getUser(); static UserGroupInformation createProxyUGI(String proxyUser); static UserGroupInformation getProxyUGI(); static Set<String> getGroupNames(); static String getPrimaryGroupName(); }### Answer:
@Test (expectedExceptions = IllegalStateException.class) public void testAuthenticateBadUser() throws Exception { CurrentUser.authenticate(""); } |
### Question:
CurrentUser { public static String getAuthenticatedUser() { CurrentUser user = CURRENT_USER.get(); if (user == null || user.authenticatedUser == null) { throw new IllegalStateException("No user logged into the system"); } else { return user.authenticatedUser; } } private CurrentUser(String authenticatedUser); static void authenticate(final String user); static void proxyDoAsUser(final String doAsUser, final String proxyHost); static void proxy(final String aclOwner, final String aclGroup); static void clear(); static boolean isAuthenticated(); static String getAuthenticatedUser(); static UserGroupInformation getAuthenticatedUGI(); static String getUser(); static UserGroupInformation createProxyUGI(String proxyUser); static UserGroupInformation getProxyUGI(); static Set<String> getGroupNames(); static String getPrimaryGroupName(); }### Answer:
@Test (expectedExceptions = IllegalStateException.class) public void testGetAuthenticatedUserInvalid() throws Exception { CurrentUser.getAuthenticatedUser(); } |
### Question:
CurrentUser { public static void proxy(final String aclOwner, final String aclGroup) { if (!isAuthenticated() || StringUtils.isEmpty(aclOwner)) { throw new IllegalStateException("Authentication not done or Bad user name"); } CurrentUser user = CURRENT_USER.get(); LOG.info("Authenticated user {} is proxying entity owner {}/{}", user.authenticatedUser, aclOwner, aclGroup); AUDIT.info("Authenticated user {} is proxying entity owner {}/{}", user.authenticatedUser, aclOwner, aclGroup); user.proxyUser = aclOwner; } private CurrentUser(String authenticatedUser); static void authenticate(final String user); static void proxyDoAsUser(final String doAsUser, final String proxyHost); static void proxy(final String aclOwner, final String aclGroup); static void clear(); static boolean isAuthenticated(); static String getAuthenticatedUser(); static UserGroupInformation getAuthenticatedUGI(); static String getUser(); static UserGroupInformation createProxyUGI(String proxyUser); static UserGroupInformation getProxyUGI(); static Set<String> getGroupNames(); static String getPrimaryGroupName(); }### Answer:
@Test (expectedExceptions = IllegalStateException.class) public void testProxyWithNoAuth() throws Exception { CurrentUser.proxy(FalconTestUtil.TEST_USER_1, "falcon"); }
@Test public void testProxy() throws Exception { CurrentUser.authenticate("real"); CurrentUser.proxy(EntityBuilderTestUtil.USER, "users"); UserGroupInformation proxyUgi = CurrentUser.getProxyUGI(); Assert.assertNotNull(proxyUgi); Assert.assertEquals(proxyUgi.getUserName(), EntityBuilderTestUtil.USER); Assert.assertEquals(CurrentUser.getAuthenticatedUser(), "real"); Assert.assertEquals(CurrentUser.getUser(), EntityBuilderTestUtil.USER); } |
### Question:
MetadataMappingService implements FalconService, ConfigurationChangeListener, WorkflowExecutionListener { @Override public String getName() { return SERVICE_NAME; } @Override String getName(); @Override void init(); static Graph initializeGraphDB(); static Configuration getConfiguration(); Graph getGraph(); KeyIndexableGraph getIndexableGraph(); TransactionalGraph getTransactionalGraph(); TitanBlueprintsGraph getTitanGraph(); Set<String> getVertexIndexedKeys(); Set<String> getEdgeIndexedKeys(); @Override void destroy(); @Override void onAdd(final Entity entity); @Override void onRemove(Entity entity); @Override void onChange(final Entity oldEntity, final Entity newEntity); @Override void onReload(Entity entity); @Override void onStart(final WorkflowExecutionContext context); @Override void onSuccess(final WorkflowExecutionContext context); @Override void onFailure(final WorkflowExecutionContext context); @Override void onSuspend(final WorkflowExecutionContext context); @Override void onWait(final WorkflowExecutionContext context); static final String SERVICE_NAME; static final String PROPERTY_KEY_STORAGE_BACKEND; static final String STORAGE_BACKEND_HBASE; static final String STORAGE_BACKEND_BDB; static final String PROPERTY_KEY_STORAGE_HOSTNAME; static final String PROPERTY_KEY_STORAGE_TABLE; static final Set<String> PROPERTY_KEYS_HBASE; static final String PROPERTY_KEY_STORAGE_DIRECTORY; static final String PROPERTY_KEY_SERIALIZE_PATH; static final Set<String> PROPERTY_KEYS_BDB; }### Answer:
@Test public void testGetName() throws Exception { Assert.assertEquals(service.getName(), MetadataMappingService.SERVICE_NAME); } |
### Question:
MetadataMappingService implements FalconService, ConfigurationChangeListener, WorkflowExecutionListener { public Graph getGraph() { return graph; } @Override String getName(); @Override void init(); static Graph initializeGraphDB(); static Configuration getConfiguration(); Graph getGraph(); KeyIndexableGraph getIndexableGraph(); TransactionalGraph getTransactionalGraph(); TitanBlueprintsGraph getTitanGraph(); Set<String> getVertexIndexedKeys(); Set<String> getEdgeIndexedKeys(); @Override void destroy(); @Override void onAdd(final Entity entity); @Override void onRemove(Entity entity); @Override void onChange(final Entity oldEntity, final Entity newEntity); @Override void onReload(Entity entity); @Override void onStart(final WorkflowExecutionContext context); @Override void onSuccess(final WorkflowExecutionContext context); @Override void onFailure(final WorkflowExecutionContext context); @Override void onSuspend(final WorkflowExecutionContext context); @Override void onWait(final WorkflowExecutionContext context); static final String SERVICE_NAME; static final String PROPERTY_KEY_STORAGE_BACKEND; static final String STORAGE_BACKEND_HBASE; static final String STORAGE_BACKEND_BDB; static final String PROPERTY_KEY_STORAGE_HOSTNAME; static final String PROPERTY_KEY_STORAGE_TABLE; static final Set<String> PROPERTY_KEYS_HBASE; static final String PROPERTY_KEY_STORAGE_DIRECTORY; static final String PROPERTY_KEY_SERIALIZE_PATH; static final Set<String> PROPERTY_KEYS_BDB; }### Answer:
@Test public void testOnAddClusterEntity() throws Exception { long beforeVerticesCount = getVerticesCount(service.getGraph()); long beforeEdgesCount = getEdgesCount(service.getGraph()); clusterEntity = addClusterEntity(CLUSTER_ENTITY_NAME, COLO_NAME, "classification=production"); verifyEntityWasAddedToGraph(CLUSTER_ENTITY_NAME, RelationshipType.CLUSTER_ENTITY); verifyClusterEntityEdges(); Assert.assertEquals(getVerticesCount(service.getGraph()), beforeVerticesCount + 4); Assert.assertEquals(getEdgesCount(service.getGraph()), beforeEdgesCount + 3); } |
### Question:
HadoopClientFactory { public static HadoopClientFactory get() { return INSTANCE; } private HadoopClientFactory(); static HadoopClientFactory get(); FileSystem createFalconFileSystem(final URI uri); FileSystem createFalconFileSystem(final Configuration conf); FileSystem createProxiedFileSystem(final Configuration conf); DistributedFileSystem createDistributedProxiedFileSystem(final Configuration conf); FileSystem createProxiedFileSystem(final URI uri); FileSystem createProxiedFileSystem(final URI uri,
final Configuration conf); @SuppressWarnings("ResultOfMethodCallIgnored") FileSystem createFileSystem(UserGroupInformation ugi, final URI uri,
final Configuration conf); @SuppressWarnings("ResultOfMethodCallIgnored") DistributedFileSystem createDistributedFileSystem(UserGroupInformation ugi, final URI uri,
final Configuration conf); void validateJobClient(String executeUrl, String rmPrincipal); static FsPermission getDirDefaultPermission(Configuration conf); static FsPermission getFileDefaultPermission(Configuration conf); static FsPermission getDirDefault(); static FsPermission getFileDefault(); static void mkdirsWithDefaultPerms(FileSystem fs, Path path); static void mkdirs(FileSystem fs, Path path,
FsPermission permission); static final String FS_DEFAULT_NAME_KEY; static final String MR_JT_ADDRESS_KEY; static final String YARN_RM_ADDRESS_KEY; static final FsPermission READ_EXECUTE_PERMISSION; static final FsPermission ALL_PERMISSION; static final FsPermission READ_ONLY_PERMISSION; }### Answer:
@Test public void testGet() throws Exception { HadoopClientFactory clientFactory = HadoopClientFactory.get(); Assert.assertNotNull(clientFactory); } |
### Question:
WorkflowJobEndNotificationService implements FalconService { @Override public String getName() { return SERVICE_NAME; } @Override String getName(); @Override void init(); @Override void destroy(); void registerListener(WorkflowExecutionListener listener); void unregisterListener(WorkflowExecutionListener listener); void notifyFailure(WorkflowExecutionContext context); void notifySuccess(WorkflowExecutionContext context); void notifyStart(WorkflowExecutionContext context); void notifySuspend(WorkflowExecutionContext context); void notifyWait(WorkflowExecutionContext context); static final String SERVICE_NAME; }### Answer:
@Test public void testGetName() throws Exception { Assert.assertEquals(service.getName(), WorkflowJobEndNotificationService.SERVICE_NAME); } |
### Question:
EvictionHelper { private EvictionHelper(){} private EvictionHelper(); static Pair<Date, Date> getDateRange(String period); static Long evalExpressionToMilliSeconds(String period); }### Answer:
@Test public void testEvictionHelper() throws Exception { Assert.assertEquals(EvictionHelper.evalExpressionToMilliSeconds("days(3)").longValue(), 259200000); Assert.assertEquals(EvictionHelper.evalExpressionToMilliSeconds("days(1)").longValue(), 86400000); Assert.assertEquals(EvictionHelper.evalExpressionToMilliSeconds("hours(5)").longValue(), 18000000); Assert.assertEquals(EvictionHelper.evalExpressionToMilliSeconds("minutes(5)").longValue(), 300000); Assert.assertEquals(EvictionHelper.evalExpressionToMilliSeconds("minutes(1)").longValue(), 60000); } |
### Question:
EvictedInstanceSerDe { public static void serializeEvictedInstancePaths(final FileSystem fileSystem, final Path logFilePath, StringBuffer instances) throws IOException { LOG.info("Writing deleted instances {} to path {}", instances, logFilePath); OutputStream out = null; try { out = fileSystem.create(logFilePath); instances.insert(0, INSTANCEPATH_PREFIX); out.write(instances.toString().getBytes()); FsPermission permission = new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL); fileSystem.setPermission(logFilePath, permission); } finally { if (out != null) { out.close(); } } if (LOG.isDebugEnabled()) { logEvictedInstancePaths(fileSystem, logFilePath); } } private EvictedInstanceSerDe(); static void serializeEvictedInstancePaths(final FileSystem fileSystem,
final Path logFilePath,
StringBuffer instances); static String[] deserializeEvictedInstancePaths(final FileSystem fileSystem,
final Path logFile); static final String INSTANCEPATH_PREFIX; static final String INSTANCEPATH_SEPARATOR; }### Answer:
@Test public void testSerializeEvictedInstancePathsForNoEviction() throws Exception { EvictedInstanceSerDe.serializeEvictedInstancePaths(fs, csvFilePathWithNoContent, new StringBuffer()); Assert.assertEquals(readLogFile(csvFilePathWithNoContent), EvictedInstanceSerDe.INSTANCEPATH_PREFIX); }
@Test public void testSerializeEvictedInstancePathsWithEviction() throws Exception { EvictedInstanceSerDe.serializeEvictedInstancePaths(fs, csvFilePathWithContent, evictedInstancePaths); Assert.assertEquals(readLogFile(csvFilePathWithContent), evictedInstancePaths.toString()); } |
### Question:
EvictedInstanceSerDe { public static String[] deserializeEvictedInstancePaths(final FileSystem fileSystem, final Path logFile) throws IOException { ByteArrayOutputStream writer = new ByteArrayOutputStream(); InputStream instance = fileSystem.open(logFile); IOUtils.copyBytes(instance, writer, 4096, true); String[] instancePaths = writer.toString().split(INSTANCEPATH_PREFIX); if (instancePaths.length <= 1) { LOG.info("Returning 0 instance paths for feed "); return new String[0]; } else { LOG.info("Returning instance paths for feed {}", instancePaths[1]); return instancePaths[1].split(INSTANCEPATH_SEPARATOR); } } private EvictedInstanceSerDe(); static void serializeEvictedInstancePaths(final FileSystem fileSystem,
final Path logFilePath,
StringBuffer instances); static String[] deserializeEvictedInstancePaths(final FileSystem fileSystem,
final Path logFile); static final String INSTANCEPATH_PREFIX; static final String INSTANCEPATH_SEPARATOR; }### Answer:
@Test(dependsOnMethods = "testSerializeEvictedInstancePathsForNoEviction") public void testDeserializeEvictedInstancePathsForNoEviction() throws Exception { String[] instancePaths = EvictedInstanceSerDe.deserializeEvictedInstancePaths(fs, csvFilePathWithNoContent); Assert.assertEquals(instancePaths.length, 0); }
@Test(dependsOnMethods = "testSerializeEvictedInstancePathsWithEviction") public void testDeserializeEvictedInstancePathsWithEviction() throws Exception { String[] instancePaths = EvictedInstanceSerDe.deserializeEvictedInstancePaths(fs, csvFilePathWithContent); Assert.assertEquals(instancePaths.length, 2); Assert.assertTrue(instancePaths[0].equals( "thrift: Assert.assertTrue(instancePaths[1].equals( "thrift: } |
### Question:
ExtensionStore { public Map<String, String> getExtensionResources(final String extensionName) throws StoreAccessException { Map<String, String> extensionFileMap = new HashMap<>(); try { Path extensionPath = new Path(storePath, extensionName.toLowerCase()); Path resourcesPath = null; FileStatus[] files = fs.listStatus(extensionPath); for (FileStatus fileStatus : files) { if (fileStatus.getPath().getName().equalsIgnoreCase(RESOURCES_DIR)) { resourcesPath = fileStatus.getPath(); break; } } if (resourcesPath == null) { throw new StoreAccessException(" For extension " + extensionName + " there is no " + RESOURCES_DIR + "at the extension store path " + storePath); } RemoteIterator<LocatedFileStatus> fileStatusListIterator = fs.listFiles(resourcesPath, true); while (fileStatusListIterator.hasNext()) { LocatedFileStatus fileStatus = fileStatusListIterator.next(); Path filePath = Path.getPathWithoutSchemeAndAuthority(fileStatus.getPath()); extensionFileMap.put(filePath.getName(), filePath.toString()); } } catch (IOException e) { throw new StoreAccessException(e); } return extensionFileMap; } private ExtensionStore(); static ExtensionMetaStore getMetaStore(); static ExtensionStore get(); Map<String, String> getExtensionResources(final String extensionName); String getExtensionLibPath(final String extensionName); String getExtensionResource(final String resourcePath); String deleteExtension(final String extensionName, String currentUser); String registerExtension(final String extensionName, final String path, final String description,
String extensionOwner); String getResource(final String extensionResourcePath); Path getExtensionStorePath(); boolean isExtensionStoreInitialized(); String updateExtensionStatus(final String extensionName, String currentUser, ExtensionStatus status); }### Answer:
@Test public void testGetExtensionResources() throws StoreAccessException { String extensionName = new HdfsMirroringExtension().getName(); Map<String, String> resources = store.getExtensionResources(extensionName); for (Map.Entry<String, String> entry : resources.entrySet()) { String path = resourcesMap.get(entry.getKey()); Assert.assertEquals(entry.getValue(), path); } } |
### Question:
ExtensionStore { public String getExtensionLibPath(final String extensionName) throws StoreAccessException { try { Path extensionPath = new Path(storePath, extensionName.toLowerCase()); Path libsPath = null; FileStatus[] files = fs.listStatus(extensionPath); for (FileStatus fileStatus : files) { if (fileStatus.getPath().getName().equalsIgnoreCase(LIBS_DIR)) { libsPath = Path.getPathWithoutSchemeAndAuthority(fileStatus.getPath()); break; } } if (libsPath == null) { LOG.info("For extension " + extensionName + " there is no " + LIBS_DIR + "at the extension store path " + extensionPath); return null; } else { return libsPath.toString(); } } catch (IOException e) { throw new StoreAccessException(e); } } private ExtensionStore(); static ExtensionMetaStore getMetaStore(); static ExtensionStore get(); Map<String, String> getExtensionResources(final String extensionName); String getExtensionLibPath(final String extensionName); String getExtensionResource(final String resourcePath); String deleteExtension(final String extensionName, String currentUser); String registerExtension(final String extensionName, final String path, final String description,
String extensionOwner); String getResource(final String extensionResourcePath); Path getExtensionStorePath(); boolean isExtensionStoreInitialized(); String updateExtensionStatus(final String extensionName, String currentUser, ExtensionStatus status); }### Answer:
@Test public void testGetExtensionLibPath() throws StoreAccessException { String extensionName = new HdfsMirroringExtension().getName(); String libPath = extensionStorePath + "/hdfs-mirroring/libs"; Assert.assertEquals(store.getExtensionLibPath(extensionName), libPath); } |
### Question:
ExtensionStore { public String deleteExtension(final String extensionName, String currentUser) throws FalconException { ExtensionType extensionType = AbstractExtension.isExtensionTrusted(extensionName) ? ExtensionType.TRUSTED : ExtensionType.CUSTOM; if (extensionType.equals(ExtensionType.TRUSTED)) { throw new ValidationException(extensionName + " is trusted cannot be deleted."); } else if (!metaStore.checkIfExtensionExists(extensionName)) { throw new FalconException("Extension:" + extensionName + " is not registered with Falcon."); } else if (!metaStore.getDetail(extensionName).getExtensionOwner().equals(currentUser)) { throw new FalconException("User: " + currentUser + " is not allowed to delete extension: " + extensionName); } else { metaStore.deleteExtension(extensionName); return "Deleted extension:" + extensionName; } } private ExtensionStore(); static ExtensionMetaStore getMetaStore(); static ExtensionStore get(); Map<String, String> getExtensionResources(final String extensionName); String getExtensionLibPath(final String extensionName); String getExtensionResource(final String resourcePath); String deleteExtension(final String extensionName, String currentUser); String registerExtension(final String extensionName, final String path, final String description,
String extensionOwner); String getResource(final String extensionResourcePath); Path getExtensionStorePath(); boolean isExtensionStoreInitialized(); String updateExtensionStatus(final String extensionName, String currentUser, ExtensionStatus status); }### Answer:
@Test public void testDeleteExtension() throws IOException, URISyntaxException, FalconException { String extensionPath = EXTENSION_PATH + "testDelete"; createLibs(extensionPath); createReadmeAndJar(extensionPath); createMETA(extensionPath); store = ExtensionStore.get(); store.registerExtension("toBeDeleted", STORAGE_URL + extensionPath, "test desc", "falconUser"); Assert.assertTrue(store.getResource(STORAGE_URL + extensionPath + "/README").equals("README")); store.deleteExtension("toBeDeleted", "falconUser"); ExtensionMetaStore metaStore = new ExtensionMetaStore(); Assert.assertEquals(metaStore.getAllExtensions().size(), 0); } |
### Question:
ExtensionService implements FalconService { @Override public String getName() { return SERVICE_NAME; } @Override String getName(); @Override void init(); @Override void destroy(); static ExtensionStore getExtensionStore(); static final String SERVICE_NAME; }### Answer:
@Test public void testGetName() throws Exception { Assert.assertEquals(service.getName(), ExtensionService.SERVICE_NAME); } |
### Question:
ExtensionService implements FalconService { public static ExtensionStore getExtensionStore() { return ExtensionStore.get(); } @Override String getName(); @Override void init(); @Override void destroy(); static ExtensionStore getExtensionStore(); static final String SERVICE_NAME; }### Answer:
@Test public void testGetExtensionStore() throws Exception { Assert.assertNotNull(ExtensionService.getExtensionStore()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.