method2testcases
stringlengths 118
6.63k
|
---|
### Question:
SafetyFactory { @Deprecated public static XMLInputFactory createXMLInputFactory() { return SafeStaxParserFactory.createXMLInputFactory(); } private SafetyFactory(); @Deprecated static XMLInputFactory createXMLInputFactory(); @Deprecated static DocumentBuilder createDocumentBuilder(boolean namespaceAware); }### Answer:
@Test public void test_createXMLInputFactory() { assertThat(SafetyFactory.createXMLInputFactory()).isNotNull(); } |
### Question:
RuleMetadataLoader { static String[] getStringArray(Map<String, Object> map, String propertyName) { Object propertyValue = map.get(propertyName); if (!(propertyValue instanceof List)) { throw new IllegalStateException(String.format(INVALID_PROPERTY_MESSAGE, propertyName)); } return ((List<String>) propertyValue).toArray(new String[0]); } RuleMetadataLoader(String resourceFolder); RuleMetadataLoader(String resourceFolder, String defaultProfilePath); private RuleMetadataLoader(String resourceFolder, Set<String> activatedByDefault); void addRulesByAnnotatedClass(NewRepository repository, List<Class<?>> ruleClasses); void addRulesByRuleKey(NewRepository repository, List<String> ruleKeys); }### Answer:
@Test public void getStringArray() throws Exception { Map<String, Object> map = Collections.singletonMap("key", Arrays.asList("x", "y")); assertThat(RuleMetadataLoader.getStringArray(map, "key")).containsExactly("x", "y"); }
@Test(expected = IllegalStateException.class) public void getStringArray_with_invalid_type() throws Exception { Map<String, Object> map = Collections.singletonMap("key", "x"); RuleMetadataLoader.getStringArray(map, "key"); }
@Test(expected = IllegalStateException.class) public void getStringArray_without_property() throws Exception { RuleMetadataLoader.getStringArray(Collections.emptyMap(), "key"); } |
### Question:
SafetyFactory { @Deprecated public static DocumentBuilder createDocumentBuilder(boolean namespaceAware) { return SafeDomParserFactory.createDocumentBuilder(namespaceAware); } private SafetyFactory(); @Deprecated static XMLInputFactory createXMLInputFactory(); @Deprecated static DocumentBuilder createDocumentBuilder(boolean namespaceAware); }### Answer:
@Test public void test_createDocumentBuilder() { assertThat(SafetyFactory.createDocumentBuilder(true)).isNotNull(); assertThat(SafetyFactory.createDocumentBuilder(false)).isNotNull(); } |
### Question:
Resources { static String toString(String path, Charset charset) throws IOException { try (InputStream input = Resources.class.getClassLoader().getResourceAsStream(path)) { if (input == null) { throw new IOException("Resource not found in the classpath: " + path); } ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; for (int read = input.read(buffer); read != -1; read = input.read(buffer)) { out.write(buffer, 0, read); } return new String(out.toByteArray(), charset); } } private Resources(); }### Answer:
@Test public void read_resource() throws Exception { assertThat(Resources.toString("org/sonarsource/analyzer/commons/ResourcesTest.txt", UTF_8)).isEqualTo("hello\n"); }
@Test(expected = IOException.class) public void read_invalid_resource() throws Exception { Resources.toString("invalid/path.txt", UTF_8); } |
### Question:
ExternalReportProvider { public static List<File> getReportFiles(SensorContext context, String externalReportsProperty) { boolean externalIssuesSupported = context.getSonarQubeVersion().isGreaterThanOrEqual(Version.create(7, 2)); String[] reportPaths = context.config().getStringArray(externalReportsProperty); if (reportPaths.length == 0) { return Collections.emptyList(); } if (!externalIssuesSupported) { LOG.error("Import of external issues requires SonarQube 7.2 or greater."); return Collections.emptyList(); } List<File> result = new ArrayList<>(); for (String reportPath : reportPaths) { File report = getIOFile(context.fileSystem().baseDir(), reportPath); result.add(report); } return result; } private ExternalReportProvider(); static List<File> getReportFiles(SensorContext context, String externalReportsProperty); }### Answer:
@Test public void test_return_empty_when_no_value() throws Exception { SensorContextTester context = SensorContextTester.create(new File(".")); List<File> reportFiles = ExternalReportProvider.getReportFiles(context, EXTERNAL_REPORTS_PROPERTY); assertThat(reportFiles).isEmpty(); assertThat(logTester.logs()).isEmpty(); }
@Test public void test_resolve_abs_and_relative() throws Exception { SensorContextTester context = SensorContextTester.create(new File("src/test/resources")); context.settings().setProperty(EXTERNAL_REPORTS_PROPERTY, "foo.out, " + new File("src/test/resources/bar.out").getAbsolutePath()); List<File> reportFiles = ExternalReportProvider.getReportFiles(context, EXTERNAL_REPORTS_PROPERTY); assertThat(reportFiles).hasSize(2); assertThat(reportFiles.get(0).getAbsolutePath()).isEqualTo(new File("src/test/resources/foo.out").getAbsolutePath()); assertThat(reportFiles.get(1).getAbsolutePath()).isEqualTo(new File("src/test/resources/bar.out").getAbsolutePath()); assertThat(logTester.logs()).isEmpty(); } |
### Question:
ContainsDetector extends Detector { @Override public int scan(String line) { String lineWithoutWhitespaces = StringUtils.deleteWhitespace(line); int matchers = 0; for (String str : strs) { matchers += StringUtils.countMatches(lineWithoutWhitespaces, str); } return matchers; } ContainsDetector(double probability, String... strs); @Override int scan(String line); }### Answer:
@Test public void scan() { ContainsDetector detector = new ContainsDetector(0.3, "++", "for("); assertThat(detector.scan("for (int i =0; i++; i<4) {")).isEqualTo(2); assertThat(detector.scan("String name;")).isZero(); } |
### Question:
EndWithDetector extends Detector { @Override public int scan(String line) { for (int index = line.length() - 1; index >= 0; index--) { char character = line.charAt(index); for (char endOfLine : endOfLines) { if (character == endOfLine) { return 1; } } if (!Character.isWhitespace(character) && character != '*' && character != '/') { return 0; } } return 0; } EndWithDetector(double probability, char... endOfLines); @Override int scan(String line); }### Answer:
@Test public void scan() { EndWithDetector detector = new EndWithDetector(0.3, '}'); assertThat(detector.scan(" return true; }")).isOne(); assertThat(detector.scan("} catch(NullPointerException e) {")).isZero(); assertThat(detector.scan("} ")).isOne(); assertThat(detector.scan("}*")).isOne(); assertThat(detector.scan("}/")).isOne(); assertThat(detector.scan("")).isZero(); } |
### Question:
CamelCaseDetector extends Detector { @Override public int scan(String line) { char previousChar = ' '; char indexChar; for (int i = 0; i < line.length(); i++) { indexChar = line.charAt(i); if (isLowerCaseThenUpperCase(previousChar, indexChar)) { return 1; } previousChar = indexChar; } return 0; } CamelCaseDetector(double probability); @Override int scan(String line); }### Answer:
@Test public void scan() { CamelCaseDetector detector = new CamelCaseDetector(0.3); assertThat(detector.scan("isDog() or isCat()")).isOne(); assertThat(detector.scan("String name;")).isZero(); } |
### Question:
XmlFile { @CheckForNull public static Node nodeAttribute(Node node, String attribute) { NamedNodeMap attributes = node.getAttributes(); if (attributes == null) { return null; } return attributes.getNamedItem(attribute); } private XmlFile(InputFile inputFile); private XmlFile(String str); static XmlFile create(InputFile inputFile); static XmlFile create(String str); @Nullable InputFile getInputFile(); String getContents(); Charset getCharset(); Document getDocument(); Document getNamespaceAwareDocument(); Document getNamespaceUnawareDocument(); Optional<PrologElement> getPrologElement(); static XmlTextRange startLocation(CDATASection node); static XmlTextRange endLocation(CDATASection node); static XmlTextRange startLocation(Element node); static XmlTextRange endLocation(Element node); static XmlTextRange nameLocation(Element node); static XmlTextRange attributeNameLocation(Attr node); static XmlTextRange attributeValueLocation(Attr node); static XmlTextRange nodeLocation(Node node); static Optional<XmlTextRange> getRange(Node node, Location location); static List<Node> children(Node node); static List<Node> asList(@Nullable NodeList nodeList); @CheckForNull static Node nodeAttribute(Node node, String attribute); }### Answer:
@Test public void testNodeAttribute() throws Exception { XmlFile xmlFile = XmlFile.create( "<a attr='foo'>\n" + " <!-- comment -->\n" + " <b>world</b>\n" + "</a>"); Node aNode = xmlFile.getDocument().getFirstChild(); assertThat(XmlFile.nodeAttribute(aNode, "attr")).isNotNull(); assertThat(XmlFile.nodeAttribute(aNode, "unknown")).isNull(); Node commentNode = aNode.getFirstChild(); assertThat(XmlFile.nodeAttribute(commentNode, "unknown")).isNull(); } |
### Question:
KeywordsDetector extends Detector { @Override public int scan(String line) { int matchers = 0; if (toUpperCase) { line = line.toUpperCase(Locale.getDefault()); } StringTokenizer tokenizer = new StringTokenizer(line, " \t(),{}"); while (tokenizer.hasMoreTokens()) { String word = tokenizer.nextToken(); if (keywords.contains(word)) { matchers++; } } return matchers; } KeywordsDetector(double probability, String... keywords); KeywordsDetector(double probability, boolean toUpperCase, String... keywords); @Override int scan(String line); }### Answer:
@Test public void scan() { KeywordsDetector detector = new KeywordsDetector(0.3, "public", "static"); assertThat(detector.scan("public static void main")).isEqualTo(2); assertThat(detector.scan("private(static} String name;")).isOne(); assertThat(detector.scan("publicstatic")).isZero(); assertThat(detector.scan("i++;")).isZero(); detector = new KeywordsDetector(0.3, true, "PUBLIC"); assertThat(detector.scan("Public static pubLIC")).isEqualTo(2); } |
### Question:
CodeRecognizer { public final boolean isLineOfCode(String line) { return recognition(line) - threshold > 0; } CodeRecognizer(double threshold, LanguageFootprint language); final double recognition(String line); final List<String> extractCodeLines(List<String> lines); final boolean isLineOfCode(String line); }### Answer:
@Test public void isLineOfCode() { CodeRecognizer cr = new CodeRecognizer(0.8, new FakeFootprint()); assertThat(cr.isLineOfCode("}")).isTrue(); assertThat(cr.isLineOfCode("squid")).isFalse(); } |
### Question:
CodeRecognizer { public final List<String> extractCodeLines(List<String> lines) { List<String> codeLines = new ArrayList<>(); for (String line : lines) { if (recognition(line) >= threshold) { codeLines.add(line); } } return codeLines; } CodeRecognizer(double threshold, LanguageFootprint language); final double recognition(String line); final List<String> extractCodeLines(List<String> lines); final boolean isLineOfCode(String line); }### Answer:
@Test public void extractCodeLines() { CodeRecognizer cr = new CodeRecognizer(0.8, new FakeFootprint()); assertThat(cr.extractCodeLines(Arrays.asList("{", "squid"))).containsOnly("{"); } |
### Question:
ProgressReport implements Runnable { public synchronized void cancel() { thread.interrupt(); join(); } ProgressReport(String threadName, long period, Logger logger, String adjective); ProgressReport(String threadName, long period, String adjective); ProgressReport(String threadName, long period); @Override void run(); synchronized void start(Iterable<String> filenames); synchronized void nextFile(); synchronized void stop(); synchronized void cancel(); }### Answer:
@Test(timeout = 5000) public void testCancel() throws InterruptedException { Logger logger = mock(Logger.class); ProgressReport report = new ProgressReport(ProgressReport.class.getName(), 100, logger, "analyzed"); report.start(Arrays.asList("foo.java")); waitForMessage(logger); report.cancel(); } |
### Question:
ProfileGenerator { public static File generateProfile(String serverUrl, String language, String repository, RulesConfiguration rulesConfiguration, Set<String> excludedRules) { try { Set<String> ruleKeys = getRuleKeys(serverUrl, language, repository); ruleKeys.removeAll(excludedRules); return generateProfile(language, repository, rulesConfiguration, ruleKeys); } catch (IOException | XMLStreamException e) { throw new RuntimeException(e); } } private ProfileGenerator(); static File generateProfile(String serverUrl, String language, String repository, RulesConfiguration rulesConfiguration, Set<String> excludedRules); }### Answer:
@Test public void test_generation_of_profile() throws Exception { ProfileGenerator.RulesConfiguration rulesConfiguration = new ProfileGenerator.RulesConfiguration() .add("S1451", "headerFormat", " .add("S1451", "isRegularExpression", "true") .add("S2762", "threshold", "1"); Set<String> rules = new HashSet<>(Arrays.asList("S1451", "S2762", "S101")); File profile = ProfileGenerator.generateProfile("js", "javascript", rulesConfiguration, rules); String profileAsString = Files.readAllLines(profile.toPath()).stream().collect(Collectors.joining()); assertThat(profileAsString).isEqualTo("<?xml version=\"1.0\" encoding=\"UTF-8\"?><profile><name>rules</name><language>js</language><rules>" + "<rule><repositoryKey>javascript</repositoryKey><key>S101</key><priority>INFO</priority></rule>" + "<rule><repositoryKey>javascript</repositoryKey><key>S1451</key><priority>INFO</priority>" + "<parameters><parameter><key>headerFormat</key><value> "<parameter><key>isRegularExpression</key><value>true</value></parameter></parameters></rule>" + "<rule><repositoryKey>javascript</repositoryKey><key>S2762</key><priority>INFO</priority><parameters><parameter><key>threshold</key><value>1</value></parameter></parameters></rule>" + "</rules></profile>"); }
@Test public void test_connection() throws Exception { ProfileGenerator.RulesConfiguration rulesConfiguration = new ProfileGenerator.RulesConfiguration(); ServerSocket mockServer = new ServerSocket(0); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.submit(() -> { Socket socket = mockServer.accept(); InputStream inputStream = socket.getInputStream(); String request = new BufferedReader(new InputStreamReader(inputStream)).readLine(); assertThat(request).contains("p=1&ps=500&languages=js&repositories=javascript"); OutputStream out = socket.getOutputStream(); String content = "{\"total\":1,\"p\":1,\"ps\":500,\"rules\":[{\"key\":\"javascript:S3798\"}]}"; String response = "HTTP/1.1 200 OK\n" + "Content-Length: " + content.length() + "\n" + "Content-Type: text/html\n\n" + content; out.write(response.getBytes(StandardCharsets.UTF_8)); out.close(); socket.close(); return null; }); File file = ProfileGenerator.generateProfile("http: String response = Files.readAllLines(file.toPath()).stream().collect(Collectors.joining()); assertThat(response).contains("S3798"); mockServer.close(); } |
### Question:
JsonParser { Map<String, Object> parse(String data) { try { return (Map<String, Object>) parser.parse(data); } catch (ParseException e) { throw new IllegalArgumentException("Could not parse JSON", e); } } }### Answer:
@Test public void parse() throws Exception { JsonParser parser = new JsonParser(); Map<String, Object> map = parser.parse("{ \"name\" : \"Paul\" }"); Object name = map.get("name"); assertThat(name).isEqualTo("Paul"); }
@Test(expected = IllegalArgumentException.class) public void invalid_json() { new JsonParser().parse("{{}"); } |
### Question:
ReflectionResource { @POST public Reflection createReflection(Reflection reflection) { ReflectionGoal newReflection = reflectionServiceHelper.createReflection(reflection.toReflectionGoal()); String id = newReflection.getId().getId(); return new Reflection(newReflection, reflectionServiceHelper.getStatusForReflection(id), reflectionServiceHelper.getCurrentSize(id), reflectionServiceHelper.getTotalSize(id)); } @Inject ReflectionResource(ReflectionServiceHelper reflectionServiceHelper, CatalogServiceHelper catalogServiceHelper); @GET @Path("/{id}") Reflection getReflection(@PathParam("id") String id); @POST Reflection createReflection(Reflection reflection); @PUT @Path("/{id}") Reflection editReflection(@PathParam("id") String id, Reflection reflection); @DELETE @Path("/{id}") Response deleteReflection(@PathParam("id") String id); }### Answer:
@Test public void testUpdateReflection() { Reflection newReflection = createReflection(); Reflection response = expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH)).buildPost(Entity.entity(newReflection, JSON)), Reflection.class); String betterName = "much better name"; response.setName(betterName); Reflection response2 = expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH).path(response.getId())).buildPut(Entity.entity(response, JSON)), Reflection.class); assertEquals(response2.getId(), response.getId()); assertEquals(response2.getName(), betterName); assertEquals(response2.getType(), response.getType()); assertEquals(response2.getCreatedAt(), response.getCreatedAt()); assertTrue(response2.getUpdatedAt() > response.getUpdatedAt()); assertNotEquals(response2.getTag(), response.getTag()); assertEquals(response2.getDisplayFields(), response.getDisplayFields()); assertEquals(response2.getDimensionFields(), response.getDimensionFields()); assertEquals(response2.getDistributionFields(), response.getDistributionFields()); assertEquals(response2.getMeasureFields(), response.getMeasureFields()); assertEquals(response2.getPartitionFields(), response.getPartitionFields()); assertEquals(response2.getSortFields(), response.getSortFields()); assertEquals(response2.getPartitionDistributionStrategy(), response.getPartitionDistributionStrategy()); newReflectionServiceHelper().removeReflection(response2.getId()); }
@Test public void testBoostToggleOnRawReflection() { Reflection newReflection = createReflection(); Reflection response = expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH)).buildPost(Entity.entity(newReflection, JSON)), Reflection.class); assertFalse(response.isArrowCachingEnabled()); response.setArrowCachingEnabled(true); response = expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH).path(response.getId())).buildPut(Entity.entity(response, JSON)), Reflection.class); assertTrue(response.isArrowCachingEnabled()); }
@Test public void testCreateReflection() { Reflection newReflection = createReflection(); Reflection response = expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH)).buildPost(Entity.entity(newReflection, JSON)), Reflection.class); assertEquals(response.getDatasetId(), newReflection.getDatasetId()); assertEquals(response.getName(), newReflection.getName()); assertEquals(response.getType(), newReflection.getType()); assertEquals(response.isEnabled(), newReflection.isEnabled()); assertNotNull(response.getCreatedAt()); assertNotNull(response.getUpdatedAt()); assertNotNull(response.getStatus()); assertNotNull(response.getTag()); assertNotNull(response.getId()); assertEquals(response.getDisplayFields(), newReflection.getDisplayFields()); assertNull(response.getDimensionFields()); assertNull(response.getDistributionFields()); assertNull(response.getMeasureFields()); assertNull(response.getPartitionFields()); assertNull(response.getSortFields()); assertEquals(response.getPartitionDistributionStrategy(), newReflection.getPartitionDistributionStrategy()); newReflectionServiceHelper().removeReflection(response.getId()); } |
### Question:
ReflectionResource { @DELETE @Path("/{id}") public Response deleteReflection(@PathParam("id") String id) { reflectionServiceHelper.removeReflection(id); return Response.ok().build(); } @Inject ReflectionResource(ReflectionServiceHelper reflectionServiceHelper, CatalogServiceHelper catalogServiceHelper); @GET @Path("/{id}") Reflection getReflection(@PathParam("id") String id); @POST Reflection createReflection(Reflection reflection); @PUT @Path("/{id}") Reflection editReflection(@PathParam("id") String id, Reflection reflection); @DELETE @Path("/{id}") Response deleteReflection(@PathParam("id") String id); }### Answer:
@Test public void testDeleteReflection() { Reflection newReflection = createReflection(); Reflection response = expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH)).buildPost(Entity.entity(newReflection, JSON)), Reflection.class); expectSuccess(getBuilder(getPublicAPI(3).path(REFLECTIONS_PATH).path(response.getId())).buildDelete()); assertFalse(newReflectionServiceHelper().getReflectionById(response.getId()).isPresent()); } |
### Question:
SourceResource { @GET @RolesAllowed({"admin", "user"}) public ResponseList<Source> getSources() { final ResponseList<Source> sources = new ResponseList<>(); final List<SourceConfig> sourceConfigs = sourceService.getSources(); for (SourceConfig sourceConfig : sourceConfigs) { Source source = fromSourceConfig(sourceConfig); sources.add(source); } return sources; } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); @GET @RolesAllowed({"admin", "user"}) ResponseList<Source> getSources(); @POST @RolesAllowed({"admin"}) SourceDeprecated addSource(SourceDeprecated source); @GET @RolesAllowed({"admin", "user"}) @Path("/{id}") SourceDeprecated getSource(@PathParam("id") String id); @PUT @RolesAllowed({"admin"}) @Path("/{id}") SourceDeprecated updateSource(@PathParam("id") String id, SourceDeprecated source); @DELETE @RolesAllowed("admin") @Path("/{id}") Response deleteSource(@PathParam("id") String id); @GET @RolesAllowed("admin") @Path("/type") ResponseList<SourceTypeTemplate> getSourceTypes(); @GET @RolesAllowed("admin") @Path("/type/{name}") SourceTypeTemplate getSourceByType(@PathParam("name") String name); }### Answer:
@Test public void testListSources() throws Exception { ResponseList<SourceResource.SourceDeprecated> sources = expectSuccess(getBuilder(getPublicAPI(3).path(SOURCES_PATH)).buildGet(), new GenericType<ResponseList<SourceResource.SourceDeprecated>>() {}); assertEquals(sources.getData().size(), newSourceService().getSources().size()); } |
### Question:
SourceResource { @POST @RolesAllowed({"admin"}) public SourceDeprecated addSource(SourceDeprecated source) { try { SourceConfig newSourceConfig = sourceService.createSource(source.toSourceConfig()); return fromSourceConfig(newSourceConfig); } catch (NamespaceException | ExecutionSetupException e) { throw new ServerErrorException(e); } } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); @GET @RolesAllowed({"admin", "user"}) ResponseList<Source> getSources(); @POST @RolesAllowed({"admin"}) SourceDeprecated addSource(SourceDeprecated source); @GET @RolesAllowed({"admin", "user"}) @Path("/{id}") SourceDeprecated getSource(@PathParam("id") String id); @PUT @RolesAllowed({"admin"}) @Path("/{id}") SourceDeprecated updateSource(@PathParam("id") String id, SourceDeprecated source); @DELETE @RolesAllowed("admin") @Path("/{id}") Response deleteSource(@PathParam("id") String id); @GET @RolesAllowed("admin") @Path("/type") ResponseList<SourceTypeTemplate> getSourceTypes(); @GET @RolesAllowed("admin") @Path("/type/{name}") SourceTypeTemplate getSourceByType(@PathParam("name") String name); }### Answer:
@Test public void testAddSource() throws Exception { SourceResource.SourceDeprecated newSource = new SourceResource.SourceDeprecated(); newSource.setName("Foopy"); newSource.setType("NAS"); NASConf config = new NASConf(); config.path = "/"; newSource.setConfig(config); SourceResource.SourceDeprecated source = expectSuccess(getBuilder(getPublicAPI(3).path(SOURCES_PATH)).buildPost(Entity.entity(newSource, JSON)), SourceResource.SourceDeprecated.class); assertEquals(source.getName(), newSource.getName()); assertNotNull(source.getState()); deleteSource(source.getName()); } |
### Question:
SourceResource { @PUT @RolesAllowed({"admin"}) @Path("/{id}") public SourceDeprecated updateSource(@PathParam("id") String id, SourceDeprecated source) { SourceConfig sourceConfig; try { sourceConfig = sourceService.updateSource(id, source.toSourceConfig()); return fromSourceConfig(sourceConfig); } catch (NamespaceException | ExecutionSetupException e) { throw new ServerErrorException(e); } } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); @GET @RolesAllowed({"admin", "user"}) ResponseList<Source> getSources(); @POST @RolesAllowed({"admin"}) SourceDeprecated addSource(SourceDeprecated source); @GET @RolesAllowed({"admin", "user"}) @Path("/{id}") SourceDeprecated getSource(@PathParam("id") String id); @PUT @RolesAllowed({"admin"}) @Path("/{id}") SourceDeprecated updateSource(@PathParam("id") String id, SourceDeprecated source); @DELETE @RolesAllowed("admin") @Path("/{id}") Response deleteSource(@PathParam("id") String id); @GET @RolesAllowed("admin") @Path("/type") ResponseList<SourceTypeTemplate> getSourceTypes(); @GET @RolesAllowed("admin") @Path("/type/{name}") SourceTypeTemplate getSourceByType(@PathParam("name") String name); }### Answer:
@Test public void testUpdateSource() throws Exception { SourceConfig sourceConfig = new SourceConfig(); sourceConfig.setName("Foopy2"); NASConf nasConfig = new NASConf(); sourceConfig.setType(nasConfig.getType()); nasConfig.path = "/"; sourceConfig.setConfig(nasConfig.toBytesString()); SourceConfig createdSourceConfig = newSourceService().registerSourceWithRuntime(sourceConfig); final AccelerationSettings settings = new AccelerationSettings() .setMethod(RefreshMethod.FULL) .setRefreshPeriod(TimeUnit.HOURS.toMillis(2)) .setGracePeriod(TimeUnit.HOURS.toMillis(6)); SourceResource.SourceDeprecated updatedSource = new SourceResource.SourceDeprecated(createdSourceConfig, settings, reader, null); updatedSource.setDescription("Desc"); SourceResource.SourceDeprecated source = expectSuccess(getBuilder(getPublicAPI(3).path(SOURCES_PATH).path(createdSourceConfig.getId().getId())).buildPut(Entity.entity(updatedSource, JSON)), SourceResource.SourceDeprecated.class); assertEquals("Desc", source.getDescription()); assertNotNull(source.getState()); assertNotNull(source.getTag()); deleteSource(source.getName()); } |
### Question:
SourceResource { @GET @RolesAllowed({"admin", "user"}) @Path("/{id}") public SourceDeprecated getSource(@PathParam("id") String id) throws NamespaceException { SourceConfig sourceConfig = sourceService.getById(id); return fromSourceConfig(sourceConfig); } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); @GET @RolesAllowed({"admin", "user"}) ResponseList<Source> getSources(); @POST @RolesAllowed({"admin"}) SourceDeprecated addSource(SourceDeprecated source); @GET @RolesAllowed({"admin", "user"}) @Path("/{id}") SourceDeprecated getSource(@PathParam("id") String id); @PUT @RolesAllowed({"admin"}) @Path("/{id}") SourceDeprecated updateSource(@PathParam("id") String id, SourceDeprecated source); @DELETE @RolesAllowed("admin") @Path("/{id}") Response deleteSource(@PathParam("id") String id); @GET @RolesAllowed("admin") @Path("/type") ResponseList<SourceTypeTemplate> getSourceTypes(); @GET @RolesAllowed("admin") @Path("/type/{name}") SourceTypeTemplate getSourceByType(@PathParam("name") String name); }### Answer:
@Test public void testGetSource() throws Exception { SourceConfig sourceConfig = new SourceConfig(); sourceConfig.setName("Foopy4"); NASConf nasConfig = new NASConf(); sourceConfig.setType(nasConfig.getType()); nasConfig.path = "/"; sourceConfig.setConfig(nasConfig.toBytesString()); SourceConfig createdSourceConfig = newSourceService().registerSourceWithRuntime(sourceConfig); SourceResource.SourceDeprecated source = expectSuccess(getBuilder(getPublicAPI(3).path(SOURCES_PATH).path(createdSourceConfig.getId().getId())).buildGet(), SourceResource.SourceDeprecated.class); assertEquals(source.getName(), sourceConfig.getName()); assertNotNull(source.getState()); } |
### Question:
SetTableauDefaults extends UpgradeTask { @VisibleForTesting static boolean updateOptionsIfNeeded(Version previousVersion, Supplier<SystemOptionManager> optionManagerSupplier, boolean isOptionManagerOpen) throws Exception { if (Upgrade.UPGRADE_VERSION_ORDERING.compare(previousVersion, VERSION_460) >= 0) { return false; } final SystemOptionManager optionManager = optionManagerSupplier.get(); try { if (!isOptionManagerOpen) { optionManager.start(); } final OptionValue regularTableauDefault = TableauResource.CLIENT_TOOLS_TABLEAU.getDefault(); final OptionValue tableauEnable = OptionValue.createBoolean(regularTableauDefault.getType(), regularTableauDefault.getName(), true); if (!optionManager.isSet(TableauResource.CLIENT_TOOLS_TABLEAU.getOptionName())) { optionManager.setOption(tableauEnable); return true; } return false; } finally { if (!isOptionManagerOpen) { optionManager.close(); } } } SetTableauDefaults(); @Override String getTaskUUID(); @Override void upgrade(UpgradeContext context); }### Answer:
@Test public void testPost460Version() throws Exception { final Version version = new Version("4.6.1", 4, 6, 1, 0, ""); assertFalse(SetTableauDefaults.updateOptionsIfNeeded(version, () -> optionManager, true)); }
@Test public void testPost4x0Version() throws Exception { final Version version = new Version("5.2.0", 5, 2, 0, 0, ""); assertFalse(SetTableauDefaults.updateOptionsIfNeeded(version, () -> optionManager, true)); }
@Test public void testPre460VersionAndKeyExists() throws Exception { final Version version = new Version("5.1.0", 5, 2, 0, 0, ""); assertFalse(SetTableauDefaults.updateOptionsIfNeeded(version, () -> optionManager, true)); assertFalse(optionManager.isSet(TableauResource.CLIENT_TOOLS_TABLEAU.getOptionName())); }
@Test public void testPre4x0Version() throws Exception { final Version version = new Version("3.9.0", 3, 9, 0, 0, ""); assertTrue(SetTableauDefaults.updateOptionsIfNeeded(version, () -> optionManager, true)); assertTrue(optionManager.getOption(TableauResource.CLIENT_TOOLS_TABLEAU)); }
@Test public void testPre460Version() throws Exception { final Version version = new Version("4.5.9", 4, 5, 9, 0, ""); assertTrue(SetTableauDefaults.updateOptionsIfNeeded(version, () -> optionManager, true)); assertTrue(optionManager.getOption(TableauResource.CLIENT_TOOLS_TABLEAU)); }
@Test public void test460Version() throws Exception { final Version version = new Version("4.6.0", 4, 6, 0, 0, ""); assertFalse(SetTableauDefaults.updateOptionsIfNeeded(version, () -> optionManager, true)); } |
### Question:
SourceResource { @VisibleForTesting protected SourceDeprecated fromSourceConfig(SourceConfig sourceConfig) { return new SourceDeprecated(sourceService.fromSourceConfig(sourceConfig)); } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); @GET @RolesAllowed({"admin", "user"}) ResponseList<Source> getSources(); @POST @RolesAllowed({"admin"}) SourceDeprecated addSource(SourceDeprecated source); @GET @RolesAllowed({"admin", "user"}) @Path("/{id}") SourceDeprecated getSource(@PathParam("id") String id); @PUT @RolesAllowed({"admin"}) @Path("/{id}") SourceDeprecated updateSource(@PathParam("id") String id, SourceDeprecated source); @DELETE @RolesAllowed("admin") @Path("/{id}") Response deleteSource(@PathParam("id") String id); @GET @RolesAllowed("admin") @Path("/type") ResponseList<SourceTypeTemplate> getSourceTypes(); @GET @RolesAllowed("admin") @Path("/type/{name}") SourceTypeTemplate getSourceByType(@PathParam("name") String name); }### Answer:
@Test public void testRemovingSensitiveFields() throws Exception { SourceConfig config = new SourceConfig(); config.setName("Foopy"); config.setId(new EntityId("id")); config.setTag("0"); config.setAccelerationGracePeriod(0L); config.setAccelerationRefreshPeriod(0L); APrivateSource priv = new APrivateSource(); priv.password = "hello"; config.setConnectionConf(priv); SourceResource sourceResource = new SourceResource(newSourceService(), null); SourceResource.SourceDeprecated source = sourceResource.fromSourceConfig(config); APrivateSource newConfig = (APrivateSource) source.getConfig(); assertEquals(newConfig.password, ConnectionConf.USE_EXISTING_SECRET_VALUE); } |
### Question:
JobResource extends BaseResourceWithAllocator { @POST @Path("/{id}/cancel") public void cancelJob(@PathParam("id") String id) throws JobException { final String username = securityContext.getUserPrincipal().getName(); try { jobs.cancel(CancelJobRequest.newBuilder() .setUsername(username) .setJobId(JobsProtoUtil.toBuf(new JobId(id))) .setReason(String.format("Query cancelled by user '%s'", username)) .build()); } catch (JobNotFoundException e) { throw new NotFoundException(String.format("Could not find a job with id [%s]", id)); } } @Inject JobResource(JobsService jobs, SecurityContext securityContext, BufferAllocatorFactory allocatorFactory); @GET @Path("/{id}") JobStatus getJobStatus(@PathParam("id") String id); @GET @Path("/{id}/results") JobResourceData getQueryResults(@PathParam("id") String id, @QueryParam("offset") @DefaultValue("0") Integer offset, @Valid @QueryParam("limit") @DefaultValue("100") Integer limit); @POST @Path("/{id}/cancel") void cancelJob(@PathParam("id") String id); @GET @Path("/{id}/reflection/{reflectionId}") JobStatus getReflectionJobStatus(@PathParam("id") String id,
@PathParam("reflectionId") String reflectionId); @POST @Path("/{id}/reflection/{reflectionId}/cancel") void cancelReflectionJob(@PathParam("id") String id,
@PathParam("reflectionId") String reflectionId); }### Answer:
@Test public void testCancelJob() throws InterruptedException { JobsService jobs = l(JobsService.class); SqlQuery query = new SqlQuery("select * from sys.version", Collections.emptyList(), SystemUser.SYSTEM_USERNAME); final String id = submitAndWaitUntilSubmitted( JobRequest.newBuilder() .setSqlQuery(query) .setQueryType(QueryType.REST) .build() ).getId(); expectSuccess(getBuilder(getPublicAPI(3).path(JOB_PATH).path(id).path("cancel")).buildPost(null)); String cancelReason = "Query cancelled by user 'dremio'"; while (true) { JobStatus status = expectSuccess(getBuilder(getPublicAPI(3).path(JOB_PATH).path(id)).buildGet(), JobStatus.class); JobState jobState = status.getJobState(); Assert.assertTrue("expected job to cancel successfully", Arrays .asList(JobState.PLANNING, JobState.RUNNING, JobState.STARTING, JobState.CANCELED, JobState.PENDING, JobState.METADATA_RETRIEVAL, JobState.QUEUED, JobState.ENGINE_START, JobState.EXECUTION_PLANNING, JobState.FAILED) .contains(jobState)); if (jobState == JobState.CANCELED) { expectStatus(Response.Status.BAD_REQUEST, getBuilder(getPublicAPI(3).path(JOB_PATH).path(id).path("results").queryParam("limit", 1000)).buildGet()); assertEquals(cancelReason, status.getCancellationReason()); break; } else if (jobState == JobState.COMPLETED) { break; } else if (jobState == JobState.FAILED) { assertEquals(cancelReason, status.getErrorMessage()); break; } else { Thread.sleep(TimeUnit.MILLISECONDS.toMillis(100)); } } } |
### Question:
ClusterStatsResource { @VisibleForTesting public static Stats getSources(List<SourceConfig> allSources, SabotContext context){ final Stats resource = new Stats(); for (SourceConfig sourceConfig : allSources) { int pdsCount = -1; String type = sourceConfig.getType(); if(type == null && sourceConfig.getLegacySourceTypeEnum() != null) { type = sourceConfig.getLegacySourceTypeEnum().name(); } if("S3".equals(type) && sourceConfig.getName().startsWith("Samples")) { type = "SamplesS3"; } SourceStats source = new SourceStats(sourceConfig.getId(), type, pdsCount); resource.addVdsQuery(SearchQueryUtils.newTermQuery(DATASET_SOURCES, sourceConfig.getName())); resource.addSource(source); } return resource; } @Inject ClusterStatsResource(
Provider<SabotContext> context,
SourceService sourceService,
NamespaceService namespaceService,
JobsService jobsService,
ReflectionServiceHelper reflectionServiceHelper,
EditionProvider editionProvider
); @GET @RolesAllowed({"admin", "user"}) ClusterStats getStats(@DefaultValue("false") @QueryParam("showCompactStats") final boolean showCompactStats); @VisibleForTesting static Stats getSources(List<SourceConfig> allSources, SabotContext context); }### Answer:
@Test public void testListSources() throws Exception { ClusterStatsResource.ClusterStats stats = expectSuccess(getBuilder(getPublicAPI(3).path(PATH)).buildGet(), ClusterStatsResource.ClusterStats.class); assertNotNull(stats); assertEquals(stats.getSources().size(), newSourceService().getSources().size()); }
@Test public void testSamplesS3() throws Exception{ List<SourceConfig> sources = new ArrayList(); SourceConfig configS3Samples = new SourceConfig(); configS3Samples.setMetadataPolicy(DEFAULT_METADATA_POLICY_WITH_AUTO_PROMOTE); configS3Samples.setName("Samples"); configS3Samples.setType("S3"); SourceConfig configS3 = new SourceConfig(); configS3.setMetadataPolicy(DEFAULT_METADATA_POLICY_WITH_AUTO_PROMOTE); configS3.setName("SourceS3"); configS3.setType("S3"); sources.add(configS3Samples); sources.add(configS3); ClusterStatsResource.Stats result = ClusterStatsResource.getSources(sources,getSabotContext()); assertTrue("Type is incorrect", "SamplesS3".equals(result.getAllSources().get(0).getType())); assertTrue("Type is incorrect", "S3".equals(result.getAllSources().get(1).getType())); } |
### Question:
CatalogResource { @GET public ResponseList<? extends CatalogItem> listTopLevelCatalog(@QueryParam("include") final List<String> include) { return new ResponseList<>(catalogServiceHelper.getTopLevelCatalogItems(include)); } @Inject CatalogResource(CatalogServiceHelper catalogServiceHelper); @GET ResponseList<? extends CatalogItem> listTopLevelCatalog(@QueryParam("include") final List<String> include); @GET @Path("/{id}") CatalogEntity getCatalogItem(@PathParam("id") String id,
@QueryParam("include") final List<String> include); @POST CatalogEntity createCatalogItem(CatalogEntity entity); @POST @Path("/{id}") Dataset promoteToDataset(Dataset dataset, @PathParam("id") String id); @PUT @Path("/{id}") CatalogEntity updateCatalogItem(CatalogEntity entity, @PathParam("id") String id); @DELETE @Path("/{id}") void deleteCatalogItem(@PathParam("id") String id, @QueryParam("tag") String tag); @POST @Path("/{id}/refresh") void refreshCatalogItem(@PathParam("id") String id); @POST @Path("/{id}/metadata/refresh") MetadataRefreshResponse refreshCatalogItemMetadata(@PathParam("id") String id,
@QueryParam("deleteWhenMissing") Boolean delete,
@QueryParam("forceUpdate") Boolean force,
@QueryParam("autoPromotion") Boolean promotion); @GET @Path("/by-path/{segment:.*}") CatalogEntity getCatalogItemByPath(@PathParam("segment") List<PathSegment> segments); @GET @Path("/search") ResponseList<CatalogItem> search(@QueryParam("query") String query); }### Answer:
@Test public void testListTopLevelCatalog() throws Exception { int topLevelCount = newSourceService().getSources().size() + newNamespaceService().getSpaces().size() + 1; ResponseList<CatalogItem> items = getRootEntities(null); assertEquals(items.getData().size(), topLevelCount); int homeCount = 0; int spaceCount = 0; int sourceCount = 0; for (CatalogItem item : items.getData()) { if (item.getType() == CatalogItem.CatalogItemType.CONTAINER) { if (item.getContainerType() == CatalogItem.ContainerSubType.HOME) { homeCount++; } if (item.getContainerType() == CatalogItem.ContainerSubType.SPACE) { spaceCount++; } if (item.getContainerType() == CatalogItem.ContainerSubType.SOURCE) { sourceCount++; } } } assertEquals(homeCount, 1); assertEquals(spaceCount, newNamespaceService().getSpaces().size()); assertEquals(sourceCount, 1); } |
### Question:
UserResource { @GET @Path("/{id}") public User getUser(@PathParam("id") String id) throws UserNotFoundException { return User.fromUser(userGroupService.getUser(new UID(id))); } @Inject UserResource(UserService userGroupService,
NamespaceService namespaceService,
@Context SecurityContext securityContext); @GET @Path("/{id}") User getUser(@PathParam("id") String id); @RolesAllowed({"admin"}) @POST User createUser(User user); static com.dremio.service.users.User addUser(com.dremio.service.users.User newUser, String password, UserService userService,
NamespaceService namespaceService); @RolesAllowed({"admin", "user"}) @PUT @Path("/{id}") User updateUser(User user, @PathParam("id") String id); @GET @Path("/by-name/{name}") User getUserByName(@PathParam("name") String name); }### Answer:
@Test public void testGetUserById() throws Exception { final UserService userService = l(UserService.class); com.dremio.service.users.User user1 = userService.getUser("user1"); User user = expectSuccess(getBuilder(getPublicAPI(3).path(USER_PATH).path(user1.getUID().getId())).buildGet(), User.class); assertEquals(user.getId(), user1.getUID().getId()); assertEquals(user.getName(), user1.getUserName()); }
@Test public void testGetUserDetails() throws Exception { final UserService userService = l(UserService.class); com.dremio.service.users.User user1 = userService.getUser("user1"); User user = expectSuccess(getBuilder(getPublicAPI(3).path(USER_PATH).path(user1.getUID().getId())) .buildGet(), User.class); assertEquals(user.getId(), user1.getUID().getId()); assertEquals(user.getName(), user1.getUserName()); assertEquals(user.getFirstName(), user1.getFirstName()); assertEquals(user.getLastName(), user1.getLastName()); assertEquals(user.getEmail(), user1.getEmail()); assertEquals(user.getTag(), user1.getVersion()); assertNull("Password should not be sent to a data consumer", user.getPassword()); } |
### Question:
UserResource { @RolesAllowed({"admin"}) @POST public User createUser(User user) throws IOException { final com.dremio.service.users.User userConfig = UserResource.addUser(of(user, Optional.empty()), user.getPassword(), userGroupService, namespaceService); return User.fromUser(userConfig); } @Inject UserResource(UserService userGroupService,
NamespaceService namespaceService,
@Context SecurityContext securityContext); @GET @Path("/{id}") User getUser(@PathParam("id") String id); @RolesAllowed({"admin"}) @POST User createUser(User user); static com.dremio.service.users.User addUser(com.dremio.service.users.User newUser, String password, UserService userService,
NamespaceService namespaceService); @RolesAllowed({"admin", "user"}) @PUT @Path("/{id}") User updateUser(User user, @PathParam("id") String id); @GET @Path("/by-name/{name}") User getUserByName(@PathParam("name") String name); }### Answer:
@Test public void testCreateUser() throws Exception { UserInfoRequest userInfo = new UserInfoRequest(null, "test_new_user", "test", "new user", "[email protected]", "0", "123some_password", null); User savedUser = expectSuccess(getBuilder(getPublicAPI(3).path(USER_PATH)) .buildPost(Entity.json(userInfo)), User.class); assertNotNull(savedUser.getId()); assertEquals(savedUser.getName(), userInfo.getName()); assertEquals(savedUser.getFirstName(), userInfo.getFirstName()); assertEquals(savedUser.getLastName(), userInfo.getLastName()); assertEquals(savedUser.getEmail(), userInfo.getEmail()); assertNull("Password should not be sent to a data consumer", savedUser.getPassword()); assertNotNull(savedUser.getTag()); final UserService userService = l(UserService.class); userService.deleteUser(savedUser.getName(), savedUser.getTag()); } |
### Question:
UserResource { @RolesAllowed({"admin", "user"}) @PUT @Path("/{id}") public User updateUser(User user, @PathParam("id") String id) throws UserNotFoundException, IOException, DACUnauthorizedException { if (Strings.isNullOrEmpty(id)) { throw new IllegalArgumentException("No user id provided"); } final com.dremio.service.users.User savedUser = userGroupService.getUser(new UID(id)); if (!securityContext.isUserInRole("admin") && !securityContext.getUserPrincipal().getName().equals(savedUser.getUserName())) { throw new DACUnauthorizedException(format("User %s is not allowed to update user %s", securityContext.getUserPrincipal().getName(), savedUser.getUserName())); } if (!savedUser.getUserName().equals(user.getName())) { throw new NotSupportedException("Changing of user name is not supported"); } final com.dremio.service.users.User userConfig = userGroupService.updateUser(of(user, Optional.of(id)), user.getPassword()); return User.fromUser(userConfig); } @Inject UserResource(UserService userGroupService,
NamespaceService namespaceService,
@Context SecurityContext securityContext); @GET @Path("/{id}") User getUser(@PathParam("id") String id); @RolesAllowed({"admin"}) @POST User createUser(User user); static com.dremio.service.users.User addUser(com.dremio.service.users.User newUser, String password, UserService userService,
NamespaceService namespaceService); @RolesAllowed({"admin", "user"}) @PUT @Path("/{id}") User updateUser(User user, @PathParam("id") String id); @GET @Path("/by-name/{name}") User getUserByName(@PathParam("name") String name); }### Answer:
@Test public void testUpdateUser() { UserInfoRequest userInfo = new UserInfoRequest(createdUser.getUID().getId(), createdUser.getUserName(), "a new firstName", " a new last name", "[email protected]", createdUser.getVersion(), null, null); User savedUser = expectSuccess(getBuilder(getPublicAPI(3).path(USER_PATH).path(createdUser.getUID().getId())) .buildPut(Entity.json(userInfo)), User.class); assertEquals(createdUser.getUID().getId(), savedUser.getId()); assertEquals(savedUser.getName(), userInfo.getName()); assertEquals(savedUser.getFirstName(), userInfo.getFirstName()); assertEquals(savedUser.getLastName(), userInfo.getLastName()); assertEquals(savedUser.getEmail(), userInfo.getEmail()); assertNotEquals("version should be changed", savedUser.getTag(), userInfo.getTag()); assertNull("Password should not be sent to a data consumer", savedUser.getPassword()); createdUser = SimpleUser.newBuilder() .setUID(new UID(savedUser.getId())) .setUserName(savedUser.getName()) .setVersion(savedUser.getTag()).build(); } |
### Question:
UserResource { @GET @Path("/by-name/{name}") public User getUserByName(@PathParam("name") String name) throws UserNotFoundException { return User.fromUser(userGroupService.getUser(name)); } @Inject UserResource(UserService userGroupService,
NamespaceService namespaceService,
@Context SecurityContext securityContext); @GET @Path("/{id}") User getUser(@PathParam("id") String id); @RolesAllowed({"admin"}) @POST User createUser(User user); static com.dremio.service.users.User addUser(com.dremio.service.users.User newUser, String password, UserService userService,
NamespaceService namespaceService); @RolesAllowed({"admin", "user"}) @PUT @Path("/{id}") User updateUser(User user, @PathParam("id") String id); @GET @Path("/by-name/{name}") User getUserByName(@PathParam("name") String name); }### Answer:
@Test public void testGetUserByName() throws Exception { final UserService userService = l(UserService.class); User user = expectSuccess(getBuilder(getPublicAPI(3).path(USER_PATH).path("by-name").path(createdUser.getUserName())).buildGet(), User.class); assertEquals(user.getId(), createdUser.getUID().getId()); assertEquals(user.getName(), createdUser.getUserName()); } |
### Question:
UserStats { public String getEdition() { return edition; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); }### Answer:
@Test public void testGetEdition() { UserStats.Builder stats = new UserStats.Builder(); stats.setEdition("oss"); String expected = "dremio-oss-" + DremioVersionInfo.getVersion(); assertEquals(expected, stats.build().getEdition()); } |
### Question:
UserStats { public List<Map<String, Object>> getUserStatsByDate() { return userStatsByDate; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); }### Answer:
@Test public void testGetStatsByDate() { UserStats.Builder statsBuilder = new UserStats.Builder(); LocalDate now = LocalDate.now(); statsBuilder.addUserStat(toEpochMillis(now.minusDays(11)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusDays(9)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusDays(9)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusDays(9)), "ODBC", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusDays(9)), "ODBC", "testuser2"); statsBuilder.addUserStat(toEpochMillis(now), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "ODBC", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "ODBC", "testuser2"); UserStats stats = statsBuilder.build(); List<Map<String, Object>> statsByDate = stats.getUserStatsByDate(); assertEquals(2, statsByDate.size()); Map<String, Object> firstDateEntry = fetchDateEntry("date", now.minusDays(9).toString(), statsByDate); assertEquals(1, firstDateEntry.get("UI")); assertEquals(2, firstDateEntry.get("ODBC")); assertEquals(2, firstDateEntry.get("total")); Map<String, Object> secondDateEntry = fetchDateEntry("date", now.toString(), statsByDate); assertEquals(1, secondDateEntry.get("UI")); assertEquals(2, secondDateEntry.get("ODBC")); assertEquals(2, secondDateEntry.get("total")); } |
### Question:
UserStats { public List<Map<String, Object>> getUserStatsByWeek() { return userStatsByWeek; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); }### Answer:
@Test public void testGetStatsByWeek() { UserStats.Builder statsBuilder = new UserStats.Builder(); LocalDate now = LocalDate.now(); statsBuilder.addUserStat(toEpochMillis(now.minusWeeks(3)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusWeeks(1)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusWeeks(1)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusWeeks(1)), "ODBC", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusWeeks(1)), "ODBC", "testuser2"); statsBuilder.addUserStat(toEpochMillis(now), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "ODBC", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "ODBC", "testuser2"); UserStats stats = statsBuilder.build(); List<Map<String, Object>> statsByDate = stats.getUserStatsByWeek(); assertEquals(2, statsByDate.size()); Map<String, Object> firstDateEntry = fetchDateEntry("week", getLastSundayDate(now.minusWeeks(1)).toString(), statsByDate); assertEquals(1, firstDateEntry.get("UI")); assertEquals(2, firstDateEntry.get("ODBC")); assertEquals(2, firstDateEntry.get("total")); Map<String, Object> secondDateEntry = fetchDateEntry("week", getLastSundayDate(now).toString(), statsByDate); assertEquals(1, secondDateEntry.get("UI")); assertEquals(2, secondDateEntry.get("ODBC")); assertEquals(2, secondDateEntry.get("total")); } |
### Question:
UserStats { public List<Map<String, Object>> getUserStatsByMonth() { return userStatsByMonth; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); }### Answer:
@Test public void testGetStatsByMonth() { UserStats.Builder statsBuilder = new UserStats.Builder(); LocalDate now = LocalDate.now(); statsBuilder.addUserStat(toEpochMillis(now.minusMonths(1)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusMonths(1)), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusMonths(1)), "ODBC", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now.minusMonths(1)), "ODBC", "testuser2"); statsBuilder.addUserStat(toEpochMillis(now), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "UI", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "ODBC", "testuser1"); statsBuilder.addUserStat(toEpochMillis(now), "ODBC", "testuser2"); List<Map<String, Object>> statsByDate = statsBuilder.build().getUserStatsByMonth(); assertEquals(2, statsByDate.size()); Map<String, Object> firstDateEntry = fetchDateEntry("month", getMonthStartDate(now.minusMonths(1)).toString(), statsByDate); assertEquals(1, firstDateEntry.get("UI")); assertEquals(2, firstDateEntry.get("ODBC")); assertEquals(2, firstDateEntry.get("total")); Map<String, Object> secondDateEntry = fetchDateEntry("month", getMonthStartDate(now).toString(), statsByDate); assertEquals(1, secondDateEntry.get("UI")); assertEquals(2, secondDateEntry.get("ODBC")); assertEquals(2, secondDateEntry.get("total")); } |
### Question:
MediaTypeFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { final UriInfo info = requestContext.getUriInfo(); MultivaluedMap<String, String> parameters = info.getQueryParameters(); String format = parameters.getFirst("format"); if (format == null) { return; } requestContext.getHeaders().putSingle(HttpHeaders.ACCEPT, format); } @Override void filter(ContainerRequestContext requestContext); }### Answer:
@Test public void testHeaderChange() throws IOException { MediaTypeFilter filter = new MediaTypeFilter(); ContainerRequest request = ContainerRequestBuilder.from("http: filter.filter(request); assertEquals(1, request.getAcceptableMediaTypes().size()); assertEquals(new AcceptableMediaType("unit", "test"), request.getAcceptableMediaTypes().get(0)); }
@Test public void testHeaderIsUntouched() throws IOException { MediaTypeFilter filter = new MediaTypeFilter(); ContainerRequest request = ContainerRequestBuilder.from("http: filter.filter(request); assertEquals(1, request.getAcceptableMediaTypes().size()); assertEquals(new AcceptableMediaType("random", "media"), request.getAcceptableMediaTypes().get(0)); } |
### Question:
ClasspathHealthMonitor implements LiveHealthMonitor { @Override public boolean isHealthy() { logger.debug("Checking jars {}", necessaryJarFoldersSet.size()); for(String jarFolderPath : necessaryJarFoldersSet) { File jarFolder = new File(jarFolderPath); boolean folderAccessible = false; try { folderAccessible = Files.isExecutable(jarFolder.toPath()); } catch (SecurityException se) { logger.error("SecurityException while checking folder: {}", jarFolderPath, se); } if (!folderAccessible) { logger.error("Jar: {} does not exist or it is not readable!", jarFolderPath); return false; } } logger.debug("All necessary jars exist and are readable."); return true; } ClasspathHealthMonitor(); ClasspathHealthMonitor(Set<String> classpath); @Override boolean isHealthy(); }### Answer:
@Test public void testIsHealthy() { assertTrue(classpathHealthMonitor.isHealthy()); new File(secondJarFolder).setExecutable(false); assertFalse(classpathHealthMonitor.isHealthy()); new File(secondJarFolder).setExecutable(true); assertTrue(classpathHealthMonitor.isHealthy()); new File(secondJarFolder).delete(); assertFalse(classpathHealthMonitor.isHealthy()); } |
### Question:
JSONJobDataFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { if (!APPLICATION_JSON_TYPE.equals(responseContext.getMediaType()) || !WebServer.X_DREMIO_JOB_DATA_NUMBERS_AS_STRINGS_SUPPORTED_VALUE .equals(requestContext.getHeaderString(WebServer.X_DREMIO_JOB_DATA_NUMBERS_AS_STRINGS))) { return; } ObjectWriterInjector.set(new NumberAsStringWriter(ObjectWriterInjector.getAndClear())); } @Override void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext); }### Answer:
@Test public void testJSONGeneratorUntouched() throws IOException { JSONJobDataFilter filter = new JSONJobDataFilter(); ContainerRequestBuilder request = ContainerRequestBuilder.from("http: if (testData.getHeaderKey() != null) { request.header(testData.getHeaderKey(), testData.getHeaderValue()); } ContainerResponse response = new ContainerResponse(request.build(), Response.ok().type(testData.getMediaType()).build()); filter.filter(request.build(), response); ObjectWriterModifier modifier = ObjectWriterInjector.get(); if (testData.isExpectedToBeTouched()) { assertNotNull(modifier); ObjectWriter writer = mock(ObjectWriter.class); modifier.modify(mock(JsonEndpointConfig.class), new MultivaluedHashMap<String, Object>(), new Object(), writer, mock(JsonGenerator.class)); verify(writer).withAttribute(DataJsonOutput.DREMIO_JOB_DATA_NUMBERS_AS_STRINGS_ATTRIBUTE, true); } else { assertNull(modifier); } } |
### Question:
JSONPrettyPrintFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { UriInfo info = requestContext.getUriInfo(); if (!info.getQueryParameters().containsKey("pretty")) { return; } ObjectWriterInjector.set(new PrettyPrintWriter(ObjectWriterInjector.getAndClear())); } @Override void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext); }### Answer:
@Test public void testJSONGeneratorConfigured() throws IOException { JSONPrettyPrintFilter filter = new JSONPrettyPrintFilter(); ContainerRequest request = ContainerRequestBuilder.from("http: ContainerResponse response = new ContainerResponse(request, Response.ok().build()); filter.filter(request, response); ObjectWriterModifier modifier = ObjectWriterInjector.get(); assertNotNull(modifier); JsonGenerator g = mock(JsonGenerator.class); modifier.modify(mock(JsonEndpointConfig.class), new MultivaluedHashMap<String, Object>(), new Object(), mock(ObjectWriter.class), g); verify(g).useDefaultPrettyPrinter(); }
@Test public void testJSONGeneratorUntouched() throws IOException { JSONPrettyPrintFilter filter = new JSONPrettyPrintFilter(); ContainerRequest request = ContainerRequestBuilder.from("http: ContainerResponse response = new ContainerResponse(request, Response.ok().build()); filter.filter(request, response); ObjectWriterModifier modifier = ObjectWriterInjector.get(); assertNull(modifier); } |
### Question:
Doc { void generateDoc(String linkPrefix, PrintStream out) throws JsonMappingException, JsonProcessingException { Set<Class<?>> classes = new TreeSet<>(new Comparator<Class<?>>() { @Override public int compare(Class<?> o1, Class<?> o2) { return o1.getName().compareTo(o2.getName()); } }); classes.addAll(this.classes); for (Class<?> c : classes) { Provider provider = c.getAnnotation(Provider.class); if (provider != null) { ProviderClass providerClass = new ProviderClass(c); providers.add(providerClass); } else if (ContainerResponseFilter.class.isAssignableFrom(c)) { others.add(c); } else if (ContainerRequestFilter.class.isAssignableFrom(c)) { others.add(c); } else if (MessageBodyReader.class.isAssignableFrom(c)) { others.add(c); } else if (MessageBodyWriter.class.isAssignableFrom(c)) { others.add(c); } else if (Feature.class.isAssignableFrom(c)) { others.add(c); } else if (ExceptionMapper.class.isAssignableFrom(c)) { others.add(c); } else if (RolesAllowedDynamicFeature.class.isAssignableFrom(c)) { others.add(c); } else { Resources resources = new Resources(c); roots.add(resources); } } Collections.sort(roots, new Comparator<Resources>() { @Override public int compare(Resources o1, Resources o2) { if (o1.basePath == null && o2.basePath == null) { return 0; } else if (o1.basePath == null) { return -1; } else if (o2.basePath == null) { return 1; } return o1.basePath.value().compareTo(o2.basePath.value()); } }); out.println("# TOC"); out.println(" - [Resources](#"+linkPrefix.toLowerCase()+"-resources)"); out.println(" - [JobData](#"+linkPrefix.toLowerCase()+"-data)"); out.println(" - [Others](#"+linkPrefix.toLowerCase()+"-others)"); out.println(); out.println("#"+linkPrefix+" Resources: "); for (Resources resources : roots) { out.println(resources); out.println(); } out.println(); ObjectMapper om = JSONUtil.prettyMapper(); om.enable(SerializationFeature.INDENT_OUTPUT); out.println("#"+linkPrefix+" JobData"); for (final Class<?> type : rawDataTypes) { out.println("## `" + type + "`"); try { SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); om.acceptJsonFormatVisitor(om.constructType(type), visitor); JsonSchema schema = visitor.finalSchema(); out.println("- Example:"); out.println("```"); out.println(example(schema)); out.println("```"); } catch (RuntimeException e) { throw new RuntimeException("Error generating schema for " + type, e); } out.println(); } out.println(); out.println("#"+linkPrefix+" Others: "); for (Class<?> other : others) { out.println("## " + other); } } Doc(Collection<? extends Class<?>> classes); static void main(String[] args); }### Answer:
@Test public void test() throws Exception { Doc docv2 = new Doc(asList(DatasetVersionResource.class)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream out = new PrintStream(baos); docv2.generateDoc("V2", out); assertTrue(baos.toString(), baos.toString().contains(DatasetVersionResource.class.getName())); } |
### Question:
HostProcessingRateUtil { public static Set<HostProcessingRate> computeRecordProcRateAtPhaseHostLevel(int major, Set<HostProcessingRate> hostProcessingRateSet) { if (hostProcessingRateSet == null || hostProcessingRateSet.isEmpty()) { return new TreeSet<>(); } Table<String, String, BigInteger> hostToColumnToValueTable = HashBasedTable.create(); buildPhaseHostMetrics(major, hostProcessingRateSet, hostToColumnToValueTable); return constructHostProcessingRateSet(major, hostToColumnToValueTable); } static BigDecimal computeRecordProcessingRate(BigInteger maxRecords, BigInteger processNanos); static Set<HostProcessingRate> computeRecordProcRateAtPhaseOperatorHostLevel(int major,
List<ImmutablePair<UserBitShared.OperatorProfile, Integer>> ops,
Table<Integer, Integer, String> majorMinorHostTable); static Set<HostProcessingRate> computeRecordProcRateAtPhaseHostLevel(int major, Set<HostProcessingRate> hostProcessingRateSet); }### Answer:
@Test public void testComputeRecordProcRateAtPhaseHostLevel() { int major = 1; String hostname1 = "hostname1"; String hostname2 = "hostname2"; HostProcessingRate hpr1 = new HostProcessingRate(major, hostname1, BigInteger.valueOf(5), BigInteger.valueOf(5_000_000_000L), BigInteger.valueOf(1)); HostProcessingRate hpr2 = new HostProcessingRate(major, hostname1, BigInteger.valueOf(40), BigInteger.valueOf(10_000_000_000L), BigInteger.valueOf(2)); HostProcessingRate hpr3 = new HostProcessingRate(major, hostname2, BigInteger.valueOf(80), BigInteger.valueOf(20_000_000_000L), BigInteger.valueOf(3)); HostProcessingRate hpr4 = new HostProcessingRate(major+1, hostname1, BigInteger.valueOf(70), BigInteger.valueOf(20), BigInteger.valueOf(3)); Set<HostProcessingRate> unAggregatedHostProcessingRate = Sets.newHashSet(hpr1, hpr2, hpr3, hpr4); Map<String, BigDecimal> expectedRecordProcRate = new HashMap<>(); expectedRecordProcRate.put(hostname1, BigDecimal.valueOf(3)); expectedRecordProcRate.put(hostname2, BigDecimal.valueOf(4)); Map<String, BigInteger> expectedNumThreads = new HashMap<>(); expectedNumThreads.put(hostname1, BigInteger.valueOf(3)); expectedNumThreads.put(hostname2, BigInteger.valueOf(3)); Set<HostProcessingRate> aggregatedHostProcessingRate = HostProcessingRateUtil .computeRecordProcRateAtPhaseHostLevel(major,unAggregatedHostProcessingRate); verifyAggreatedRecordProcessingRates(major, expectedRecordProcRate, expectedNumThreads, aggregatedHostProcessingRate); } |
### Question:
HostProcessingRateUtil { public static Set<HostProcessingRate> computeRecordProcRateAtPhaseOperatorHostLevel(int major, List<ImmutablePair<UserBitShared.OperatorProfile, Integer>> ops, Table<Integer, Integer, String> majorMinorHostTable) { Table<String, String, BigInteger> hostToColumnToValueTable = HashBasedTable.create(); buildOperatorHostMetrics(major, ops, majorMinorHostTable, hostToColumnToValueTable); return constructHostProcessingRateSet(major, hostToColumnToValueTable); } static BigDecimal computeRecordProcessingRate(BigInteger maxRecords, BigInteger processNanos); static Set<HostProcessingRate> computeRecordProcRateAtPhaseOperatorHostLevel(int major,
List<ImmutablePair<UserBitShared.OperatorProfile, Integer>> ops,
Table<Integer, Integer, String> majorMinorHostTable); static Set<HostProcessingRate> computeRecordProcRateAtPhaseHostLevel(int major, Set<HostProcessingRate> hostProcessingRateSet); }### Answer:
@Test public void testComputeRecordProcRateAtPhaseOperatorHostLevel() { int major = 1; int minor1 = 1; int minor2 = 2; int minor3 = 3; String hostname1 = "hostname1"; String hostname2 = "hostname2"; Table<Integer, Integer, String> majorMinorHostTable = HashBasedTable.create(); majorMinorHostTable.put(major, minor1, hostname1); majorMinorHostTable.put(major, minor2, hostname2); majorMinorHostTable.put(major, minor3, hostname1); StreamProfile streamProfile1 = StreamProfile.newBuilder().setRecords(40).build(); StreamProfile streamProfile2 = StreamProfile.newBuilder().setRecords(20).build(); StreamProfile streamProfile3 = StreamProfile.newBuilder().setRecords(60).build(); OperatorProfile op1 = OperatorProfile.newBuilder().addInputProfile(streamProfile1) .setProcessNanos(10_000_000_000L).build(); OperatorProfile op2 = OperatorProfile.newBuilder().addInputProfile(streamProfile2) .setProcessNanos(20_000_000_000L).build(); OperatorProfile op3 = OperatorProfile.newBuilder().addInputProfile(streamProfile3) .setProcessNanos(30_000_000_000L).build(); ImmutablePair<OperatorProfile, Integer> ip1 = ImmutablePair.of(op1, minor1); ImmutablePair<OperatorProfile, Integer> ip2 = ImmutablePair.of(op2, minor2); ImmutablePair<OperatorProfile, Integer> ip3 = ImmutablePair.of(op3, minor3); List<ImmutablePair<OperatorProfile, Integer>> ops = Lists.newArrayList(ip1, ip2, ip3); Map<String, BigDecimal> expectedRecordProcRate = new HashMap<>(); expectedRecordProcRate.put(hostname1, BigDecimal.valueOf(2.5)); expectedRecordProcRate.put(hostname2, BigDecimal.valueOf(1)); Map<String, BigInteger> expectedNumThreads = new HashMap<>(); expectedNumThreads.put(hostname1, BigInteger.valueOf(2)); expectedNumThreads.put(hostname2, BigInteger.valueOf(1)); Set<HostProcessingRate> aggregatedHostProcessingRate = computeRecordProcRateAtPhaseOperatorHostLevel(major, ops, majorMinorHostTable); verifyAggreatedRecordProcessingRates(major, expectedRecordProcRate, expectedNumThreads, aggregatedHostProcessingRate); } |
### Question:
SimpleDurationFormat { static String formatNanos(long durationInNanos) { if (durationInNanos < 1) { return "0s"; } final long days = TimeUnit.NANOSECONDS.toDays(durationInNanos); final long hours = TimeUnit.NANOSECONDS.toHours(durationInNanos) - TimeUnit.DAYS.toHours(TimeUnit.NANOSECONDS.toDays(durationInNanos)); final long minutes = TimeUnit.NANOSECONDS.toMinutes(durationInNanos) - TimeUnit.HOURS.toMinutes(TimeUnit.NANOSECONDS.toHours(durationInNanos)); final long seconds = TimeUnit.NANOSECONDS.toSeconds(durationInNanos) - TimeUnit.MINUTES.toSeconds(TimeUnit.NANOSECONDS.toMinutes(durationInNanos)); final long milliSeconds = TimeUnit.NANOSECONDS.toMillis(durationInNanos) - TimeUnit.SECONDS.toMillis(TimeUnit.NANOSECONDS.toSeconds(durationInNanos)); final long microSeconds = TimeUnit.NANOSECONDS.toMicros(durationInNanos) - TimeUnit.MILLISECONDS.toMicros(TimeUnit.NANOSECONDS.toMillis(durationInNanos)); final long nanoSeconds = durationInNanos - TimeUnit.MICROSECONDS.toNanos(TimeUnit.NANOSECONDS.toMicros(durationInNanos)); if (days >= 1) { return days + "d" + hours + "h" + minutes + "m"; } else if (hours >= 1) { return hours + "h" + minutes + "m"; } else if (minutes >= 1) { return minutes + "m" + seconds + "s"; } else if (seconds >= 1) { return String.format("%.3fs", seconds + milliSeconds/1000.0); } else if (milliSeconds >= 1) { return milliSeconds + "ms"; } else if (microSeconds >= 1) { return microSeconds + "us"; } else { return nanoSeconds + "ns"; } } }### Answer:
@Test public void testFormatNanos() { assertEquals("123us", SimpleDurationFormat.formatNanos(123456)); assertEquals("456ns", SimpleDurationFormat.formatNanos(456)); assertEquals("825ms", SimpleDurationFormat.formatNanos(825435267)); assertEquals("1.825s", SimpleDurationFormat.formatNanos(1825435267)); assertEquals("30m45s", SimpleDurationFormat.formatNanos(1845825435267L)); assertEquals("1h20m", SimpleDurationFormat.formatNanos(4845825435267L)); } |
### Question:
JobResultToLogEntryConverter implements Function<Job, LoggedQuery> { @Override public LoggedQuery apply(Job job) { final JobInfo info = job.getJobAttempt().getInfo(); final List<String> contextList = info.getContextList(); String outcomeReason = null; switch(job.getJobAttempt().getState()) { case CANCELED: outcomeReason = info.getCancellationInfo().getMessage(); break; case FAILED: outcomeReason = info.getFailureInfo(); break; default: break; } return new LoggedQuery( job.getJobId().getId(), contextList == null ? null : contextList.toString(), info.getSql(), info.getStartTime(), info.getFinishTime(), job.getJobAttempt().getState(), outcomeReason, info.getUser() ); } @Override LoggedQuery apply(Job job); }### Answer:
@Test public void testOutcomeReasonCancelled() throws Exception { JobResultToLogEntryConverter converter = new JobResultToLogEntryConverter(); Job job = mock(Job.class); JobAttempt jobAttempt = new JobAttempt(); JobInfo jobInfo = new JobInfo(); JobId jobId = new JobId(); jobId.setId("testId"); final String cancelReason = "this is the cancel reason"; JobCancellationInfo jobCancellationInfo = new JobCancellationInfo(); jobCancellationInfo.setMessage(cancelReason); when(job.getJobId()).thenReturn(jobId); jobAttempt.setState(JobState.CANCELED); jobAttempt.setInfo(jobInfo); jobInfo.setCancellationInfo(jobCancellationInfo); when(job.getJobAttempt()).thenReturn(jobAttempt); assertEquals(cancelReason, converter.apply(job).getOutcomeReason()); }
@Test public void testOutcomeReasonFailed() throws Exception { JobResultToLogEntryConverter converter = new JobResultToLogEntryConverter(); Job job = mock(Job.class); JobAttempt jobAttempt = new JobAttempt(); JobInfo jobInfo = new JobInfo(); JobId jobId = new JobId(); jobId.setId("testId"); final String failureReason = "this is the failure reason"; when(job.getJobId()).thenReturn(jobId); jobAttempt.setState(JobState.FAILED); jobAttempt.setInfo(jobInfo); jobInfo.setFailureInfo(failureReason); when(job.getJobAttempt()).thenReturn(jobAttempt); assertEquals(failureReason, converter.apply(job).getOutcomeReason()); } |
### Question:
JobsProtoUtil { private static <M extends GeneratedMessageV3, T extends Message<T> & Schema<T>> T toStuff(Schema<T> protostuffSchema, M protobuf) { T message = protostuffSchema.newMessage(); ProtobufIOUtil.mergeFrom(protobuf.toByteArray(), message, protostuffSchema); return message; } private JobsProtoUtil(); static JobAttempt getLastAttempt(com.dremio.service.job.JobDetails jobDetails); static JobProtobuf.JobAttempt toBuf(JobAttempt attempt); static JobAttempt toStuff(JobProtobuf.JobAttempt attempt); static JobProtobuf.JobId toBuf(JobId jobId); static DatasetCommonProtobuf.ViewFieldType toBuf(ViewFieldType viewFieldType); static List<DatasetCommonProtobuf.ViewFieldType> toBuf(List<ViewFieldType> viewFieldTypes); static ViewFieldType toStuff(DatasetCommonProtobuf.ViewFieldType viewFieldType); static List<ViewFieldType> toStuff(List<DatasetCommonProtobuf.ViewFieldType> fieldTypes); static JobId toStuff(JobProtobuf.JobId jobId); static JobProtobuf.JobFailureInfo toBuf(JobFailureInfo jobFailureInfo); static JobFailureInfo toStuff(JobProtobuf.JobFailureInfo jobFailureInfo); static JobResult toStuff(JobProtobuf.JobResult jobResult); static QueryMetadata toBuf(com.dremio.service.jobs.metadata.QueryMetadata queryMetadata); static JobCancellationInfo toStuff(JobProtobuf.JobCancellationInfo jobCancellationInfo); static JobProtobuf.MaterializationSummary toBuf(MaterializationSummary materializationSummary); static com.dremio.service.job.JobState toBuf(JobState jobState); static com.dremio.service.job.AttemptEvent.State toBuf(com.dremio.exec.proto.beans.AttemptEvent.State attemptState); static com.dremio.exec.proto.UserBitShared.AttemptEvent.State toBuf2(com.dremio.exec.proto.beans.AttemptEvent.State attemptState); static com.dremio.exec.proto.beans.AttemptEvent.State toBuf(com.dremio.service.job.AttemptEvent.State attemptState); static com.dremio.exec.proto.beans.AttemptEvent.State toBuf(com.dremio.exec.proto.UserBitShared.AttemptEvent.State attemptState); static List<AttemptEvent> toStuff2(List<com.dremio.exec.proto.beans.AttemptEvent> stateList); static JobState toStuff(com.dremio.service.job.JobState jobState); static com.dremio.service.job.QueryType toBuf(com.dremio.service.job.proto.QueryType queryType); static com.dremio.service.job.RequestType toBuf(RequestType requestType); static RequestType toStuff(com.dremio.service.job.RequestType requestType); static DatasetType toStuff(DatasetCommonProtobuf.DatasetType datasetType); static SearchTypes.SortOrder toStoreSortOrder(SearchJobsRequest.SortOrder order); static com.dremio.exec.work.user.SubstitutionSettings toPojo(SubstitutionSettings substitutionSettings); static SubstitutionSettings toBuf(com.dremio.exec.work.user.SubstitutionSettings substitutionSettings); static com.dremio.service.job.proto.QueryType toStuff(QueryType queryType); static MaterializationSummary toStuff(JobProtobuf.MaterializationSummary materializationSummary); static SqlQuery toBuf(com.dremio.service.jobs.SqlQuery sqlQuery); }### Answer:
@Test public void testToStuff() { JobAttempt resultJobAttempt = toStuff(jobAttemptProtobuf); assertEquals(resultJobAttempt, jobAttemptProtostuff); JobFailureInfo jobFailureInfo = toStuff(jobFailureInfoProtoBuf); assertEquals(jobFailureInfoProtoStuff, jobFailureInfo); JobCancellationInfo jobCancellationInfo = toStuff(jobCancellationInfoProtobuf); assertNotEquals(jobCancellationInfoProtoStuff, jobCancellationInfo); } |
### Question:
DatasetConfigUpgrade extends UpgradeTask implements LegacyUpgradeTask { @VisibleForTesting byte[] convertFromOldSchema(OldSchema oldSchema) { FlatBufferBuilder builder = new FlatBufferBuilder(); int[] fieldOffsets = new int[oldSchema.fieldsLength()]; for (int i = 0; i < oldSchema.fieldsLength(); i++) { fieldOffsets[i] = convertFromOldField(oldSchema.fields(i), builder); } int fieldsOffset = org.apache.arrow.flatbuf.Schema.createFieldsVector(builder, fieldOffsets); int[] metadataOffsets = new int[oldSchema.customMetadataLength()]; for (int i = 0; i < metadataOffsets.length; i++) { int keyOffset = builder.createString(oldSchema.customMetadata(i).key()); int valueOffset = builder.createString(oldSchema.customMetadata(i).value()); KeyValue.startKeyValue(builder); KeyValue.addKey(builder, keyOffset); KeyValue.addValue(builder, valueOffset); metadataOffsets[i] = KeyValue.endKeyValue(builder); } int metadataOffset = org.apache.arrow.flatbuf.Field.createCustomMetadataVector(builder, metadataOffsets); org.apache.arrow.flatbuf.Schema.startSchema(builder); org.apache.arrow.flatbuf.Schema.addFields(builder, fieldsOffset); org.apache.arrow.flatbuf.Schema.addCustomMetadata(builder, metadataOffset); builder.finish(org.apache.arrow.flatbuf.Schema.endSchema(builder)); return builder.sizedByteArray(); } DatasetConfigUpgrade(); @Override Version getMaxVersion(); @Override String getTaskUUID(); @Override void upgrade(UpgradeContext context); @Override String toString(); }### Answer:
@Test public void testArrowSchemaConversion() { byte[] schema = Base64.getDecoder().decode(OLD_SCHEMA); try { BatchSchema.deserialize(schema); fail("Should not be able to process old Schema"); } catch (IndexOutOfBoundsException e) { } ByteString schemaBytes = ByteString.copyFrom(schema); DatasetConfigUpgrade datasetConfigUpgrade = new DatasetConfigUpgrade(); OldSchema oldSchema = OldSchema.getRootAsOldSchema(schemaBytes.asReadOnlyByteBuffer()); byte[] newschemaBytes = datasetConfigUpgrade.convertFromOldSchema(oldSchema); BatchSchema batchSchema = BatchSchema.deserialize(newschemaBytes); int fieldCount = batchSchema.getFieldCount(); assertEquals(4, fieldCount); List<String> expected = ImmutableList.of( "R_REGIONKEY", "R_NAME", "R_COMMENT", "$_dremio_$_update_$"); List<String> actual = Lists.newArrayList(); for (int i = 0; i < fieldCount; i++) { Field field = batchSchema.getColumn(i); actual.add(field.getName()); } assertTrue(Objects.equals(expected, actual)); } |
### Question:
AttemptsHelper { public static long getLegacyEnqueuedTime(JobAttempt jobAttempt) { final JobInfo jobInfo = jobAttempt.getInfo(); if (jobInfo == null) { return 0; } final ResourceSchedulingInfo schedulingInfo = jobInfo.getResourceSchedulingInfo(); if (schedulingInfo == null) { return 0; } final Long schedulingStart = schedulingInfo.getResourceSchedulingStart(); Long schedulingEnd = schedulingInfo.getResourceSchedulingEnd(); if (schedulingStart == null || schedulingEnd == null) { return 0; } if (jobAttempt.getState() == JobState.ENQUEUED) { schedulingEnd = System.currentTimeMillis(); } else { schedulingEnd = Math.max(schedulingStart, schedulingEnd); } return schedulingEnd - schedulingStart; } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); }### Answer:
@Test public void testGetEnqueuedTime() { final ResourceSchedulingInfo schedulingInfo = new ResourceSchedulingInfo() .setResourceSchedulingStart(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(3)) .setResourceSchedulingEnd(0L); final JobInfo info = new JobInfo() .setResourceSchedulingInfo(schedulingInfo); final JobAttempt attempt = new JobAttempt() .setInfo(info) .setState(JobState.ENQUEUED); assertTrue("Enqueued job has wrong enqueued time", AttemptsHelper.getLegacyEnqueuedTime(attempt) >= TimeUnit.HOURS.toMillis(3)); }
@Test public void testGetEnqueuedTimeFailedJob() { final ResourceSchedulingInfo schedulingInfo = new ResourceSchedulingInfo() .setResourceSchedulingStart(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(3)) .setResourceSchedulingEnd(0L); final JobInfo info = new JobInfo() .setResourceSchedulingInfo(schedulingInfo); final JobAttempt attempt = new JobAttempt() .setInfo(info) .setState(JobState.FAILED); assertEquals(0L, AttemptsHelper.getLegacyEnqueuedTime(attempt)); } |
### Question:
AttemptsHelper { public Long getPlanningTime() { return getDuration(State.PLANNING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); }### Answer:
@Test public void testGetPlanningTime() { final ResourceSchedulingInfo schedulingInfo = new ResourceSchedulingInfo() .setResourceSchedulingStart(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(3)) .setResourceSchedulingEnd(0L); final JobInfo info = new JobInfo() .setResourceSchedulingInfo(schedulingInfo); final JobAttempt attempt = new JobAttempt() .setInfo(info) .setState(JobState.ENQUEUED) .setDetails(new JobDetails()); assertEquals(0L, AttemptsHelper.getLegacyPlanningTime(attempt)); }
@Test public void testPlanningTime() { Preconditions.checkNotNull(attemptsHelper.getPlanningTime()); assertTrue(1L == attemptsHelper.getPlanningTime()); } |
### Question:
AttemptsHelper { public static long getLegacyExecutionTime(JobAttempt jobAttempt) { final JobInfo jobInfo = jobAttempt.getInfo(); if (jobInfo == null) { return 0; } final JobDetails jobDetails = jobAttempt.getDetails(); if (jobDetails == null) { return 0; } final long startTime = Optional.ofNullable(jobInfo.getStartTime()).orElse(0L); final long finishTime = Optional.ofNullable(jobInfo.getFinishTime()).orElse(startTime); final long planningScheduling = Optional.ofNullable(jobDetails.getTimeSpentInPlanning()).orElse(0L); return finishTime - startTime - planningScheduling; } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); }### Answer:
@Test public void testGetExecutionTime() { final ResourceSchedulingInfo schedulingInfo = new ResourceSchedulingInfo() .setResourceSchedulingStart(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(3)) .setResourceSchedulingEnd(0L); final JobInfo info = new JobInfo() .setResourceSchedulingInfo(schedulingInfo); final JobAttempt attempt = new JobAttempt() .setInfo(info) .setState(JobState.ENQUEUED) .setDetails(new JobDetails()); assertEquals(0L, AttemptsHelper.getLegacyExecutionTime(attempt)); } |
### Question:
AttemptsHelper { public Long getPendingTime() { return getDuration(State.PENDING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); }### Answer:
@Test public void testGetPendingTime() { Preconditions.checkNotNull(attemptsHelper.getPendingTime()); assertTrue(1L == attemptsHelper.getPendingTime()); } |
### Question:
AttemptsHelper { public Long getMetadataRetrievalTime() { return getDuration(State.METADATA_RETRIEVAL); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); }### Answer:
@Test public void testGetMetadataRetrievalTime() { Preconditions.checkNotNull(attemptsHelper.getMetadataRetrievalTime()); assertTrue(1L == attemptsHelper.getMetadataRetrievalTime()); } |
### Question:
AttemptsHelper { public Long getEngineStartTime() { return getDuration(State.ENGINE_START); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); }### Answer:
@Test public void testGetEngineStartTime() { Preconditions.checkNotNull(attemptsHelper.getEngineStartTime()); assertTrue(1L == attemptsHelper.getEngineStartTime()); } |
### Question:
AttemptsHelper { public Long getQueuedTime() { return getDuration(State.QUEUED); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); }### Answer:
@Test public void testGetQueuedTime() { Preconditions.checkNotNull(attemptsHelper.getQueuedTime()); assertTrue(1L == attemptsHelper.getQueuedTime()); } |
### Question:
AttemptsHelper { public Long getExecutionPlanningTime() { return getDuration(State.EXECUTION_PLANNING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); }### Answer:
@Test public void testGetExecutionPlanningTime() { Preconditions.checkNotNull(attemptsHelper.getExecutionPlanningTime()); assertTrue(1L == attemptsHelper.getExecutionPlanningTime()); } |
### Question:
AttemptsHelper { public Long getStartingTime() { return getDuration(State.STARTING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); }### Answer:
@Test public void testGetStartingTime() { Preconditions.checkNotNull(attemptsHelper.getStartingTime()); assertTrue(1L == attemptsHelper.getStartingTime()); } |
### Question:
AttemptsHelper { public Long getRunningTime() { return getDuration(State.RUNNING); } AttemptsHelper(JobAttempt jobAttempt); boolean hasStateDurations(); static long getCommandPoolWaitTime(JobAttempt jobAttempt); static long getLegacyEnqueuedTime(JobAttempt jobAttempt); static long getPoolWaitTime(JobAttempt jobAttempt); static long getLegacyPlanningTime(JobAttempt jobAttempt); static long getLegacyExecutionTime(JobAttempt jobAttempt); Long getPendingTime(); Long getMetadataRetrievalTime(); Long getPlanningTime(); Long getQueuedTime(); Long getEngineStartTime(); Long getExecutionPlanningTime(); Long getStartingTime(); Long getRunningTime(); Long getTotalTime(); }### Answer:
@Test public void testGetRunningTime() { Preconditions.checkNotNull(attemptsHelper.getRunningTime()); assertTrue(1L == attemptsHelper.getRunningTime()); } |
### Question:
SimpleUserService implements UserService { @Override public Iterable<? extends User> searchUsers(String searchTerm, String sortColumn, SortOrder order, Integer limit) throws IOException { limit = limit == null ? 10000 : limit; if (searchTerm == null || searchTerm.isEmpty()) { return getAllUsers(limit); } final SearchQuery query = SearchQueryUtils.or( SearchQueryUtils.newContainsTerm(UserIndexKeys.NAME, searchTerm), SearchQueryUtils.newContainsTerm(UserIndexKeys.FIRST_NAME, searchTerm), SearchQueryUtils.newContainsTerm(UserIndexKeys.LAST_NAME, searchTerm), SearchQueryUtils.newContainsTerm(UserIndexKeys.EMAIL, searchTerm)); final LegacyFindByCondition conditon = new LegacyFindByCondition() .setCondition(query) .setLimit(limit) .addSorting(buildSorter(sortColumn, order)); return Lists.transform(Lists.newArrayList(KVUtil.values(userStore.find(conditon))), infoConfigTransformer); } @Inject SimpleUserService(Provider<LegacyKVStoreProvider> kvStoreProvider); @Override User getUser(String userName); @Override User getUser(UID uid); @Override User createUser(final User userConfig, final String authKey); @Override User updateUser(final User userGroup, final String authKey); @Override User updateUserName(final String oldUserName, final String newUserName, final User userGroup, final String authKey); @Override void authenticate(String userName, String password); @Override Iterable<? extends User> getAllUsers(Integer limit); @Override boolean hasAnyUser(); @Override Iterable<? extends User> searchUsers(String searchTerm, String sortColumn, SortOrder order,
Integer limit); @Override void deleteUser(final String userName, String version); void setPassword(String userName, String password); @VisibleForTesting static void validatePassword(String input); @VisibleForTesting
static final String USER_STORE; }### Answer:
@Test public void testSearch() throws Exception { try(final LegacyKVStoreProvider kvstore = LegacyKVStoreProviderAdapter.inMemory(DremioTest.CLASSPATH_SCAN_RESULT)) { kvstore.start(); final SimpleUserService userGroupService = new SimpleUserService(() -> kvstore); initUserStore(kvstore, userGroupService); assertEquals(2, Iterables.size(userGroupService.searchUsers("David", null, null, null))); assertEquals(1, Iterables.size(userGroupService.searchUsers("Johnson", null, null, null))); assertEquals(2, Iterables.size(userGroupService.searchUsers("Mark", null, null, null))); assertEquals(2, Iterables.size(userGroupService.searchUsers("avi", null, null, null))); assertEquals(1, Iterables.size(userGroupService.searchUsers("k.j", null, null, null))); assertEquals(2, Iterables.size(userGroupService.searchUsers("@dremio", null, null, null))); assertEquals(1, Iterables.size(userGroupService.searchUsers("rkda", null, null, null))); assertEquals(3, Iterables.size(userGroupService.searchUsers("a", null, null, null))); } } |
### Question:
MetricsCombiner { private QueryProgressMetrics combine() { long rowsProcessed = executorMetrics .mapToLong(QueryProgressMetrics::getRowsProcessed) .sum(); return QueryProgressMetrics.newBuilder() .setRowsProcessed(rowsProcessed) .build(); } private MetricsCombiner(Stream<QueryProgressMetrics> executorMetrics); }### Answer:
@Test public void testCombine() { CoordExecRPC.QueryProgressMetrics metrics1 = CoordExecRPC.QueryProgressMetrics .newBuilder() .setRowsProcessed(100) .build(); CoordExecRPC.QueryProgressMetrics metrics2 = CoordExecRPC.QueryProgressMetrics .newBuilder() .setRowsProcessed(120) .build(); assertEquals(0, MetricsCombiner.combine(Stream.empty()).getRowsProcessed()); assertEquals(100, MetricsCombiner.combine(Stream.of(metrics1)).getRowsProcessed()); assertEquals(220, MetricsCombiner.combine(Stream.of(metrics1, metrics2)).getRowsProcessed()); } |
### Question:
ReconnectingConnection implements Closeable { public <R extends MessageLite, C extends RpcCommand<R, CONNECTION_TYPE>> void runCommand(C cmd) { if (closed.get()) { cmd.connectionFailed(FailureType.CONNECTION, new IOException("Connection has been closed: " + toString())); } ConnectionRunner r = new ConnectionRunner(); connector.execute(r); r.executeCommand(cmd); } ReconnectingConnection(String name, OUTBOUND_HANDSHAKE handshake, String host, int port); ReconnectingConnection(String name, OUTBOUND_HANDSHAKE handshake, String host, int port, long lostConnectionReattemptMS, long connectionSuccessTimeoutMS, long timeBetweenAttemptMS); void runCommand(C cmd); CloseHandlerCreator getCloseHandlerCreator(); void addExternalConnection(CONNECTION_TYPE connection); @Override void close(); String toString(); }### Answer:
@Test public void ensureDirectFailureOnRpcException() { conn().runCommand(Cmd.expectFail()); }
@Test public void ensureSecondSuccess() { conn( r -> r.connectionFailed(FailureType.CONNECTION, new IllegalStateException()), r -> r.connectionSucceeded(newRemoteConnection()) ).runCommand(Cmd.expectSucceed()); }
@Test public void ensureTimeoutFailAndRecover() { TestReConnection c = conn(200,100,1, r -> { wt(100); r.connectionFailed(FailureType.CONNECTION, new IllegalStateException()); }, r -> r.connectionSucceeded(newRemoteConnection()) ); c.runCommand(Cmd.expectFail()); wt(200); c.runCommand(Cmd.expectSucceed()); }
@Test public void ensureSuccessThenAvailable() { TestReConnection c = conn(r -> r.connectionSucceeded(newRemoteConnection())); c.runCommand(Cmd.expectSucceed()); c.runCommand(Cmd.expectAvailable()); }
@Test public void ensureInActiveCausesReconnection() { TestReConnection c = conn( 100, 100, 1, r -> r.connectionSucceeded(newBadConnection()), r -> { wt(200); r.connectionFailed(FailureType.CONNECTION, new IllegalStateException()); }, r -> r.connectionSucceeded(newRemoteConnection()) ); c.runCommand(Cmd.expectSucceed()); c.runCommand(Cmd.expectFail()); wt(300); c.runCommand(Cmd.expectSucceed()); c.runCommand(Cmd.expectAvailable()); }
@Test public void ensureFirstFailsWaiting() throws InterruptedException, ExecutionException { CountDownLatch latch = new CountDownLatch(1); TestReConnection c = conn( 100000, 100, 100, r -> { try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } r.connectionFailed(FailureType.CONNECTION, new IllegalStateException()); }, r -> r.connectionSucceeded(newRemoteConnection()) ); CompletableFuture<Void> first = CompletableFuture.runAsync(() -> c.runCommand(Cmd.expectFail())); CompletableFuture<Void> rest = CompletableFuture.allOf(IntStream.range(0, 10).mapToObj(i -> CompletableFuture.runAsync(() -> { c.runCommand(Cmd.expectFail()); })).collect(Collectors.toList()).toArray(new CompletableFuture[0])); try { rest.get(0, TimeUnit.SECONDS); Assert.fail(); } catch (TimeoutException e) { } latch.countDown(); first.get(); rest.get(); } |
### Question:
RpcException extends IOException { public static <T extends Throwable> void propagateIfPossible(@Nullable RpcException e, Class<T> clazz) throws T { if (e == null) { return; } Throwable cause = e.getCause(); if (!(cause instanceof UserRemoteException)) { return; } UserRemoteException ure = (UserRemoteException) e.getCause(); DremioPBError remoteError = ure.getOrCreatePBError(false); ExceptionWrapper ew = remoteError.getException(); Class<? extends Throwable> exceptionClazz; do { try { exceptionClazz = Class.forName(ew.getExceptionClass()).asSubclass(Throwable.class); } catch (ClassNotFoundException cnfe) { logger.info("Cannot deserialize exception " + ew.getExceptionClass(), cnfe); return; } if (UserRpcException.class.isAssignableFrom(exceptionClazz)) { ew = ew.getCause(); continue; } break; } while(true); Throwable t; try { Constructor<? extends Throwable> constructor = exceptionClazz.getConstructor(String.class, Throwable.class); t = constructor.newInstance(ew.getMessage(), e); } catch(ReflectiveOperationException nsme) { Constructor<? extends Throwable> constructor; try { constructor = exceptionClazz.getConstructor(String.class); t = constructor.newInstance(ew.getMessage()).initCause(e); } catch (ReflectiveOperationException rfe) { logger.info("Cannot deserialize exception " + ew.getExceptionClass(), rfe); return; } } Throwables.propagateIfPossible(t, clazz); } RpcException(); RpcException(String message, Throwable cause); RpcException(String errMsg, String status, String errorId, Throwable cause); RpcException(String errMsg, String status, String errorId); RpcException(String message); RpcException(Throwable cause); static RpcException mapException(Throwable t); static RpcException mapException(String message, Throwable t); boolean isRemote(); DremioPBError getRemoteError(); static void propagateIfPossible(@Nullable RpcException e, Class<T> clazz); String getStatus(); String getErrorId(); }### Answer:
@Test public void testNullException() throws Exception { RpcException.propagateIfPossible(null, Exception.class); }
@Test public void testNonRemoteException() throws Exception { RpcException e = new RpcException("Test message", new Exception()); RpcException.propagateIfPossible(e, Exception.class); }
@Test public void testRemoteTestException() throws Exception { UserRemoteException ure = UserRemoteException.create(UserException .unsupportedError(new UserRpcException(null, "user rpc exception", new TestException("test message"))) .build(logger).getOrCreatePBError(false)); exception.expect(TestException.class); exception.expectMessage("test message"); RpcException.propagateIfPossible(new RpcException(ure), TestException.class); }
@Test public void testRemoteRuntimeException() throws Exception { UserRemoteException ure = UserRemoteException.create(UserException .unsupportedError(new UserRpcException(null, "user rpc exception", new RuntimeException("test message"))) .build(logger).getOrCreatePBError(false)); exception.expect(RuntimeException.class); exception.expectMessage("test message"); RpcException.propagateIfPossible(new RpcException(ure), TestException.class); } |
### Question:
KeyPair extends AbstractList<Object> implements CompoundKey { @SuppressWarnings("unchecked") public static <K1, K2> KeyPair<K1, K2> of(List<Object> list) { checkArgument(list.size() == 2, "list should be of size 2, had actually %s elements", list); final K1 value1 = (K1) list.get(0); final K2 value2 = (K2) list.get(1); return new KeyPair<>(value1, value2); } KeyPair(K1 key1, K2 key2); @SuppressWarnings("unchecked") static KeyPair<K1, K2> of(List<Object> list); @Override Object get(int index); @Override int size(); K1 getKey1(); K2 getKey2(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testOf() { if (!valid) { thrown.expect(IllegalArgumentException.class); } KeyPair<String, String> keyPair = KeyPair.of(values); assertNotNull(keyPair); assertEquals(values.get(0), keyPair.getKey1()); assertEquals(values.get(1), keyPair.getKey2()); assertEquals(values, keyPair); } |
### Question:
KeyUtils { public static boolean equals(Object left, Object right) { if (left instanceof byte[] && right instanceof byte[]) { return Arrays.equals((byte[]) left, (byte[]) right); } return Objects.equals(left, right); } private KeyUtils(); static boolean equals(Object left, Object right); static int hash(Object... keys); static String toString(Object key); }### Answer:
@Test public void testEqualsReturnsFalseAllNull() { assertTrue(KeyUtils.equals(null, null)); }
@Test public void testEqualsReturnsFalseLeftNull() { assertFalse(KeyUtils.equals(null, Boolean.TRUE)); }
@Test public void testEqualsReturnsFalseRightNull() { assertFalse(KeyUtils.equals(Boolean.TRUE, null)); }
@Test public void testEqualsReturnsTrueWithBooleanTrueTrue() { assertTrue(KeyUtils.equals(Boolean.TRUE, Boolean.TRUE)); }
@Test public void testEqualsReturnsTrueWithBooleanFalseFalse() { assertTrue(KeyUtils.equals(Boolean.FALSE, Boolean.FALSE)); }
@Test public void testEqualsReturnsFalseWithBooleanTrueFalse() { assertFalse(KeyUtils.equals(Boolean.TRUE, Boolean.FALSE)); }
@Test public void testEqualsReturnsFalseWithBooleanFalseTrue() { assertFalse(KeyUtils.equals(Boolean.FALSE, Boolean.TRUE)); }
@Test public void testEqualsReturnsTrueWithByteArrays() { byte[] left = new byte[]{0, 1, 2, 3, 4}; byte[] right = new byte[]{0, 1, 2, 3, 4}; assertTrue(KeyUtils.equals(left, right)); }
@Test public void testEqualsReturnsFalseWithByteArrays() { byte[] left = new byte[]{0, 1, 2, 3, 4}; byte[] right = new byte[]{0, 1, 2, 3, 5}; assertFalse(KeyUtils.equals(left, right)); }
@Test public void testEqualsReturnsFalseWithByteArraysDifferentLength() { byte[] left = new byte[]{0, 1, 2, 3, 4}; byte[] right = new byte[]{0, 1, 2, 3}; assertFalse(KeyUtils.equals(left, right)); }
@Test public void testEqualsReturnsTrueByteProtoObject() { assertTrue(KeyUtils.equals( new KeyPair<>( TEST_STRING.getBytes(UTF_8), "some other silly string".getBytes(UTF_8)), new KeyPair<>( TEST_STRING.getBytes(UTF_8), "some other silly string".getBytes(UTF_8)))); }
@Test public void testEqualsReturnsFalseByteProtoObject() { assertFalse(KeyUtils.equals( new KeyPair<>( TEST_STRING.getBytes(UTF_8), "some other silly string".getBytes(UTF_8)), new KeyPair<>( TEST_STRING.getBytes(UTF_8), "some other silly".getBytes(UTF_8)))); }
@Test public void testEqualsReturnsFalseByteProtoObjectWithNull() { assertFalse(KeyUtils.equals( new KeyPair<>( TEST_STRING.getBytes(UTF_8), "some other silly string".getBytes(UTF_8)), new KeyPair<>( TEST_STRING.getBytes(UTF_8), null))); }
@Test public void testEqualsReturnsFalseWithProtoObjectsDifferentUUID() { assertFalse(KeyUtils.equals( new KeyPair<>( PROTOBUFF_ORIGINAL_STRING, UUID.randomUUID()), new KeyTriple<>( "Some string", PROTOBUFF_ORIGINAL_STRING, UUID.randomUUID()))); }
@Test public void testEqualsReturnsFalseWithNestedProtoObjectsDifferentUUID() { assertFalse(KeyUtils.equals( new KeyTriple<>( new KeyPair<>(PROTOBUFF_ORIGINAL_STRING, UUID.randomUUID()), new KeyTriple<>("Some string", PROTOBUFF_ORIGINAL_STRING, UUID.randomUUID()), new KeyTriple<>("Some string", PROTOBUFF_ORIGINAL_STRING, UUID.randomUUID())), new KeyTriple<>( new KeyPair<>(PROTOBUFF_ORIGINAL_STRING, UUID.randomUUID()), new KeyTriple<>("Some string", PROTOBUFF_ORIGINAL_STRING, UUID.randomUUID()), new KeyTriple<>("Some string", PROTOBUFF_ORIGINAL_STRING, UUID.randomUUID())))); } |
### Question:
Clean { public static void go(String[] args) throws Exception { final DACConfig dacConfig = DACConfig.newConfig(); final Options options = Options.parse(args); if(options.help) { return; } if (!dacConfig.isMaster) { throw new UnsupportedOperationException("Cleanup should be run on master node"); } Optional<LocalKVStoreProvider> providerOptional = CmdUtils.getKVStoreProvider(dacConfig.getConfig()); if (!providerOptional.isPresent()) { AdminLogger.log("No KVStore detected."); return; } try (LocalKVStoreProvider provider = providerOptional.get()) { provider.start(); if (provider.getStores().size() == 0) { AdminLogger.log("No store stats available"); } if(options.hasActiveOperation()) { AdminLogger.log("Initial Store Status."); } else { AdminLogger.log("No operation requested. "); } for(StoreWithId<?, ?> id : provider) { KVAdmin admin = id.getStore().getAdmin(); AdminLogger.log(admin.getStats()); } if(options.deleteOrphans) { deleteSplitOrphans(provider.asLegacy()); deleteCollaborationOrphans(provider.asLegacy()); } if(options.maxJobDays < Integer.MAX_VALUE) { deleteOldJobsAndProfiles(provider.asLegacy(), options.maxJobDays); } if (options.deleteOrphanProfiles) { deleteOrphanProfiles(provider.asLegacy()); } if(options.reindexData) { reindexData(provider); } if(options.compactKvStore) { compactStore(provider); } if(options.hasActiveOperation()) { AdminLogger.log("\n\nFinal Store Status."); for(StoreWithId<?, ?> id : provider.unwrap(LocalKVStoreProvider.class)) { KVAdmin admin = id.getStore().getAdmin(); AdminLogger.log(admin.getStats()); } } return; } } static void go(String[] args); static void main(String[] args); }### Answer:
@Test public void runWithOptions() throws Exception { getCurrentDremioDaemon().close(); Clean.go(new String[] {}); Clean.go(new String[] {"-o", "-i", "-c", "-j=30", "-p"}); Clean.go(new String[] {"-h"}); } |
### Question:
KeyUtils { public static String toString(Object key) { if (null == key) { return null; } return (key instanceof byte[] ? Arrays.toString((byte[]) key) : key.toString()); } private KeyUtils(); static boolean equals(Object left, Object right); static int hash(Object... keys); static String toString(Object key); }### Answer:
@Test public void testToStringNull() { assertNull(KeyUtils.toString(null)); }
@Test public void testToStringBytes() { assertEquals("[1, 2, 3, 4]", KeyUtils.toString(new byte[]{1, 2, 3, 4})); }
@Test public void testToStringString() { assertEquals("[1, 2, 3, 4]", KeyUtils.toString("[1, 2, 3, 4]")); }
@Test public void testToStringProtoStringBytesKeyPair() { assertEquals("KeyPair{ key1=somestring, key2=[1, 23, 43, 5]}", KeyUtils.toString( new KeyPair<>("somestring", new byte[]{1, 23, 43, 5}))); }
@Test public void testToStringProtoByteKeyPairByteKeyTriple() { assertEquals("KeyTriple{ key1=[123, 127, 9, 0], key2=KeyPair{ key1=somestring, key2=[1, 23, 43, 5]}, key3=[0, 0, 0, 0]}", KeyUtils.toString( new KeyTriple<>( new byte[]{123, 127, 9, 0}, new KeyPair<>("somestring", new byte[]{1, 23, 43, 5}), new byte[]{0, 0, 0, 0}))); } |
### Question:
AdminCommandRunner { static void runCommand(String commandName, Class<?> command, String[] commandArgs) throws Exception { final Method mainMethod = command.getMethod("main", String[].class); Preconditions.checkState(Modifier.isStatic(mainMethod.getModifiers()) && Modifier.isPublic(mainMethod.getModifiers()), "#main(String[]) must have public and static modifiers"); final Object[] objects = new Object[1]; objects[0] = commandArgs; try { mainMethod.invoke(null, objects); } catch (final ReflectiveOperationException e) { final Throwable cause = e.getCause() != null ? e.getCause() : e; Throwables.throwIfUnchecked(cause); throw new RuntimeException(String.format("Failed to run '%s' command", commandName), e); } } static void main(String[] args); }### Answer:
@Test public void runCommand() throws Exception { assertFalse(TestCommand.invokedCorrectly); AdminCommandRunner.runCommand("test-command", TestCommand.class, new String[]{"arg0", "arg1"}); assertTrue(TestCommand.invokedCorrectly); } |
### Question:
KeyUtils { public static int hash(Object... keys) { if (null == keys) { return 0; } int result = 1; for (Object key : keys) { result = 31 * result + hashCode(key); } return result; } private KeyUtils(); static boolean equals(Object left, Object right); static int hash(Object... keys); static String toString(Object key); }### Answer:
@Test public void testHashBytes() { assertEquals(918073283, KeyUtils.hash(new byte[]{1, 2, 3, 4, 5, 6})); }
@Test public void testHashBytesAndString() { assertEquals(214780274, KeyUtils.hash(new byte[]{1, 2, 3, 4, 5, 6}, "test hash string")); }
@Test public void testHashBytesAndStringAndNull() { assertEquals(-1931746098, KeyUtils.hash(new byte[]{1, 2, 3, 4, 5, 6}, "test hash string", null)); }
@Test public void testHashString() { assertEquals(1819279604, KeyUtils.hash("test hash string")); }
@Test public void testHashNull() { assertEquals(0, KeyUtils.hash(null)); } |
### Question:
KeyTriple extends AbstractList<Object> implements CompoundKey { @SuppressWarnings("unchecked") public static <K1, K2, K3> KeyTriple<K1, K2, K3> of(List<Object> list) { checkArgument(list.size() == 3, "list should be of size 3, had actually %s elements", list); final K1 value1 = (K1) list.get(0); final K2 value2 = (K2) list.get(1); final K3 value3 = (K3) list.get(2); return new KeyTriple<>(value1, value2, value3); } KeyTriple(K1 key1, K2 key2, K3 key3); @SuppressWarnings("unchecked") static KeyTriple<K1, K2, K3> of(List<Object> list); @Override Object get(int index); @Override int size(); K1 getKey1(); K2 getKey2(); K3 getKey3(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testOf() { if (!valid) { thrown.expect(IllegalArgumentException.class); } final KeyTriple<String, String, String> keyPair = KeyTriple.of(values); assertNotNull(keyPair); assertEquals(values.get(0), keyPair.getKey1()); assertEquals(values.get(1), keyPair.getKey2()); assertEquals(values.get(2), keyPair.getKey3()); assertEquals(values, keyPair); } |
### Question:
ReIndexer implements ReplayHandler { @Override public void put(String tableName, byte[] key, byte[] value) { if (!isIndexed(tableName)) { logger.trace("Ignoring put: {} on table '{}'", key, tableName); return; } final KVStoreTuple<?> keyTuple = keyTuple(tableName, key); final Document document = toDoc(tableName, keyTuple, valueTuple(tableName, value)); if (document != null) { indexManager.getIndex(tableName) .update(keyAsTerm(keyTuple), document); metrics(tableName).puts++; } } ReIndexer(IndexManager indexManager, Map<String, StoreWithId<?, ?>> idToStore); @Override void put(String tableName, byte[] key, byte[] value); @Override void delete(String tableName, byte[] key); }### Answer:
@Test public void add() throws Exception { LuceneSearchIndex index = mock(LuceneSearchIndex.class); final boolean[] added = {false}; doAnswer(invocation -> { added[0] = true; return null; }).when(index).update(any(Term.class), any(Document.class)); when(indexManager.getIndex(same(storeName))) .thenReturn(index); reIndexer.put(storeName, one, two); assertTrue(added[0]); } |
### Question:
ExportProfiles { private static void exportOffline(ExportProfilesOptions options, DACConfig dacConfig) throws Exception { Optional<LocalKVStoreProvider> providerOptional = CmdUtils.getKVStoreProvider(dacConfig.getConfig()); if (!providerOptional.isPresent()) { AdminLogger.log("No database found. Profiles are not exported"); return; } try (LocalKVStoreProvider kvStoreProvider = providerOptional.get()) { kvStoreProvider.start(); exportOffline(options, kvStoreProvider.asLegacy()); } } static void main(String[] args); }### Answer:
@Test public void testOffline() throws Exception { final String tmpPath = folder0.newFolder("testOffline").getAbsolutePath(); final LegacyKVStoreProvider localKVStoreProvider = l(LegacyKVStoreProvider.class); final LegacyKVStoreProvider spy = spy(localKVStoreProvider); Mockito.doNothing().when(spy).close(); final String[] args = {"-o", "--output", tmpPath, "--format", "JSON", "--write-mode", "FAIL_IF_EXISTS"}; final ExportProfiles.ExportProfilesOptions options = getExportOptions(args); ExportProfiles.exportOffline(options, spy); verifyResult(tmpPath, queryProfile, String.join(" ", args)); } |
### Question:
ReIndexer implements ReplayHandler { @Override public void delete(String tableName, byte[] key) { if (!isIndexed(tableName)) { logger.trace("Ignoring delete: {} on table '{}'", key, tableName); return; } indexManager.getIndex(tableName) .deleteDocuments(keyAsTerm(keyTuple(tableName, key))); metrics(tableName).deletes++; } ReIndexer(IndexManager indexManager, Map<String, StoreWithId<?, ?>> idToStore); @Override void put(String tableName, byte[] key, byte[] value); @Override void delete(String tableName, byte[] key); }### Answer:
@Test public void delete() throws Exception { LuceneSearchIndex index = mock(LuceneSearchIndex.class); final boolean[] deleted = {false}; doAnswer(invocation -> { deleted[0] = true; return null; }).when(index).deleteDocuments(any(Term.class)); when(indexManager.getIndex(same(storeName))) .thenReturn(index); reIndexer.delete(storeName, one); assertTrue(deleted[0]); } |
### Question:
TracingKVStore implements KVStore<K, V> { @Override public Document<K, V> get(K key, GetOption... options) { return trace("get", () -> delegate.get(key, options)); } TracingKVStore(String creatorName, Tracer tracer, KVStore<K,V> delegate); static TracingKVStore<K, V> of(String name, Tracer tracer, KVStore<K,V> delegate); @Override Document<K, V> get(K key, GetOption... options); @Override Iterable<Document<K, V>> get(List<K> keys, GetOption... options); @Override boolean contains(K key, ContainsOption... options); @Override Document<K, V> put(K key, V value, PutOption... options); @Override Iterable<Document<K, V>> find(FindOption... options); @Override Iterable<Document<K, V>> find(FindByRange<K> find, FindOption... options); @Override void delete(K key, DeleteOption... options); @Override KVAdmin getAdmin(); @Override String getName(); static final String METHOD_TAG; static final String TABLE_TAG; static final String OPERATION_NAME; static final String CREATOR_TAG; }### Answer:
@Test public void testTypedReturnMethod() { setupLegitParentSpan(); when(delegate.get("myKey")).thenReturn(new TestDocument("myKey","yourValue")); Document<String, String> ret = underTest.get("myKey"); assertEquals("yourValue", ret.getValue()); assertChildSpanMethod("get"); } |
### Question:
TracingKVStore implements KVStore<K, V> { @Override public void delete(K key, DeleteOption... options) { trace("delete", () -> delegate.delete(key, options)); } TracingKVStore(String creatorName, Tracer tracer, KVStore<K,V> delegate); static TracingKVStore<K, V> of(String name, Tracer tracer, KVStore<K,V> delegate); @Override Document<K, V> get(K key, GetOption... options); @Override Iterable<Document<K, V>> get(List<K> keys, GetOption... options); @Override boolean contains(K key, ContainsOption... options); @Override Document<K, V> put(K key, V value, PutOption... options); @Override Iterable<Document<K, V>> find(FindOption... options); @Override Iterable<Document<K, V>> find(FindByRange<K> find, FindOption... options); @Override void delete(K key, DeleteOption... options); @Override KVAdmin getAdmin(); @Override String getName(); static final String METHOD_TAG; static final String TABLE_TAG; static final String OPERATION_NAME; static final String CREATOR_TAG; }### Answer:
@Test public void testVoidReturnMethod() { setupLegitParentSpan(); underTest.delete("byebye"); verify(delegate).delete("byebye"); assertChildSpanMethod("delete"); } |
### Question:
KVStoreOptionUtility { public static void validateOptions(KVStore.KVStoreOption... options) { if (null == options || options.length <= 1) { return; } boolean foundVersion = false; boolean foundCreate = false; for (KVStore.KVStoreOption option : options) { if (option == KVStore.PutOption.CREATE) { if (foundCreate) { throw new IllegalArgumentException("Multiple CREATE PutOptions supplied."); } else { foundCreate = true; } } else if (option instanceof VersionOption) { if (foundVersion) { throw new IllegalArgumentException("Multiple Version PutOptions supplied."); } else { foundVersion = true; } } } if (foundCreate && foundVersion) { throw new IllegalArgumentException("Conflicting PutOptions supplied."); } } static void validateOptions(KVStore.KVStoreOption... options); static Optional<KVStore.PutOption> getCreateOrVersionOption(KVStore.KVStoreOption... options); static void checkIndexPutOptionIsNotUsed(KVStore.KVStoreOption... options); static KVStore.PutOption[] removeIndexPutOption(KVStore.PutOption... options); }### Answer:
@Test public void testValidateOptionsNull() { KVStoreOptionUtility.validateOptions((KVStore.PutOption[]) null); }
@Test public void testValidateOptionsEmpty() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{}); }
@Test public void testValidateOptionsSingleCreate() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{createOption}); }
@Test(expected = IllegalArgumentException.class) public void testValidateOptionsMultipleCreate() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{createOption, createOption}); }
@Test(expected = IllegalArgumentException.class) public void testValidateOptionsMultipleCreateWithIndex() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{createOption, indexPutOption, createOption}); }
@Test public void testValidateOptionsCreateAndIndex() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{createOption, indexPutOption}); }
@Test public void testValidateOptionsIndexAndCreate() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{indexPutOption, createOption}); }
@Test public void testValidateOptionsSingleVersion() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{versionOption}); }
@Test(expected = IllegalArgumentException.class) public void testValidateOptionsMultipleVersion() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{versionOption, versionOption}); }
@Test(expected = IllegalArgumentException.class) public void testValidateOptionsMultipleVersionWithIndex() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{versionOption, indexPutOption, versionOption}); }
@Test public void testValidateOptionsVersionAndIndex() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{versionOption, indexPutOption}); }
@Test public void testValidateOptionsIndexAndVersion() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{indexPutOption, versionOption}); }
@Test(expected = IllegalArgumentException.class) public void testValidateOptionsConflict() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{createOption, versionOption}); }
@Test(expected = IllegalArgumentException.class) public void testValidateOptionsConflictWithIndex() { KVStoreOptionUtility.validateOptions(new KVStore.PutOption[]{indexPutOption, createOption, versionOption}); } |
### Question:
ResetCatalogSearch { static void go(String[] args) throws Exception { final DACConfig dacConfig = DACConfig.newConfig(); parse(args); if (!dacConfig.isMaster) { throw new UnsupportedOperationException("Reset catalog search should be run on master node"); } final Optional<LocalKVStoreProvider> providerOptional = CmdUtils.getKVStoreProvider(dacConfig.getConfig()); if (!providerOptional.isPresent()) { AdminLogger.log("Failed to complete catalog search reset. No KVStore detected."); return; } try (LocalKVStoreProvider provider = providerOptional.get()) { provider.start(); AdminLogger.log("Resetting catalog search..."); final ConfigurationStore configStore = new ConfigurationStore(provider.asLegacy()); configStore.delete(CONFIG_KEY); AdminLogger.log("Catalog search reset will be completed in 1 minute after Dremio starts."); } } static void main(String[] args); }### Answer:
@Test public void testResetCatalogSearchCommand() throws Exception { getCurrentDremioDaemon().close(); ResetCatalogSearch.go(new String[] {}); final Optional<LocalKVStoreProvider> providerOptional = CmdUtils.getKVStoreProvider(getDACConfig().getConfig()); if (!providerOptional.isPresent()) { throw new Exception("No KVStore detected."); } try (LocalKVStoreProvider provider = providerOptional.get()) { provider.start(); final ConfigurationStore configStore = new ConfigurationStore(provider.asLegacy()); final ConfigurationEntry configurationEntry = configStore.get(CONFIG_KEY); assertEquals(configurationEntry, null); } } |
### Question:
KVStoreOptionUtility { public static void checkIndexPutOptionIsNotUsed(KVStore.KVStoreOption... options) { if (null == options || options.length == 0) { return; } for (KVStore.KVStoreOption option : options) { if (option instanceof IndexPutOption) { throw new IllegalArgumentException("IndexPutOption not supported."); } } } static void validateOptions(KVStore.KVStoreOption... options); static Optional<KVStore.PutOption> getCreateOrVersionOption(KVStore.KVStoreOption... options); static void checkIndexPutOptionIsNotUsed(KVStore.KVStoreOption... options); static KVStore.PutOption[] removeIndexPutOption(KVStore.PutOption... options); }### Answer:
@Test public void testIndexPutOptionNotSupportedNull() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(); }
@Test public void testIndexPutOptionNotSupportedEmpty() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{}); }
@Test public void testIndexPutOptionNotSupportedSingleCreate() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{createOption}); }
@Test public void testIndexPutOptionNotSupportedSingleVersion() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{versionOption}); }
@Test public void testIndexPutOptionNotSupportedCreateAndVersion() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{createOption, versionOption}); }
@Test(expected = IllegalArgumentException.class) public void testIndexPutOptionNotSupportedIndexPutOptionFound() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{indexPutOption}); }
@Test(expected = IllegalArgumentException.class) public void testIndexPutOptionNotSupportedIndexPutOptionFoundAmongMany() { KVStoreOptionUtility.checkIndexPutOptionIsNotUsed(new KVStore.PutOption[]{createOption, indexPutOption, versionOption}); } |
### Question:
SystemStoragePluginInitializer implements Initializer<Void> { @VisibleForTesting void createOrUpdateSystemSource(final CatalogService catalogService, final NamespaceService ns, final SourceConfig config) throws Exception { try { config.setAllowCrossSourceSelection(true); final boolean isCreated = catalogService.createSourceIfMissingWithThrow(config); if (isCreated) { return; } } catch (ConcurrentModificationException ex) { logger.info("Two source creations occurred simultaneously, ignoring the failed one.", ex); } final NamespaceKey nsKey = new NamespaceKey(config.getName()); final SourceConfig oldConfig = ns.getSource(nsKey); final SourceConfig updatedConfig = config; updatedConfig .setId(oldConfig.getId()) .setCtime(oldConfig.getCtime()) .setTag(oldConfig.getTag()) .setConfigOrdinal(oldConfig.getConfigOrdinal()); if (oldConfig.equals(updatedConfig)) { return; } ((CatalogServiceImpl) catalogService).getSystemUserCatalog().updateSource(updatedConfig); } @Override Void initialize(BindingProvider provider); }### Answer:
@Test public void refreshSystemPluginsTest() throws Exception { SystemStoragePluginInitializer systemInitializer = new SystemStoragePluginInitializer(); SourceConfig c = new SourceConfig(); InternalFileConf conf = new InternalFileConf(); conf.connection = "classpath: conf.path = "/"; conf.isInternal = false; conf.propertyList = ImmutableList.of(new Property("abc", "bcd"), new Property("def", "123")); c.setName("mytest"); c.setConnectionConf(conf); c.setMetadataPolicy(CatalogService.NEVER_REFRESH_POLICY); systemInitializer.createOrUpdateSystemSource(catalogService, namespaceService, c); final CatalogServiceImpl catalog = (CatalogServiceImpl) catalogService; SourceConfig updatedC = new SourceConfig(); InternalFileConf updatedCConf = new InternalFileConf(); updatedCConf.connection = "file: updatedCConf.path = "/"; updatedCConf.isInternal = true; updatedC.setName("mytest"); updatedC.setConnectionConf(updatedCConf); updatedC.setMetadataPolicy(CatalogService.DEFAULT_METADATA_POLICY); final SourceConfig config = catalog.getManagedSource("mytest").getId().getClonedConfig(); InternalFileConf decryptedConf = (InternalFileConf) reader.getConnectionConf(config); systemInitializer.createOrUpdateSystemSource(catalogService, namespaceService, updatedC); final SourceConfig updatedConfig = catalog.getManagedSource("mytest").getId().getClonedConfig(); InternalFileConf decryptedUpdatedConfig = (InternalFileConf) reader.getConnectionConf(updatedConfig); assertNotNull(decryptedConf.getProperties()); assertEquals(2, decryptedConf.getProperties().size()); assertTrue(decryptedUpdatedConfig.getProperties().isEmpty()); assertNotEquals(config.getMetadataPolicy(), updatedConfig.getMetadataPolicy()); assertNotEquals(decryptedConf.getConnection(), decryptedUpdatedConfig.getConnection()); assertEquals("file: assertNotEquals(decryptedConf.isInternal, decryptedUpdatedConfig.isInternal); assertEquals(decryptedConf.path, decryptedUpdatedConfig.path); assertNotEquals(config.getTag(), updatedConfig.getTag()); SourceConfig updatedC2 = new SourceConfig(); InternalFileConf updatedCConf2 = new InternalFileConf(); updatedCConf2.connection = "file: updatedCConf2.path = "/"; updatedCConf2.isInternal = true; updatedC2.setName("mytest"); updatedC2.setConnectionConf(updatedCConf2); updatedC2.setMetadataPolicy(CatalogService.DEFAULT_METADATA_POLICY); systemInitializer.createOrUpdateSystemSource(catalogService, namespaceService, updatedC2); final SourceConfig updatedConfig2 = catalog.getManagedSource("mytest").getId().getClonedConfig(); InternalFileConf decryptedConf2 = (InternalFileConf) reader.getConnectionConf(updatedConfig2); assertTrue(decryptedConf2.getProperties().isEmpty()); assertEquals(updatedConfig.getTag(), updatedConfig2.getTag()); catalog.deleteSource("mytest"); assertNull(catalog.getManagedSource("myTest")); } |
### Question:
KVStoreOptionUtility { public static Optional<KVStore.PutOption> getCreateOrVersionOption(KVStore.KVStoreOption... options) { validateOptions(options); if (null == options || options.length == 0) { return Optional.empty(); } for (KVStore.KVStoreOption option : options) { if (option == KVStore.PutOption.CREATE) { return Optional.of((KVStore.PutOption) option); } else if (option instanceof VersionOption) { return Optional.of((VersionOption) option); } } return Optional.empty(); } static void validateOptions(KVStore.KVStoreOption... options); static Optional<KVStore.PutOption> getCreateOrVersionOption(KVStore.KVStoreOption... options); static void checkIndexPutOptionIsNotUsed(KVStore.KVStoreOption... options); static KVStore.PutOption[] removeIndexPutOption(KVStore.PutOption... options); }### Answer:
@Test public void testGetCreateOrVersionOptionNull() { final Optional<KVStore.PutOption> ret = KVStoreOptionUtility.getCreateOrVersionOption(); assertFalse(ret.isPresent()); }
@Test public void testGetCreateOrVersionOptionEmpty() { final Optional<KVStore.PutOption> ret = KVStoreOptionUtility.getCreateOrVersionOption(new KVStore.PutOption[]{}); assertFalse(ret.isPresent()); }
@Test public void testGetCreateOrVersionOptionSingleCreate() { final Optional<KVStore.PutOption> ret = KVStoreOptionUtility.getCreateOrVersionOption(new KVStore.PutOption[]{createOption}); assertEquals(createOption, ret.get()); }
@Test public void testGetCreateOrVersionOptionSingleVersion() { final Optional<KVStore.PutOption> ret = KVStoreOptionUtility.getCreateOrVersionOption(new KVStore.PutOption[]{versionOption}); assertEquals(versionOption, ret.get()); }
@Test(expected = IllegalArgumentException.class) public void testGetCreateOrVersionOptionCreateAndVersion() { KVStoreOptionUtility.getCreateOrVersionOption(new KVStore.PutOption[]{createOption, versionOption}); }
@Test public void testGetCreateOrVersionOptionIndexPutOptionFound() { final Optional<KVStore.PutOption> ret = KVStoreOptionUtility.getCreateOrVersionOption(new KVStore.PutOption[]{indexPutOption}); assertFalse(ret.isPresent()); }
@Test(expected = IllegalArgumentException.class) public void testGetCreateOrVersionOptionPutOptionFoundAmongMany() { KVStoreOptionUtility.getCreateOrVersionOption(new KVStore.PutOption[]{createOption, indexPutOption, versionOption}); } |
### Question:
DateUtils { public static long getStartOfLastMonth() { LocalDate now = LocalDate.now(); LocalDate targetDate = now.minusDays(now.getDayOfMonth() - 1).minusMonths(1); Instant instant = targetDate.atStartOfDay().toInstant(ZoneOffset.UTC); return instant.toEpochMilli(); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final LocalDate dateWithinWeek); static LocalDate getMonthStartDate(final LocalDate dateWithinMonth); static LocalDate fromEpochMillis(final long epochMillis); }### Answer:
@Test public void testGetStartOfLastMonth() { LocalDate dateLastMonth = LocalDate.now().minusMonths(1); long startOfLastMonth = DateUtils.getStartOfLastMonth(); LocalDate dateStartOfLastMonth = DateUtils.fromEpochMillis(startOfLastMonth); assertEquals(dateLastMonth.getMonthValue(), dateStartOfLastMonth.getMonthValue()); assertEquals(dateLastMonth.getYear(), dateStartOfLastMonth.getYear()); assertEquals(1, dateStartOfLastMonth.getDayOfMonth()); } |
### Question:
KVStoreOptionUtility { public static KVStore.PutOption[] removeIndexPutOption(KVStore.PutOption... options) { if (null == options) { return null; } return Arrays .stream(options) .filter(option -> !(option instanceof IndexPutOption)) .toArray(KVStore.PutOption[]::new); } static void validateOptions(KVStore.KVStoreOption... options); static Optional<KVStore.PutOption> getCreateOrVersionOption(KVStore.KVStoreOption... options); static void checkIndexPutOptionIsNotUsed(KVStore.KVStoreOption... options); static KVStore.PutOption[] removeIndexPutOption(KVStore.PutOption... options); }### Answer:
@Test public void testRemoveIndexPutOption() { testRemoveIndexPutOptions( new KVStore.PutOption[]{indexPutOption}, new KVStore.PutOption[]{}); } |
### Question:
LegacyProtobufSerializer extends ProtobufSerializer<T> { public static <M extends Message> M parseFrom(Parser<M> parser, ByteString bytes) throws InvalidProtocolBufferException { return rewriteProtostuff(parser.parseFrom(bytes)); } LegacyProtobufSerializer(Class<T> clazz, Parser<T> parser); @Override T revert(byte[] bytes); static M parseFrom(Parser<M> parser, ByteString bytes); static M parseFrom(Parser<M> parser, byte[] bytes); static M parseFrom(Parser<M> parser, ByteBuffer bytes); }### Answer:
@Test public void testParse() throws InvalidProtocolBufferException { final UnknownFieldSet term1 = UnknownFieldSet.newBuilder() .addField(SearchQuery.Term.FIELD_FIELD_NUMBER, Field.newBuilder().addLengthDelimited(ByteString.copyFromUtf8("foo")).build()) .addField(SearchQuery.Term.VALUE_FIELD_NUMBER, Field.newBuilder().addLengthDelimited(ByteString.copyFromUtf8("bar")).build()) .build(); final UnknownFieldSet sq1 = UnknownFieldSet.newBuilder() .addField(SearchQuery.TYPE_FIELD_NUMBER, Field.newBuilder().addVarint(SearchQuery.Type.TERM_VALUE).build()) .addField(SearchQuery.TERM_FIELD_NUMBER, Field.newBuilder().addGroup(term1).build()) .build(); final UnknownFieldSet term2 = UnknownFieldSet.newBuilder() .addField(SearchQuery.Term.FIELD_FIELD_NUMBER, Field.newBuilder().addLengthDelimited(ByteString.copyFromUtf8("foo")).build()) .addField(SearchQuery.Term.VALUE_FIELD_NUMBER, Field.newBuilder().addLengthDelimited(ByteString.copyFromUtf8("baz")).build()) .build(); final UnknownFieldSet sq2 = UnknownFieldSet.newBuilder() .addField(SearchQuery.TYPE_FIELD_NUMBER, Field.newBuilder().addVarint(SearchQuery.Type.TERM_VALUE).build()) .addField(SearchQuery.TERM_FIELD_NUMBER, Field.newBuilder().addGroup(term2).build()) .build(); final UnknownFieldSet bool = UnknownFieldSet.newBuilder() .addField(SearchQuery.Boolean.OP_FIELD_NUMBER, Field.newBuilder().addVarint(SearchQuery.BooleanOp.AND_VALUE).build()) .addField(SearchQuery.Boolean.CLAUSES_FIELD_NUMBER, Field.newBuilder().addGroup(sq1).addGroup(sq2).build()) .build(); final SearchQuery query = SearchQuery.newBuilder() .setType(SearchQuery.Type.BOOLEAN) .setUnknownFields(UnknownFieldSet.newBuilder().addField(SearchQuery.BOOLEAN_FIELD_NUMBER, Field.newBuilder().addGroup(bool).build()).build()) .build(); final SearchQuery expected = SearchQuery.newBuilder() .setType(SearchQuery.Type.BOOLEAN) .setBoolean( SearchQuery.Boolean.newBuilder() .setOp(SearchQuery.BooleanOp.AND) .addClauses(SearchQuery.newBuilder() .setType(SearchQuery.Type.TERM).setTerm(Term.newBuilder().setField("foo").setValue("bar"))) .addClauses(SearchQuery.newBuilder() .setType(SearchQuery.Type.TERM).setTerm(Term.newBuilder().setField("foo").setValue("baz"))) ) .build(); assertThat(LegacyProtobufSerializer.parseFrom(SearchQuery.PARSER, query.toByteString()), is(equalTo(expected))); } |
### Question:
DateUtils { public static LocalDate getLastSundayDate(final LocalDate dateWithinWeek) { int dayOfWeek = dateWithinWeek.getDayOfWeek().getValue(); dayOfWeek = (dayOfWeek == 7) ? 0 : dayOfWeek; return dateWithinWeek.minusDays(dayOfWeek); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final LocalDate dateWithinWeek); static LocalDate getMonthStartDate(final LocalDate dateWithinMonth); static LocalDate fromEpochMillis(final long epochMillis); }### Answer:
@Test public void testGetLastSundayDate() { LocalDate testDate1 = LocalDate.parse("2020-03-29"); LocalDate date1LastSunday = DateUtils.getLastSundayDate(testDate1); assertEquals(testDate1, date1LastSunday); LocalDate testDate2 = LocalDate.parse("2020-03-28"); LocalDate date2LastSunday = DateUtils.getLastSundayDate(testDate2); assertEquals(LocalDate.parse("2020-03-22"), date2LastSunday); } |
### Question:
DependencyGraph { public synchronized void loadFromStore() { for (Map.Entry<ReflectionId, ReflectionDependencies> entry : dependenciesStore.getAll()) { final List<ReflectionDependencyEntry> dependencies = entry.getValue().getEntryList(); if (dependencies == null || dependencies.isEmpty()) { continue; } try { setPredecessors(entry.getKey(), FluentIterable.from(dependencies) .transform(new Function<ReflectionDependencyEntry, DependencyEntry>() { @Override public DependencyEntry apply(ReflectionDependencyEntry entry) { return DependencyEntry.of(entry); } }).toSet()); } catch (DependencyException e) { logger.warn("Found a cyclic dependency while loading dependencies for {}, skipping", entry.getKey().getId(), e); } } } DependencyGraph(DependenciesStore dependenciesStore); synchronized void loadFromStore(); synchronized void setDependencies(final ReflectionId reflectionId, Set<DependencyEntry> dependencies); synchronized void delete(ReflectionId id); }### Answer:
@Test public void testLoadFromStore() throws Exception { final DependenciesStore dependenciesStore = Mockito.mock(DependenciesStore.class); final DependencyGraph graph = new DependencyGraph(dependenciesStore); final Multimap<String, String> dependencyMap = MultimapBuilder.hashKeys().arrayListValues().build(); dependencyMap.put("raw1", "pds1"); dependencyMap.put("raw1", "tablefunction1"); dependencyMap.put("agg1", "raw1"); dependencyMap.put("raw2", "pds2"); dependencyMap.put("raw2", "tablefunction2"); dependencyMap.put("agg2", "raw2"); dependencyMap.put("agg3", "raw2"); dependencyMap.putAll("vds-raw", Lists.newArrayList("raw1", "raw2")); dependencyMap.put("vds-agg1", "vds-raw"); dependencyMap.putAll("vds-agg2", Lists.newArrayList("agg1", "agg2")); Mockito.when(dependenciesStore.getAll()).thenReturn(storeDependencies(dependencyMap).entrySet()); graph.loadFromStore(); for (String dependant : dependencyMap.keySet()) { for (String parent : dependencyMap.get(dependant)) { assertTrue(String.format("%s > %s", parent, dependant), isPredecessor(graph, parent, dependant)); if (dependencyByName.get(parent).getType() == DependencyType.REFLECTION) { assertTrue(String.format("%s < %s", dependant, parent), isSuccessor(graph, parent, dependant)); } } } } |
### Question:
ReflectionGoalChecker { public static boolean checkGoal(ReflectionGoal goal, Materialization materialization) { return Instance.isEqual(goal, materialization.getReflectionGoalVersion()); } ReflectionGoalHash calculateReflectionGoalVersion(ReflectionGoal reflectionGoal); boolean checkHash(ReflectionGoal goal, ReflectionEntry entry); boolean isEqual(ReflectionGoal goal, ReflectionEntry entry); boolean isEqual(ReflectionGoal goal, String version); static boolean checkGoal(ReflectionGoal goal, Materialization materialization); static boolean checkGoal(ReflectionGoal goal, ReflectionEntry entry); static final ReflectionGoalChecker Instance; }### Answer:
@Test public void testMatchesTag() { final String testTag = "testTag"; final ReflectionGoal goal = ReflectionGoal.getDefaultInstance().newMessage() .setTag(testTag); assertTrue(ReflectionGoalChecker.checkGoal(goal, new ReflectionEntry().setGoalVersion(testTag))); }
@Test public void testMatchesVersion() { final String testTag = "1"; final ReflectionGoal goal = ReflectionGoal.getDefaultInstance().newMessage() .setTag("wrongTag") .setVersion(Long.valueOf(testTag)); assertTrue(ReflectionGoalChecker.checkGoal(goal, new ReflectionEntry().setGoalVersion(testTag))); }
@Test public void testMismatchNonNullVersion() { final String testTag = "1"; final ReflectionGoal goal = ReflectionGoal.getDefaultInstance().newMessage() .setTag("wrongTag") .setVersion(0L); assertFalse(ReflectionGoalChecker.checkGoal(goal, new ReflectionEntry().setGoalVersion(testTag))); }
@Test public void testMismatchNullVersion() { final String testTag = "1"; final ReflectionGoal goal = ReflectionGoal.getDefaultInstance().newMessage() .setTag("wrongTag") .setVersion(null); assertFalse(ReflectionGoalChecker.checkGoal(goal, new ReflectionEntry().setGoalVersion(testTag))); } |
### Question:
ReflectionGoalChecker { public boolean checkHash(ReflectionGoal goal, ReflectionEntry entry){ if(null == entry.getReflectionGoalHash()){ return false; } return entry.getReflectionGoalHash().equals(calculateReflectionGoalVersion(goal)); } ReflectionGoalHash calculateReflectionGoalVersion(ReflectionGoal reflectionGoal); boolean checkHash(ReflectionGoal goal, ReflectionEntry entry); boolean isEqual(ReflectionGoal goal, ReflectionEntry entry); boolean isEqual(ReflectionGoal goal, String version); static boolean checkGoal(ReflectionGoal goal, Materialization materialization); static boolean checkGoal(ReflectionGoal goal, ReflectionEntry entry); static final ReflectionGoalChecker Instance; }### Answer:
@Test public void testCheckHashAgainstHash(){ ReflectionGoal goal = new ReflectionGoal(); ReflectionEntry entry = new ReflectionEntry() .setReflectionGoalHash(new ReflectionGoalHash("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")); assertTrue(ReflectionGoalChecker.Instance.checkHash(goal, entry)); }
@Test public void testCheckHashAgainstNullHash(){ ReflectionGoal goal = new ReflectionGoal(); ReflectionEntry entry = new ReflectionEntry(); assertFalse(ReflectionGoalChecker.Instance.checkHash(goal, entry)); } |
### Question:
DateUtils { public static LocalDate getMonthStartDate(final LocalDate dateWithinMonth) { int dayOfMonth = dateWithinMonth.getDayOfMonth(); return dateWithinMonth.minusDays((dayOfMonth - 1)); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final LocalDate dateWithinWeek); static LocalDate getMonthStartDate(final LocalDate dateWithinMonth); static LocalDate fromEpochMillis(final long epochMillis); }### Answer:
@Test public void testGetMonthStartDate() { LocalDate testDate1 = LocalDate.parse("2020-03-01"); LocalDate monthStartDate = DateUtils.getMonthStartDate(testDate1); assertEquals(testDate1, monthStartDate); LocalDate testDate2 = LocalDate.parse("2020-03-31"); LocalDate date2MonthStartDate = DateUtils.getMonthStartDate(testDate2); assertEquals(testDate1, date2MonthStartDate); } |
### Question:
OptionList extends ArrayList<OptionValue> { public void mergeIfNotPresent(OptionList list) { final Set<OptionValue> options = Sets.newTreeSet(this); for (OptionValue optionValue : list) { if (options.add(optionValue)) { this.add(optionValue); } } } void merge(OptionList list); void mergeIfNotPresent(OptionList list); OptionList getSystemOptions(); OptionList getNonSystemOptions(); }### Answer:
@Test public void testMergeOptionLists() { final OptionValue optionValue0 = OptionValue.createBoolean(OptionValue.OptionType.SYSTEM, "test-option0", false); final OptionValue optionValue1 = OptionValue.createLong(OptionValue.OptionType.SYSTEM, "test-option1", 2); final OptionValue optionValue2 = OptionValue.createLong(OptionValue.OptionType.SESSION, "test-option2", 4); final OptionValue optionValue3 = OptionValue.createBoolean(OptionValue.OptionType.SYSTEM, "test-option0", true); final OptionValue optionValue4 = OptionValue.createLong(OptionValue.OptionType.SESSION, "test-option1", 2); final OptionList localList = new OptionList(); localList.add(optionValue0); localList.add(optionValue1); localList.add(optionValue2); final OptionList changedList = new OptionList(); changedList.add(optionValue3); changedList.add(optionValue4); final OptionList expectedList = new OptionList(); expectedList.add(optionValue3); expectedList.add(optionValue4); expectedList.add(optionValue1); expectedList.add(optionValue2); changedList.mergeIfNotPresent(localList); assert changedList.equals(expectedList) : String.format("OptionLists merge incorrectly.\n\nexpected: %s \n\n" + "returned: %s", expectedList, changedList); } |
### Question:
BoundCommandPool implements CommandPool { @Override public <V> CompletableFuture<V> submit(Priority priority, String descriptor, Command<V> command, boolean runInSameThread) { final long time = System.currentTimeMillis(); final CommandWrapper<V> wrapper = new CommandWrapper<>(priority, descriptor, time, command); logger.debug("command {} created", descriptor); if (runInSameThread) { logger.debug("running command {} in the same calling thread", descriptor); wrapper.run(); } else { executorService.execute(wrapper); } return wrapper.getFuture(); } BoundCommandPool(final int poolSize, Tracer tracer); @Override CompletableFuture<V> submit(Priority priority, String descriptor, Command<V> command, boolean runInSameThread); @Override void start(); @Override void close(); }### Answer:
@Test public void testSamePrioritySuppliers() throws Exception { final CommandPool pool = newTestCommandPool(); final BlockingCommand blocking = new BlockingCommand(); pool.submit(CommandPool.Priority.HIGH, "test", blocking, false); Future<Integer> future1 = pool.submit(CommandPool.Priority.HIGH, "test", (waitInMillis) -> counter.getAndIncrement(), false); Thread.sleep(5); Future<Integer> future2 = pool.submit(CommandPool.Priority.HIGH, "test", (waitInMillis) -> counter.getAndIncrement(), false); Thread.sleep(5); Future<Integer> future3 = pool.submit(CommandPool.Priority.HIGH, "test", (waitInMillis) -> counter.getAndIncrement(), false); blocking.unblock(); Assert.assertEquals(0, (int) Futures.getUnchecked(future1)); Assert.assertEquals(1, (int) Futures.getUnchecked(future2)); Assert.assertEquals(2, (int) Futures.getUnchecked(future3)); }
@Test public void testDifferentPrioritySuppliers() { final CommandPool pool = newTestCommandPool(); final BlockingCommand blocking = new BlockingCommand(); pool.submit(CommandPool.Priority.HIGH, "test", blocking, false); Future<Integer> future1 = pool.submit(CommandPool.Priority.LOW, "test", (waitInMillis) -> counter.getAndIncrement(), false); Future<Integer> future2 = pool.submit(CommandPool.Priority.MEDIUM, "test", (waitInMillis) -> counter.getAndIncrement(), false); Future<Integer> future3 = pool.submit(CommandPool.Priority.HIGH, "test", (waitInMillis) -> counter.getAndIncrement(), false); blocking.unblock(); Assert.assertEquals(2, (int) Futures.getUnchecked(future1)); Assert.assertEquals(1, (int) Futures.getUnchecked(future2)); Assert.assertEquals(0, (int) Futures.getUnchecked(future3)); } |
### Question:
PartitionChunkId implements Comparable<PartitionChunkId> { @JsonCreator public static PartitionChunkId of(String partitionChunkId) { final String[] ids = partitionChunkId.split(DELIMITER, 3); Preconditions.checkArgument(ids.length == 3 && !ids[0].isEmpty() && !ids[1].isEmpty() && !ids[2].isEmpty(), "Invalid dataset split id %s", partitionChunkId); long version; try { version = Long.parseLong(ids[1]); } catch (NumberFormatException e) { version = Long.MIN_VALUE; } return new PartitionChunkId(partitionChunkId, unescape(ids[0]), version, ids[2]); } private PartitionChunkId(String compoundSplitId, String datasetId, long splitVersion, String splitKey); @JsonCreator static PartitionChunkId of(String partitionChunkId); static PartitionChunkId of(DatasetConfig config, PartitionChunk split, long splitVersion); static PartitionChunkId of(DatasetConfig config, PartitionChunkMetadata partitionChunkMetadata, long splitVersion); @JsonValue String getSplitId(); @JsonIgnore String getDatasetId(); @JsonIgnore long getSplitVersion(); @JsonIgnore String getSplitIdentifier(); @Override int hashCode(); @Override boolean equals(Object obj); @Override int compareTo(PartitionChunkId that); @Override String toString(); static SearchQuery getSplitsQuery(DatasetConfig datasetConfig); static SearchQuery getSplitsQuery(EntityId datasetId, long splitVersion); static Range<PartitionChunkId> getCurrentSplitRange(DatasetConfig datasetConfig); static Range<PartitionChunkId> getSplitRange(EntityId datasetId, long splitVersion); static Range<PartitionChunkId> getSplitRange(EntityId datasetId, long startSplitVersion, long endSplitVersion); static LegacyFindByRange<PartitionChunkId> getSplitsRange(DatasetConfig datasetConfig); static LegacyFindByRange<PartitionChunkId> getSplitsRange(EntityId datasetId, long splitVersionId); static boolean mayRequireNewDatasetId(DatasetConfig config); static LegacyFindByRange<PartitionChunkId> unsafeGetSplitsRange(DatasetConfig config); }### Answer:
@Test public void testInvalidIdFromString() throws Exception { try { PartitionChunkId split = PartitionChunkId.of("ds1_1"); fail("ds1_1 is an invalid dataset split id"); } catch (IllegalArgumentException e) { } try { PartitionChunkId split = PartitionChunkId.of("ds2_2_"); fail("ds2_2_ is an invalid dataset split id"); } catch (IllegalArgumentException e) { } } |
### Question:
DateUtils { public static LocalDate fromEpochMillis(final long epochMillis) { return Instant.ofEpochMilli(epochMillis).atZone(ZoneOffset.UTC).toLocalDate(); } static long getStartOfLastMonth(); static LocalDate getLastSundayDate(final LocalDate dateWithinWeek); static LocalDate getMonthStartDate(final LocalDate dateWithinMonth); static LocalDate fromEpochMillis(final long epochMillis); }### Answer:
@Test public void testFromEpochMillis() { LocalDate extractedDate = DateUtils.fromEpochMillis(System.currentTimeMillis()); assertEquals(LocalDate.now(), extractedDate); } |
### Question:
DatasetStateMutator { public TransformResult apply(String oldCol, String newCol, ExpressionBase newExp, boolean dropSourceColumn) { return apply(oldCol, newCol, newExp.wrap(), dropSourceColumn); } DatasetStateMutator(String username, VirtualDatasetState virtualDatasetState, boolean preview); void setSql(QueryMetadata metadata); void addColumn(int index, Column column); void addColumn(Column column); void moveColumn(int index, int dest); int columnCount(); void addJoin(Join join); void updateColumnTables(); String uniqueColumnName(String column); String getDatasetAlias(); void groupedBy(List<Column> newColumns, List<Column> groupBys); void addFilter(Filter filter); void setOrdersList(List<Order> columnsList); TransformResult result(); int indexOfCol(String colName); void nest(); TransformResult rename(String oldCol, String newCol); TransformResult apply(String oldCol, String newCol, ExpressionBase newExp, boolean dropSourceColumn); TransformResult apply(String oldCol, String newCol, Expression newExpWrapped, boolean dropSourceColumn); Expression findColValueForModification(String colName); Expression findColValue(String colName); boolean isGrouped(); void dropColumn(String droppedColumnName); }### Answer:
@Test public void testMutatorApplyNoDropNonPreview() { boolean preview = false; TransformResult result = mutator(preview).apply("foo", "foo2", newValue, false); assertEquals(newHashSet("foo2"), result.getAddedColumns()); assertEquals(newHashSet(), result.getModifiedColumns()); assertEquals(newHashSet(), result.getRemovedColumns()); assertColIs(newValue, result, "foo2"); assertColIs(value, result, "foo"); }
@Test public void testMutatorApplyReplaceNonPreview() { boolean preview = false; TransformResult result1 = mutator(preview).apply("foo", "foo", newValue, true); assertEquals(newHashSet(), result1.getAddedColumns()); assertEquals(newHashSet("foo"), result1.getModifiedColumns()); assertEquals(newHashSet(), result1.getRemovedColumns()); assertColIs(null, result1, "foo2"); assertColIs(newValue, result1, "foo"); }
@Test public void testMutatorApplyDropNonPreview() { boolean preview = false; TransformResult result2 = mutator(preview).apply("foo", "foo2", newValue, true); assertEquals(newHashSet("foo2"), result2.getAddedColumns()); assertEquals(newHashSet(), result2.getModifiedColumns()); assertEquals(newHashSet("foo"), result2.getRemovedColumns()); assertColIs(null, result2, "foo"); assertColIs(newValue, result2, "foo2"); }
@Test public void testMutatorApplyNoDropPreview() { boolean preview = true; TransformResult result = mutator(preview).apply("foo", "foo2", newValue, false); assertEquals(newHashSet("foo2"), result.getAddedColumns()); assertEquals(newHashSet(), result.getModifiedColumns()); assertEquals(newHashSet(), result.getRemovedColumns()); assertColIs(newValue, result, "foo2"); assertColIs(value, result, "foo"); }
@Test public void testMutatorApplyReplacePreview() { boolean preview = true; TransformResult result1 = mutator(preview).apply("foo", "foo", newValue, true); assertEquals(newHashSet("foo (new)"), result1.getAddedColumns()); assertEquals(newHashSet(), result1.getModifiedColumns()); assertEquals(newHashSet("foo"), result1.getRemovedColumns()); assertColIs(null, result1, "foo2"); assertColIs(value, result1, "foo"); assertColIs(newValue, result1, "foo (new)"); }
@Test public void testMutatorApplyDropPreview() { boolean preview = true; TransformResult result2 = mutator(preview).apply("foo", "foo2", newValue, true); assertEquals(newHashSet("foo2"), result2.getAddedColumns()); assertEquals(newHashSet(), result2.getModifiedColumns()); assertEquals(newHashSet("foo"), result2.getRemovedColumns()); assertColIs(value, result2, "foo"); assertColIs(newValue, result2, "foo2"); } |
### Question:
PathUtils { public static final String join(final String... parts) { final StringBuilder sb = new StringBuilder(); for (final String part:parts) { Preconditions.checkNotNull(part, "parts cannot contain null"); if (!Strings.isNullOrEmpty(part)) { sb.append(part).append("/"); } } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } final String path = sb.toString(); return normalize(path); } static final String join(final String... parts); static final String normalize(final String path); }### Answer:
@Test(expected = NullPointerException.class) public void testNullSegmentThrowsNPE() { PathUtils.join("", null, ""); }
@Test public void testJoinPreservesAbsoluteOrRelativePaths() { final String actual = PathUtils.join("/a", "/b", "/c"); final String expected = "/a/b/c"; Assert.assertEquals("invalid path", expected, actual); final String actual2 = PathUtils.join("/a", "b", "c"); final String expected2 = "/a/b/c"; Assert.assertEquals("invalid path", expected2, actual2); final String actual3 = PathUtils.join("a", "b", "c"); final String expected3 = "a/b/c"; Assert.assertEquals("invalid path", expected3, actual3); final String actual4 = PathUtils.join("a", "", "c"); final String expected4 = "a/c"; Assert.assertEquals("invalid path", expected4, actual4); final String actual5 = PathUtils.join("", "", "c"); final String expected5 = "c"; Assert.assertEquals("invalid path", expected5, actual5); final String actual6 = PathUtils.join("", "", ""); final String expected6 = ""; Assert.assertEquals("invalid path", expected6, actual6); final String actual7 = PathUtils.join("", "", "/"); final String expected7 = "/"; Assert.assertEquals("invalid path", expected7, actual7); final String actual8 = PathUtils.join("", "", "c/"); final String expected8 = "c/"; Assert.assertEquals("invalid path", expected8, actual8); } |
### Question:
PathUtils { public static final String normalize(final String path) { if (Strings.isNullOrEmpty(Preconditions.checkNotNull(path))) { return path; } final StringBuilder builder = new StringBuilder(); char last = path.charAt(0); builder.append(last); for (int i=1; i<path.length(); i++) { char cur = path.charAt(i); if (last == '/' && cur == last) { continue; } builder.append(cur); last = cur; } return builder.toString(); } static final String join(final String... parts); static final String normalize(final String path); }### Answer:
@Test public void testNormalizeRemovesRedundantForwardSlashes() { final String actual = PathUtils.normalize("/a/b/c"); final String expected = "/a/b/c"; Assert.assertEquals("invalid path", expected, actual); final String actual2 = PathUtils.normalize(" final String expected2 = "/a/b/c"; Assert.assertEquals("invalid path", expected2, actual2); final String actual3 = PathUtils.normalize(" final String expected3 = "/"; Assert.assertEquals("invalid path", expected3, actual3); final String actual4 = PathUtils.normalize("/a"); final String expected4 = "/a"; Assert.assertEquals("invalid path", expected4, actual4); final String actual5 = PathUtils.normalize(" final String expected5 = "/"; Assert.assertEquals("invalid path", expected5, actual5); final String actual6 = PathUtils.normalize(""); final String expected6 = ""; Assert.assertEquals("invalid path", expected6, actual6); } |
### Question:
QueueProcessor implements AutoCloseable { public QueueProcessor(String name, Supplier<AutoCloseableLock> lockSupplier, Consumer<T> consumer) { this.name = name; this.lockSupplier = lockSupplier; this.consumer = consumer; this.queue = new LinkedBlockingQueue<>(); this.workerThread = null; this.isClosed = false; this.completed = true; } QueueProcessor(String name, Supplier<AutoCloseableLock> lockSupplier, Consumer<T> consumer); void enqueue(T event); void start(); @VisibleForTesting boolean completed(); void close(); }### Answer:
@Test public void testQueueProcessor() throws Exception { Pointer<Long> counter = new Pointer<>(0L); final ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock(); Lock readLock = rwlock.readLock(); Lock writeLock = rwlock.writeLock(); QueueProcessor<Long> qp = new QueueProcessor<>("queue-processor", () -> new AutoCloseableLock(writeLock).open(), (i) -> counter.value += i); qp.start(); final long totalCount = 100_000; final long numBatches = 10; final long batchCount = totalCount / numBatches; for (long i = 0; i < totalCount; i++) { qp.enqueue(new Long(i)); if (i % batchCount == (batchCount - 1)) { Thread.sleep(1); } } final long timeout = 5_000; long loopCount = 0; long expectedValue = totalCount * (totalCount - 1) / 2; while (getValue(counter, readLock) != expectedValue) { Thread.sleep(1); assertTrue(String.format("Timed out after %d ms", timeout), loopCount++ < timeout); } qp.close(); } |
### Question:
JmxConfigurator extends ReporterConfigurator { @Override public void configureAndStart(String name, MetricRegistry registry, MetricFilter filter) { reporter = JmxReporter.forRegistry(registry).convertRatesTo(rateUnit).convertDurationsTo(durationUnit).filter(filter).build(); reporter.start(); } @JsonCreator JmxConfigurator(
@JsonProperty("rate") TimeUnit rateUnit,
@JsonProperty("duration") TimeUnit durationUnit); @Override void configureAndStart(String name, MetricRegistry registry, MetricFilter filter); @Override int hashCode(); @Override boolean equals(Object other); @Override void close(); }### Answer:
@Test public void testConfigureAndStart() throws IOException, InterruptedException, MalformedObjectNameException { final MetricRegistry metrics = new MetricRegistry(); metrics.counter(NAME, () -> { Counter counter = new Counter(); counter.inc(1234); return counter; }); final JmxConfigurator configurator = new JmxConfigurator(TimeUnit.SECONDS, TimeUnit.MILLISECONDS); configurator.configureAndStart("test", metrics, new MetricFilter() { @Override public boolean matches(String s, Metric metric) { return true; } }); final Set<ObjectInstance> beans = ManagementFactory.getPlatformMBeanServer().queryMBeans(new ObjectName(OBJECT_NAME), null); assertEquals(1, beans.size()); assertEquals(OBJECT_NAME, beans.iterator().next().getObjectName().getCanonicalName()); } |
### Question:
LocalSchedulerService implements SchedulerService { @Override public void close() throws Exception { LOGGER.info("Stopping SchedulerService"); AutoCloseables.close(AutoCloseables.iter(executorService), taskLeaderElectionServiceMap.values()); LOGGER.info("Stopped SchedulerService"); } LocalSchedulerService(int corePoolSize); LocalSchedulerService(int corePoolSize,
Provider<ClusterCoordinator> clusterCoordinatorProvider,
Provider<CoordinationProtos.NodeEndpoint> currentNode,
boolean assumeTaskLeadership); @VisibleForTesting LocalSchedulerService(CloseableSchedulerThreadPool executorService,
Provider<ClusterCoordinator> clusterCoordinatorProvider,
Provider<CoordinationProtos.NodeEndpoint> currentNode,
boolean assumeTaskLeadership); @VisibleForTesting CloseableSchedulerThreadPool getExecutorService(); @Override void close(); @Override void start(); @Override Cancellable schedule(Schedule schedule, Runnable task); }### Answer:
@Test public void close() throws Exception { final CloseableSchedulerThreadPool executorService = mock(CloseableSchedulerThreadPool.class); final LocalSchedulerService service = new LocalSchedulerService(executorService, null, null, false); service.close(); verify(executorService).close(); } |
### Question:
LocalSchedulerService implements SchedulerService { @VisibleForTesting public CloseableSchedulerThreadPool getExecutorService() { return executorService; } LocalSchedulerService(int corePoolSize); LocalSchedulerService(int corePoolSize,
Provider<ClusterCoordinator> clusterCoordinatorProvider,
Provider<CoordinationProtos.NodeEndpoint> currentNode,
boolean assumeTaskLeadership); @VisibleForTesting LocalSchedulerService(CloseableSchedulerThreadPool executorService,
Provider<ClusterCoordinator> clusterCoordinatorProvider,
Provider<CoordinationProtos.NodeEndpoint> currentNode,
boolean assumeTaskLeadership); @VisibleForTesting CloseableSchedulerThreadPool getExecutorService(); @Override void close(); @Override void start(); @Override Cancellable schedule(Schedule schedule, Runnable task); }### Answer:
@Test public void newThread() { LocalSchedulerService service = new LocalSchedulerService(1); final Runnable runnable = mock(Runnable.class); final Thread thread = service.getExecutorService().getThreadFactory().newThread(runnable); assertTrue("thread should be a daemon thread", thread.isDaemon()); assertTrue("thread name should start with scheduler-", thread.getName().startsWith("scheduler-")); } |
### Question:
IncludesExcludesFilter implements MetricFilter { @Override public boolean matches(String name, Metric metric) { if (includes.isEmpty() || matches(name, includes)) { return allowedViaExcludes(name); } return false; } IncludesExcludesFilter(List<String> includes, List<String> excludes); @Override boolean matches(String name, Metric metric); @Override int hashCode(); @Override boolean equals(Object other); }### Answer:
@Test public void onlyExclude() { IncludesExcludesFilter f = new IncludesExcludesFilter(Arrays.asList(), Arrays.asList("a.*")); assertFalse(f.matches("alpha", null)); assertTrue(f.matches("beta", null)); }
@Test public void onlyInclude() { IncludesExcludesFilter f = new IncludesExcludesFilter(Arrays.asList("a.*"), Arrays.asList()); assertTrue(f.matches("alpha", null)); assertFalse(f.matches("beta", null)); }
@Test public void includeAndExclude() { IncludesExcludesFilter f = new IncludesExcludesFilter(Arrays.asList("a.*"), Arrays.asList("a\\.b.*")); assertTrue(f.matches("a.alpha", null)); assertFalse(f.matches("a.beta", null)); }
@Test public void noValues() { IncludesExcludesFilter f = new IncludesExcludesFilter(Arrays.asList(), Arrays.asList()); assertTrue(f.matches(null, null)); } |
### Question:
MutableVarcharVector extends BaseVariableWidthVector { @Override public void close() { this.clear(); } MutableVarcharVector(String name, BufferAllocator allocator, double compactionThreshold); MutableVarcharVector(String name, FieldType fieldType, BufferAllocator allocator, double compactionThreshold); final void setCompactionThreshold(double in); final boolean needsCompaction(); final int getCurrentOffset(); final int getGarbageSizeInBytes(); final int getUsedByteCapacity(); @Override FieldReader getReader(); @Override MinorType getMinorType(); void zeroVector(); void reset(); @Override void close(); @Override void clear(); byte[] get(int index); Text getObject(int index); void get(int index, NullableVarCharHolder holder); void copyFrom(int fromIndex, int thisIndex, VarCharVector from); void copyFromSafe(int fromIndex, int thisIndex, VarCharVector from); void compact(); void forceCompact(); void set(int index, VarCharHolder holder); void setSafe(int index, VarCharHolder holder); void set(int index, NullableVarCharHolder holder); void setSafe(int index, NullableVarCharHolder holder); void set(int index, Text text); void setSafe(int index, Text text); void set(int index, byte[] value); void setSafe(int index, byte[] value); void set(int index, byte[] value, int start, int length); void setSafe(int index, byte[] value, int start, int length); void set(int index, ByteBuffer value, int start, int length); void setSafe(int index, ByteBuffer value, int start, int length); void set(int index, int isSet, int start, int end, ArrowBuf buffer); void setSafe(int index, int isSet, int start, int end, ArrowBuf buffer); void set(int index, int start, int length, ArrowBuf buffer); void setSafe(int index, int start, int length, ArrowBuf buffer); void copyToVarchar(VarCharVector in, final int from, final int to); boolean isIndexSafe(int index); @Override TransferPair getTransferPair(String ref, BufferAllocator allocator); @Override TransferPair makeTransferPair(ValueVector to); }### Answer:
@Test public void TestInterleavedMidToSmall() { LinkedList<String> l1 = GetRandomStringList(TOTAL_STRINGS, midAvgSize); LinkedList<String> l2 = GetRandomStringList(TOTAL_STRINGS, smallAvgSize); final double threshold = 1.0D; System.out.println("TestInterleavedMidToSmall: threshold: " + threshold + " (only forcecompact)"); MutableVarcharVector m1 = new MutableVarcharVector("TestInterleavedMidToSmall", testAllocator, threshold ); try { TestInterLeaved(m1, l1, l2); } finally { m1.close(); } }
@Test public void TestInterleavedSmallToMid() { LinkedList<String> l1 = GetRandomStringList(TOTAL_STRINGS, smallAvgSize); LinkedList<String> l2 = GetRandomStringList(TOTAL_STRINGS, midAvgSize); final double threshold = 1.0D; System.out.println("TestInterleavedSmallToMid: threshold: " + threshold + " (only forcecompact)"); MutableVarcharVector m1 = new MutableVarcharVector("TestInterleavedSmallToMid", testAllocator, 1.0 ); try { TestInterLeaved(m1, l1, l2); } finally { m1.close(); } } |
### Question:
UserRPCServer extends BasicServer<RpcType, UserRPCServer.UserClientConnectionImpl> { @Override protected Response handle(UserClientConnectionImpl connection, int rpcType, byte[] pBody, ByteBuf dBody) throws RpcException { throw new IllegalStateException("UserRPCServer#handle must not be invoked without ResponseSender"); } @VisibleForTesting UserRPCServer(
RpcConfig rpcConfig,
Provider<UserService> userServiceProvider,
Provider<NodeEndpoint> nodeEndpointProvider,
WorkIngestor workIngestor,
Provider<UserWorker> worker,
BufferAllocator allocator,
EventLoopGroup eventLoopGroup,
InboundImpersonationManager impersonationManager,
Tracer tracer,
OptionValidatorListing optionValidatorListing
); UserRPCServer(
RpcConfig rpcConfig,
Provider<UserService> userServiceProvider,
Provider<NodeEndpoint> nodeEndpointProvider,
Provider<UserWorker> worker,
BufferAllocator allocator,
EventLoopGroup eventLoopGroup,
InboundImpersonationManager impersonationManager,
Tracer tracer,
OptionValidatorListing optionValidatorListing
); @Override UserClientConnectionImpl initRemoteConnection(SocketChannel channel); }### Answer:
@Test public void testHandlePassesNoopTracesByDefault() throws RpcException { setup(false); server.handle(connection, GET_CATALOGS_VALUE, pBody, dBody, responseSender); verify(ingestor).feedWork(eq(connection), eq(GET_CATALOGS_VALUE), eq(pBody), eq(dBody), captorSender.capture()); assertEquals(tracer.finishedSpans().size(), 0); verifySendResponse(0); }
@Test public void testHandleCreatesSpansFromTracerWhenTracingEnabled() throws RpcException { setup(true); server.handle(connection, GET_SCHEMAS_VALUE, pBody, dBody, responseSender); verify(ingestor).feedWork(eq(connection), eq(GET_SCHEMAS_VALUE), eq(pBody), eq(dBody), captorSender.capture()); assertEquals(tracer.finishedSpans().size(), 0); verifySendResponse(1); assertEquals("GET_SCHEMAS", tracer.finishedSpans().get(0).tags().get("rpc_type")); }
@Test public void testHandleSpansWhileSendingFailure() throws RpcException { setup(true); server.handle(connection, GET_CATALOGS_VALUE, pBody, dBody, responseSender); verify(ingestor).feedWork(eq(connection), eq(GET_CATALOGS_VALUE), eq(pBody), eq(dBody), captorSender.capture()); assertEquals(tracer.finishedSpans().size(), 0); UserRpcException r = mock(UserRpcException.class); verifyZeroInteractions(responseSender); captorSender.getValue().sendFailure(r); verify(responseSender).sendFailure(r); assertEquals(1, tracer.finishedSpans().size()); assertEquals("GET_CATALOGS", tracer.finishedSpans().get(0).tags().get("rpc_type")); }
@Test public void testHandleFinishesSpanIfFeedFailure() throws RpcException { WorkIngestor ingest = (con, rpc, pb, db, sender) -> { throw new RpcException(); }; setup(ingest, true); try { server.handle(connection, CANCEL_QUERY_VALUE, pBody, dBody, responseSender); } catch (RpcException e) { } assertEquals(1, tracer.finishedSpans().size()); assertEquals("CANCEL_QUERY", tracer.finishedSpans().get(0).tags().get("rpc_type")); } |
### Question:
QueriesClerk { QueriesClerk(final WorkloadTicketDepot workloadTicketDepot) { this.workloadTicketDepot = workloadTicketDepot; } QueriesClerk(final WorkloadTicketDepot workloadTicketDepot); void buildAndStartQuery(final PlanFragmentFull firstFragment, final SchedulingInfo schedulingInfo,
final QueryStarter queryStarter); FragmentTicket newFragmentTicket(final QueryTicket queryTicket, final PlanFragmentFull fragment, final SchedulingInfo schedulingInfo); }### Answer:
@Test public void testQueriesClerk() throws Exception{ WorkloadTicketDepot ticketDepot = new WorkloadTicketDepot(mockedRootAlloc, mock(SabotConfig.class), DUMMY_GROUP_MANAGER); QueriesClerk clerk = makeClerk(ticketDepot); assertLivePhasesCount(clerk, 0); int baseNumAllocators = getNumAllocators(); UserBitShared.QueryId queryId = UserBitShared.QueryId.newBuilder().setPart1(12).setPart2(23).build(); QueryTicketGetter qtg1 = new QueryTicketGetter(); clerk.buildAndStartQuery(getDummyPlan(queryId,1,0), getDummySchedulingInfo(), qtg1); QueryTicket queryTicket = qtg1.getObtainedTicket(); assertNotNull(queryTicket); assertLivePhasesCount(clerk, 0); assertEquals(baseNumAllocators + 1, getNumAllocators()); FragmentTicket ticket10 = clerk .newFragmentTicket(queryTicket, getDummyPlan(queryId,1,0), getDummySchedulingInfo()); assertLivePhasesCount(clerk, 1); assertEquals(baseNumAllocators + 2, getNumAllocators()); FragmentTicket ticket11 = clerk .newFragmentTicket(queryTicket, getDummyPlan(queryId,1,1), getDummySchedulingInfo()); assertLivePhasesCount(clerk, 1); assertEquals(baseNumAllocators + 2, getNumAllocators()); FragmentTicket ticket20 = clerk .newFragmentTicket(queryTicket, getDummyPlan(queryId,2,0), getDummySchedulingInfo()); assertLivePhasesCount(clerk, 2); assertEquals(baseNumAllocators + 3, getNumAllocators()); qtg1.close(); assertEquals(baseNumAllocators + 3, getNumAllocators()); ticket10.close(); assertLivePhasesCount(clerk, 2); assertEquals(baseNumAllocators + 3, getNumAllocators()); ticket20.close(); assertLivePhasesCount(clerk, 1); assertEquals(baseNumAllocators + 2, getNumAllocators()); ticket11.close(); assertLivePhasesCount(clerk, 0); assertEquals(baseNumAllocators, getNumAllocators()); AutoCloseables.close(ticketDepot); } |
### Question:
QueriesClerk { Collection<FragmentTicket> getFragmentTickets(QueryId queryId) { List<FragmentTicket> fragmentTickets = new ArrayList<>(); for (WorkloadTicket workloadTicket : getWorkloadTickets()) { QueryTicket queryTicket = workloadTicket.getQueryTicket(queryId); if (queryTicket != null) { for (PhaseTicket phaseTicket : queryTicket.getActivePhaseTickets()) { fragmentTickets.addAll(phaseTicket.getFragmentTickets()); } break; } } return fragmentTickets; } QueriesClerk(final WorkloadTicketDepot workloadTicketDepot); void buildAndStartQuery(final PlanFragmentFull firstFragment, final SchedulingInfo schedulingInfo,
final QueryStarter queryStarter); FragmentTicket newFragmentTicket(final QueryTicket queryTicket, final PlanFragmentFull fragment, final SchedulingInfo schedulingInfo); }### Answer:
@Test public void testGetFragmentTickets() throws Exception { WorkloadTicketDepot ticketDepot = new WorkloadTicketDepot(mockedRootAlloc, mock(SabotConfig.class), DUMMY_GROUP_MANAGER); QueriesClerk clerk = makeClerk(ticketDepot); UserBitShared.QueryId queryId = UserBitShared.QueryId.newBuilder().setPart1(12).setPart2(23).build(); QueryTicketGetter qtg1 = new QueryTicketGetter(); clerk.buildAndStartQuery(getDummyPlan(queryId,1,0), getDummySchedulingInfo(), qtg1); QueryTicket queryTicket = qtg1.getObtainedTicket(); assertNotNull(queryTicket); Set<FragmentTicket> expected = new HashSet<>(); int numMajors = 3; int numMinors = 5; for (int i = 0; i < numMajors; ++i) { for (int j = 0; j < numMinors; ++j) { FragmentTicket fragmentTicket = clerk .newFragmentTicket(queryTicket, getDummyPlan(queryId, i, j), getDummySchedulingInfo()); expected.add(fragmentTicket); } } qtg1.close(); Collection<FragmentTicket> actual = clerk.getFragmentTickets(queryId); assertEquals(expected.size(), actual.size()); assertTrue(expected.containsAll(actual)); for (FragmentTicket ticket : expected) { ticket.close(); } AutoCloseables.close(ticketDepot); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.