target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@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(); }
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; }
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; } }
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(); }
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); }
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); }
@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(); }
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; }
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; } }
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(); }
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); }
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); }
@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(); }
@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 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 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); }
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); }
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); }
@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(); }
@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 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 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); }
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); }
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); }
@Test public void scan() { CamelCaseDetector detector = new CamelCaseDetector(0.3); assertThat(detector.scan("isDog() or isCat()")).isOne(); assertThat(detector.scan("String name;")).isZero(); }
@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 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 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); }
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); }
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); }
@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(); }
@CheckForNull public static Node nodeAttribute(Node node, String attribute) { NamedNodeMap attributes = node.getAttributes(); if (attributes == null) { return null; } return attributes.getNamedItem(attribute); }
XmlFile { @CheckForNull public static Node nodeAttribute(Node node, String attribute) { NamedNodeMap attributes = node.getAttributes(); if (attributes == null) { return null; } return attributes.getNamedItem(attribute); } }
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); }
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); }
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); }
@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); }
@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 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 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); }
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); }
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); }
@Test public void isLineOfCode() { CodeRecognizer cr = new CodeRecognizer(0.8, new FakeFootprint()); assertThat(cr.isLineOfCode("}")).isTrue(); assertThat(cr.isLineOfCode("squid")).isFalse(); }
public final boolean isLineOfCode(String line) { return recognition(line) - threshold > 0; }
CodeRecognizer { public final boolean isLineOfCode(String line) { return recognition(line) - threshold > 0; } }
CodeRecognizer { public final boolean isLineOfCode(String line) { return recognition(line) - threshold > 0; } CodeRecognizer(double threshold, LanguageFootprint language); }
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); }
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); }
@Test public void extractCodeLines() { CodeRecognizer cr = new CodeRecognizer(0.8, new FakeFootprint()); assertThat(cr.extractCodeLines(Arrays.asList("{", "squid"))).containsOnly("{"); }
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 { 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 { 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); }
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); }
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); }
@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(); }
public synchronized void cancel() { thread.interrupt(); join(); }
ProgressReport implements Runnable { public synchronized void cancel() { thread.interrupt(); join(); } }
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); }
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(); }
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(); }
@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>"); }
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); } }
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); } } }
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(); }
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); }
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); }
@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(); }
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); } }
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); } } }
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(); }
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); }
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); }
@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"); }
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); } }
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); } } }
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); } } }
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); } } }
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); } } }
@Test(expected = IllegalArgumentException.class) public void invalid_json() { new JsonParser().parse("{{}"); }
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); } }
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); } } }
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); } } }
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); } } }
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); } } }
@Test public void load_profile_keys() { NewBuiltInQualityProfile newProfile = testContext.createBuiltInQualityProfile(PROFILE_NAME, LANGUAGE); BuiltInQualityProfileJsonLoader.load(newProfile, REPOSITORY_KEY, PROFILE_PATH); newProfile.done(); BuiltInQualityProfile profile = testContext.profile(LANGUAGE, PROFILE_NAME); List<BuiltInActiveRule> activeRules = profile.rules(); assertThat(activeRules).hasSize(2); assertThat(profile.rule(RuleKey.of(REPOSITORY_KEY, "S100"))).isNotNull(); assertThat(profile.rule(RuleKey.of(REPOSITORY_KEY, "S110"))).isNotNull(); assertThat(profile.rule(RuleKey.of(REPOSITORY_KEY, "S123"))).isNull(); assertThat(profile.rule(RuleKey.of(REPOSITORY_KEY, "S666"))).isNull(); }
public static void load(NewBuiltInQualityProfile profile, String repositoryKey, String jsonProfilePath) { Set<String> activeKeys = loadActiveKeysFromJsonProfile(jsonProfilePath); for (String activeKey : activeKeys) { profile.activateRule(repositoryKey, activeKey); } }
BuiltInQualityProfileJsonLoader { public static void load(NewBuiltInQualityProfile profile, String repositoryKey, String jsonProfilePath) { Set<String> activeKeys = loadActiveKeysFromJsonProfile(jsonProfilePath); for (String activeKey : activeKeys) { profile.activateRule(repositoryKey, activeKey); } } }
BuiltInQualityProfileJsonLoader { public static void load(NewBuiltInQualityProfile profile, String repositoryKey, String jsonProfilePath) { Set<String> activeKeys = loadActiveKeysFromJsonProfile(jsonProfilePath); for (String activeKey : activeKeys) { profile.activateRule(repositoryKey, activeKey); } } private BuiltInQualityProfileJsonLoader(); }
BuiltInQualityProfileJsonLoader { public static void load(NewBuiltInQualityProfile profile, String repositoryKey, String jsonProfilePath) { Set<String> activeKeys = loadActiveKeysFromJsonProfile(jsonProfilePath); for (String activeKey : activeKeys) { profile.activateRule(repositoryKey, activeKey); } } private BuiltInQualityProfileJsonLoader(); static void load(NewBuiltInQualityProfile profile, String repositoryKey, String jsonProfilePath); static Set<String> loadActiveKeysFromJsonProfile(String profilePath); }
BuiltInQualityProfileJsonLoader { public static void load(NewBuiltInQualityProfile profile, String repositoryKey, String jsonProfilePath) { Set<String> activeKeys = loadActiveKeysFromJsonProfile(jsonProfilePath); for (String activeKey : activeKeys) { profile.activateRule(repositoryKey, activeKey); } } private BuiltInQualityProfileJsonLoader(); static void load(NewBuiltInQualityProfile profile, String repositoryKey, String jsonProfilePath); static Set<String> loadActiveKeysFromJsonProfile(String profilePath); }
@Test public void testMaxTaskVersion() { DACConfig dacConfig = DACConfig.newConfig(); Upgrade upgrade = new Upgrade(dacConfig, CLASSPATH_SCAN_RESULT, false); final Optional<Version> tasksGreatestMaxVersion = upgrade.getUpgradeTasks().stream() .filter((v) -> v instanceof LegacyUpgradeTask) .map((v) -> ((LegacyUpgradeTask)v).getMaxVersion() ) .max(UPGRADE_VERSION_ORDERING); assertTrue( String.format("One task has a newer version (%s) than the current server version (%s)", tasksGreatestMaxVersion.get(), VERSION), UPGRADE_VERSION_ORDERING.compare(tasksGreatestMaxVersion.get(), VERSION) <= 0); }
@VisibleForTesting List<? extends UpgradeTask> getUpgradeTasks() { return upgradeTasks; }
Upgrade { @VisibleForTesting List<? extends UpgradeTask> getUpgradeTasks() { return upgradeTasks; } }
Upgrade { @VisibleForTesting List<? extends UpgradeTask> getUpgradeTasks() { return upgradeTasks; } Upgrade(DACConfig dacConfig, ScanResult classPathScan, boolean verbose); }
Upgrade { @VisibleForTesting List<? extends UpgradeTask> getUpgradeTasks() { return upgradeTasks; } Upgrade(DACConfig dacConfig, ScanResult classPathScan, boolean verbose); void run(); void run(boolean noDBOpenRetry); @VisibleForTesting void validateUpgrade(final LegacyKVStoreProvider storeProvider, final String curEdition); void run(final LegacyKVStoreProvider storeProvider); static void main(String[] args); }
Upgrade { @VisibleForTesting List<? extends UpgradeTask> getUpgradeTasks() { return upgradeTasks; } Upgrade(DACConfig dacConfig, ScanResult classPathScan, boolean verbose); void run(); void run(boolean noDBOpenRetry); @VisibleForTesting void validateUpgrade(final LegacyKVStoreProvider storeProvider, final String curEdition); void run(final LegacyKVStoreProvider storeProvider); static void main(String[] args); static final Comparator<Version> UPGRADE_VERSION_ORDERING; }
@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()); }
@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)); }
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)); } }
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); }
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); }
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); }
@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()); }
@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)); }
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)); } }
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); }
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); }
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); }
@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()); }
@DELETE @Path("/{id}") public Response deleteReflection(@PathParam("id") String id) { reflectionServiceHelper.removeReflection(id); return Response.ok().build(); }
ReflectionResource { @DELETE @Path("/{id}") public Response deleteReflection(@PathParam("id") String id) { reflectionServiceHelper.removeReflection(id); return Response.ok().build(); } }
ReflectionResource { @DELETE @Path("/{id}") public Response deleteReflection(@PathParam("id") String id) { reflectionServiceHelper.removeReflection(id); return Response.ok().build(); } @Inject ReflectionResource(ReflectionServiceHelper reflectionServiceHelper, CatalogServiceHelper catalogServiceHelper); }
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); }
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); }
@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()); }
@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; }
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; } }
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); }
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); }
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); }
@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()); }
@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); } }
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); } } }
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); }
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); }
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); }
@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()); }
@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); } }
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); } } }
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); }
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); }
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); }
@Test public void testUpdateSourceErrors() throws Exception { SourceConfig sourceConfig = new SourceConfig(); sourceConfig.setName("Foopy5"); 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); expectStatus(Response.Status.NOT_FOUND, getBuilder(getPublicAPI(3).path(SOURCES_PATH).path("badid")).buildPut(Entity.entity(updatedSource, JSON))); updatedSource.setTag("badtag"); expectStatus(Response.Status.CONFLICT, getBuilder(getPublicAPI(3).path(SOURCES_PATH).path(createdSourceConfig.getId().getId())).buildPut(Entity.entity(updatedSource, JSON))); deleteSource(updatedSource.getName()); }
@DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); }
SourceResource { @DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); } }
SourceResource { @DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); }
SourceResource { @DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); } @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); }
SourceResource { @DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); } @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); }
@Test public void testUpdateSourceBoundaryValues() 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.getMetadataPolicy().setDatasetRefreshAfterMs(MetadataPolicy.ONE_MINUTE_IN_MS); updatedSource.getMetadataPolicy().setAuthTTLMs(MetadataPolicy.ONE_MINUTE_IN_MS); updatedSource.getMetadataPolicy().setNamesRefreshMs(MetadataPolicy.ONE_MINUTE_IN_MS); SourceResource.SourceDeprecated source = expectSuccess(getBuilder(getPublicAPI(3).path(SOURCES_PATH).path(createdSourceConfig.getId().getId())).buildPut(Entity.entity(updatedSource, JSON)), SourceResource.SourceDeprecated.class); assertEquals(source.getMetadataPolicy().getAuthTTLMs(), updatedSource.getMetadataPolicy().getAuthTTLMs()); assertEquals(source.getMetadataPolicy().getDatasetRefreshAfterMs(), updatedSource.getMetadataPolicy().getDatasetRefreshAfterMs()); assertEquals(source.getMetadataPolicy().getNamesRefreshMs(), updatedSource.getMetadataPolicy().getNamesRefreshMs()); deleteSource(createdSourceConfig.getName()); }
@DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); }
SourceResource { @DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); } }
SourceResource { @DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); }
SourceResource { @DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); } @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); }
SourceResource { @DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); } @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); }
@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()); }
@GET @RolesAllowed({"admin", "user"}) @Path("/{id}") public SourceDeprecated getSource(@PathParam("id") String id) throws NamespaceException { SourceConfig sourceConfig = sourceService.getById(id); return fromSourceConfig(sourceConfig); }
SourceResource { @GET @RolesAllowed({"admin", "user"}) @Path("/{id}") public SourceDeprecated getSource(@PathParam("id") String id) throws NamespaceException { SourceConfig sourceConfig = sourceService.getById(id); return fromSourceConfig(sourceConfig); } }
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); }
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); }
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); }
@Test public void testDeleteSource() throws Exception { SourceConfig sourceConfig = new SourceConfig(); sourceConfig.setName("Foopy3"); NASConf nasConfig = new NASConf(); sourceConfig.setType(nasConfig.getType()); nasConfig.path = "/"; sourceConfig.setConfig(nasConfig.toBytesString()); SourceConfig createdSourceConfig = newSourceService().registerSourceWithRuntime(sourceConfig); expectSuccess(getBuilder(getPublicAPI(3).path(SOURCES_PATH).path(createdSourceConfig.getId().getId())).buildDelete()); }
@DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); }
SourceResource { @DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); } }
SourceResource { @DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); }
SourceResource { @DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); } @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); }
SourceResource { @DELETE @RolesAllowed("admin") @Path("/{id}") public Response deleteSource(@PathParam("id") String id) throws NamespaceException { SourceConfig config = sourceService.getById(id); sourceService.deleteSource(config); return Response.ok().build(); } @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); }
@Test public void testPost460Version() throws Exception { final Version version = new Version("4.6.1", 4, 6, 1, 0, ""); assertFalse(SetTableauDefaults.updateOptionsIfNeeded(version, () -> optionManager, true)); }
@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 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 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(); }
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); }
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); }
@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); }
@VisibleForTesting protected SourceDeprecated fromSourceConfig(SourceConfig sourceConfig) { return new SourceDeprecated(sourceService.fromSourceConfig(sourceConfig)); }
SourceResource { @VisibleForTesting protected SourceDeprecated fromSourceConfig(SourceConfig sourceConfig) { return new SourceDeprecated(sourceService.fromSourceConfig(sourceConfig)); } }
SourceResource { @VisibleForTesting protected SourceDeprecated fromSourceConfig(SourceConfig sourceConfig) { return new SourceDeprecated(sourceService.fromSourceConfig(sourceConfig)); } @Inject SourceResource(SourceService sourceService, SabotContext sabotContext); }
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); }
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); }
@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)); } } }
@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)); } }
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)); } } }
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); }
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); }
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); }
@Test public void testActiveUserStats() { EditionProvider editionProvider = mock(EditionProvider.class); when(editionProvider.getEdition()).thenReturn("oss-test"); LocalDate now = LocalDate.now(); List<JobSummary> testJobResults = new ArrayList<>(); testJobResults.add(newJob("testuser1", QueryType.ODBC, now)); testJobResults.add(newJob("testuser1", QueryType.ODBC, now)); testJobResults.add(newJob("testuser1", QueryType.UI_PREVIEW, now)); testJobResults.add(newJob("testuser2", QueryType.ODBC, now)); testJobResults.add(newJob("testuser1", QueryType.ODBC, DateUtils.getLastSundayDate(now))); testJobResults.add(newJob("testuser1", QueryType.ODBC, DateUtils.getLastSundayDate(now))); testJobResults.add(newJob("testuser1", QueryType.UI_PREVIEW, DateUtils.getLastSundayDate(now))); testJobResults.add(newJob("testuser2", QueryType.ODBC, DateUtils.getLastSundayDate(now))); testJobResults.add(newJob("testuser1", QueryType.ODBC, DateUtils.getMonthStartDate(now))); testJobResults.add(newJob("testuser1", QueryType.ODBC, DateUtils.getMonthStartDate(now))); testJobResults.add(newJob("testuser1", QueryType.UI_PREVIEW, DateUtils.getMonthStartDate(now))); testJobResults.add(newJob("testuser2", QueryType.ODBC, DateUtils.getMonthStartDate(now))); testJobResults.add(newJob("testuser1", QueryType.ODBC, DateUtils.getMonthStartDate(now.minusMonths(1)))); testJobResults.add(newJob("testuser1", QueryType.ODBC, DateUtils.getMonthStartDate(now.minusMonths(1)))); testJobResults.add(newJob("testuser1", QueryType.UI_PREVIEW, DateUtils.getMonthStartDate(now.minusMonths(1)))); testJobResults.add(newJob("testuser2", QueryType.ODBC, DateUtils.getMonthStartDate(now.minusMonths(1)))); JobsService jobsService = mock(JobsService.class); when(jobsService.searchJobs(any(SearchJobsRequest.class))).thenReturn(testJobResults); UserStatsResource resource = new UserStatsResource(jobsService, editionProvider); UserStats stats = resource.getActiveUserStats(); List<Map<String, Object>> statsByDate = stats.getUserStatsByDate(); Map<String, Object> firstDateEntry = fetchDateEntry("date", now.toString(), statsByDate); assertEquals(1, firstDateEntry.get("UI_PREVIEW")); assertEquals(2, firstDateEntry.get("ODBC")); assertEquals(2, firstDateEntry.get("total")); Map<String, Object> secondDateEntry = fetchDateEntry("date", DateUtils.getLastSundayDate(now).toString(), statsByDate); assertEquals(1, secondDateEntry.get("UI_PREVIEW")); assertEquals(2, secondDateEntry.get("ODBC")); assertEquals(2, secondDateEntry.get("total")); Map<String, Object> weekDateEntry = fetchDateEntry("week", DateUtils.getLastSundayDate(now).toString(), stats.getUserStatsByWeek()); assertEquals(1, weekDateEntry.get("UI_PREVIEW")); assertEquals(2, weekDateEntry.get("ODBC")); assertEquals(2, weekDateEntry.get("total")); Map<String, Object> monthDateEntry = fetchDateEntry("month", DateUtils.getMonthStartDate(now).toString(), stats.getUserStatsByMonth()); assertEquals(1, monthDateEntry.get("UI_PREVIEW")); assertEquals(2, monthDateEntry.get("ODBC")); assertEquals(2, monthDateEntry.get("total")); Map<String, Object> lastMonthEntry = fetchDateEntry("month", DateUtils.getMonthStartDate(now.minusMonths(1)).toString(), stats.getUserStatsByMonth()); assertEquals(1, lastMonthEntry.get("UI_PREVIEW")); assertEquals(2, lastMonthEntry.get("ODBC")); assertEquals(2, lastMonthEntry.get("total")); }
@GET public UserStats getActiveUserStats() { try { final UserStats.Builder activeUserStats = new UserStats.Builder(); activeUserStats.setEdition(editionProvider.getEdition()); final SearchJobsRequest request = SearchJobsRequest.newBuilder() .setFilterString(String.format(FILTER, getStartOfLastMonth(), System.currentTimeMillis())) .build(); final Iterable<JobSummary> resultantJobs = jobsService.searchJobs(request); for (JobSummary job : resultantJobs) { activeUserStats.addUserStat(job.getStartTime(), job.getQueryType().name(), job.getUser()); } return activeUserStats.build(); } catch (Exception e) { logger.error("Error while computing active user stats", e); throw new InternalServerErrorException(e); } }
UserStatsResource { @GET public UserStats getActiveUserStats() { try { final UserStats.Builder activeUserStats = new UserStats.Builder(); activeUserStats.setEdition(editionProvider.getEdition()); final SearchJobsRequest request = SearchJobsRequest.newBuilder() .setFilterString(String.format(FILTER, getStartOfLastMonth(), System.currentTimeMillis())) .build(); final Iterable<JobSummary> resultantJobs = jobsService.searchJobs(request); for (JobSummary job : resultantJobs) { activeUserStats.addUserStat(job.getStartTime(), job.getQueryType().name(), job.getUser()); } return activeUserStats.build(); } catch (Exception e) { logger.error("Error while computing active user stats", e); throw new InternalServerErrorException(e); } } }
UserStatsResource { @GET public UserStats getActiveUserStats() { try { final UserStats.Builder activeUserStats = new UserStats.Builder(); activeUserStats.setEdition(editionProvider.getEdition()); final SearchJobsRequest request = SearchJobsRequest.newBuilder() .setFilterString(String.format(FILTER, getStartOfLastMonth(), System.currentTimeMillis())) .build(); final Iterable<JobSummary> resultantJobs = jobsService.searchJobs(request); for (JobSummary job : resultantJobs) { activeUserStats.addUserStat(job.getStartTime(), job.getQueryType().name(), job.getUser()); } return activeUserStats.build(); } catch (Exception e) { logger.error("Error while computing active user stats", e); throw new InternalServerErrorException(e); } } @Inject UserStatsResource(JobsService jobsService, EditionProvider editionProvider); }
UserStatsResource { @GET public UserStats getActiveUserStats() { try { final UserStats.Builder activeUserStats = new UserStats.Builder(); activeUserStats.setEdition(editionProvider.getEdition()); final SearchJobsRequest request = SearchJobsRequest.newBuilder() .setFilterString(String.format(FILTER, getStartOfLastMonth(), System.currentTimeMillis())) .build(); final Iterable<JobSummary> resultantJobs = jobsService.searchJobs(request); for (JobSummary job : resultantJobs) { activeUserStats.addUserStat(job.getStartTime(), job.getQueryType().name(), job.getUser()); } return activeUserStats.build(); } catch (Exception e) { logger.error("Error while computing active user stats", e); throw new InternalServerErrorException(e); } } @Inject UserStatsResource(JobsService jobsService, EditionProvider editionProvider); @GET UserStats getActiveUserStats(); }
UserStatsResource { @GET public UserStats getActiveUserStats() { try { final UserStats.Builder activeUserStats = new UserStats.Builder(); activeUserStats.setEdition(editionProvider.getEdition()); final SearchJobsRequest request = SearchJobsRequest.newBuilder() .setFilterString(String.format(FILTER, getStartOfLastMonth(), System.currentTimeMillis())) .build(); final Iterable<JobSummary> resultantJobs = jobsService.searchJobs(request); for (JobSummary job : resultantJobs) { activeUserStats.addUserStat(job.getStartTime(), job.getQueryType().name(), job.getUser()); } return activeUserStats.build(); } catch (Exception e) { logger.error("Error while computing active user stats", e); throw new InternalServerErrorException(e); } } @Inject UserStatsResource(JobsService jobsService, EditionProvider editionProvider); @GET UserStats getActiveUserStats(); }
@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()); }
@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; }
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; } }
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 ); }
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); }
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); }
@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())); }
@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; }
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; } }
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 ); }
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); }
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); }
@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); }
@GET public ResponseList<? extends CatalogItem> listTopLevelCatalog(@QueryParam("include") final List<String> include) { return new ResponseList<>(catalogServiceHelper.getTopLevelCatalogItems(include)); }
CatalogResource { @GET public ResponseList<? extends CatalogItem> listTopLevelCatalog(@QueryParam("include") final List<String> include) { return new ResponseList<>(catalogServiceHelper.getTopLevelCatalogItems(include)); } }
CatalogResource { @GET public ResponseList<? extends CatalogItem> listTopLevelCatalog(@QueryParam("include") final List<String> include) { return new ResponseList<>(catalogServiceHelper.getTopLevelCatalogItems(include)); } @Inject CatalogResource(CatalogServiceHelper catalogServiceHelper); }
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); }
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); }
@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()); }
@GET @Path("/{id}") public User getUser(@PathParam("id") String id) throws UserNotFoundException { return User.fromUser(userGroupService.getUser(new UID(id))); }
UserResource { @GET @Path("/{id}") public User getUser(@PathParam("id") String id) throws UserNotFoundException { return User.fromUser(userGroupService.getUser(new UID(id))); } }
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); }
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); }
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); }
@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()); }
@GET @Path("/{id}") public User getUser(@PathParam("id") String id) throws UserNotFoundException { return User.fromUser(userGroupService.getUser(new UID(id))); }
UserResource { @GET @Path("/{id}") public User getUser(@PathParam("id") String id) throws UserNotFoundException { return User.fromUser(userGroupService.getUser(new UID(id))); } }
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); }
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); }
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); }
@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()); }
@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); }
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); } }
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); }
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); }
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); }
@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(); }
@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); }
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); } }
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); }
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); }
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); }
@Test public void testPost4x0Version() throws Exception { final Version version = new Version("5.2.0", 5, 2, 0, 0, ""); assertFalse(SetTableauDefaults.updateOptionsIfNeeded(version, () -> optionManager, true)); }
@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 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 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(); }
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); }
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); }
@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()); }
@GET @Path("/by-name/{name}") public User getUserByName(@PathParam("name") String name) throws UserNotFoundException { return User.fromUser(userGroupService.getUser(name)); }
UserResource { @GET @Path("/by-name/{name}") public User getUserByName(@PathParam("name") String name) throws UserNotFoundException { return User.fromUser(userGroupService.getUser(name)); } }
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); }
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); }
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); }
@Test public void testGetEdition() { UserStats.Builder stats = new UserStats.Builder(); stats.setEdition("oss"); String expected = "dremio-oss-" + DremioVersionInfo.getVersion(); assertEquals(expected, stats.build().getEdition()); }
public String getEdition() { return edition; }
UserStats { public String getEdition() { return edition; } }
UserStats { public String getEdition() { return edition; } }
UserStats { public String getEdition() { return edition; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); }
UserStats { public String getEdition() { return edition; } String getEdition(); List<Map<String, Object>> getUserStatsByDate(); List<Map<String, Object>> getUserStatsByWeek(); List<Map<String, Object>> getUserStatsByMonth(); }
@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")); }
public List<Map<String, Object>> getUserStatsByDate() { return userStatsByDate; }
UserStats { public List<Map<String, Object>> getUserStatsByDate() { return userStatsByDate; } }
UserStats { public List<Map<String, Object>> getUserStatsByDate() { return userStatsByDate; } }
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(); }
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(); }
@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")); }
public List<Map<String, Object>> getUserStatsByWeek() { return userStatsByWeek; }
UserStats { public List<Map<String, Object>> getUserStatsByWeek() { return userStatsByWeek; } }
UserStats { public List<Map<String, Object>> getUserStatsByWeek() { return userStatsByWeek; } }
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(); }
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(); }
@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")); }
public List<Map<String, Object>> getUserStatsByMonth() { return userStatsByMonth; }
UserStats { public List<Map<String, Object>> getUserStatsByMonth() { return userStatsByMonth; } }
UserStats { public List<Map<String, Object>> getUserStatsByMonth() { return userStatsByMonth; } }
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(); }
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(); }
@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)); }
@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); }
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); } }
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); } }
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); }
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); }
@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)); }
@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); }
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); } }
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); } }
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); }
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); }
@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()); }
@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 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 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); }
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(); }
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(); }
@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); } }
@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())); }
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())); } }
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())); } }
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); }
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); }
@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(); }
@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())); }
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())); } }
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())); } }
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); }
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); }
@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())); }
@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 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 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(); }
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); }
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); }
@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); }
@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())); }
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())); } }
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())); } }
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); }
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); }
@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())); }
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 { 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 { 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); }
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); }
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); }
@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); }
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); }
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); } }
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); } }
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); }
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); }
@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); }
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); }
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); } }
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); } }
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); }
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); }
@Test public void testGetMetricsTableHandlesNotRegisteredMetrics() throws IOException { OperatorProfile op = OperatorProfile .newBuilder().addMetric( UserBitShared.MetricValue.newBuilder() .setMetricId(1) .setDoubleValue(200)) .addMetric( UserBitShared.MetricValue.newBuilder() .setMetricId(3) .setDoubleValue(21)) .setOperatorId(UserBitShared.CoreOperatorType.PARQUET_ROW_GROUP_SCAN.getNumber()) .build(); ImmutablePair<OperatorProfile, Integer> pair = new ImmutablePair<>(op, 1); OperatorWrapper ow = new OperatorWrapper(1, ImmutableList.of(pair), OperatorMetricRegistry.getCoreOperatorTypeMetricsMap(), HashBasedTable.create(), new HashSet<>()); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final JsonGenerator jsonGenerator = new JsonFactory().createGenerator(outputStream); jsonGenerator.writeStartObject(); ow.addMetrics(jsonGenerator); jsonGenerator.writeEndObject(); jsonGenerator.flush(); final JsonElement element = new JsonParser().parse(outputStream.toString()); final int size = element.getAsJsonObject().get("metrics").getAsJsonObject().get("data").getAsJsonArray().get(0).getAsJsonArray().size(); assertEquals(2, size); }
public void addMetrics(JsonGenerator generator) throws IOException { if (operatorType == null) { return; } final Integer[] metricIds = OperatorMetricRegistry.getMetricIds(coreOperatorTypeMetricsMap, operatorType.getNumber()); if (metricIds.length == 0) { return; } generator.writeFieldName("metrics"); final String[] metricsTableColumnNames = new String[metricIds.length + 1]; metricsTableColumnNames[0] = "Thread"; Map<Integer, Integer> metricIdToMetricTableColumnIndex = new HashMap<Integer, Integer>(); int i = 1; for (final int metricId : metricIds) { Optional<MetricDef> metric = OperatorMetricRegistry.getMetricById(coreOperatorTypeMetricsMap, operatorType.getNumber(), metricId); assert metric.isPresent(); metricIdToMetricTableColumnIndex.put(metricId, i - 1); metricsTableColumnNames[i++] = metric.get().getName(); } final JsonBuilder builder = new JsonBuilder(generator, metricsTableColumnNames); for (final ImmutablePair<OperatorProfile, Integer> ip : ops) { builder.startEntry(); final OperatorProfile op = ip.getLeft(); builder.appendString( new OperatorPathBuilder() .setMajor(major) .setMinor(ip.getRight()) .setOperator(op) .build()); final boolean isHashAgg = operatorType.getNumber() == CoreOperatorType.HASH_AGGREGATE_VALUE; final boolean toSkip = isHashAgg && renderingOldProfiles(op); final Number[] values = new Number[metricIds.length]; for (final MetricValue metric : op.getMetricList()) { int metricId = metric.getMetricId(); if (toSkip) { metricId = HashAggStats.getCorrectOrdinalForOlderProfiles(metricId); if (metric.hasLongValue()) { values[metricId] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[metricId] = metric.getDoubleValue(); } } else { Optional<Integer> columnIndex = Optional.ofNullable(metricIdToMetricTableColumnIndex.get(metric.getMetricId())); columnIndex.ifPresent(index -> { if (metric.hasLongValue()) { values[index] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[index] = metric.getDoubleValue(); } }); } } int count = 0; for (final Number value : values) { if (value != null) { if (isHashAgg && metricsTableColumnNames[count].contains("TIME")) { builder.appendNanosWithUnit(value.longValue()); } else { builder.appendFormattedNumber(value); } } else { builder.appendString(""); } count++; } builder.endEntry(); } builder.end(); }
OperatorWrapper { public void addMetrics(JsonGenerator generator) throws IOException { if (operatorType == null) { return; } final Integer[] metricIds = OperatorMetricRegistry.getMetricIds(coreOperatorTypeMetricsMap, operatorType.getNumber()); if (metricIds.length == 0) { return; } generator.writeFieldName("metrics"); final String[] metricsTableColumnNames = new String[metricIds.length + 1]; metricsTableColumnNames[0] = "Thread"; Map<Integer, Integer> metricIdToMetricTableColumnIndex = new HashMap<Integer, Integer>(); int i = 1; for (final int metricId : metricIds) { Optional<MetricDef> metric = OperatorMetricRegistry.getMetricById(coreOperatorTypeMetricsMap, operatorType.getNumber(), metricId); assert metric.isPresent(); metricIdToMetricTableColumnIndex.put(metricId, i - 1); metricsTableColumnNames[i++] = metric.get().getName(); } final JsonBuilder builder = new JsonBuilder(generator, metricsTableColumnNames); for (final ImmutablePair<OperatorProfile, Integer> ip : ops) { builder.startEntry(); final OperatorProfile op = ip.getLeft(); builder.appendString( new OperatorPathBuilder() .setMajor(major) .setMinor(ip.getRight()) .setOperator(op) .build()); final boolean isHashAgg = operatorType.getNumber() == CoreOperatorType.HASH_AGGREGATE_VALUE; final boolean toSkip = isHashAgg && renderingOldProfiles(op); final Number[] values = new Number[metricIds.length]; for (final MetricValue metric : op.getMetricList()) { int metricId = metric.getMetricId(); if (toSkip) { metricId = HashAggStats.getCorrectOrdinalForOlderProfiles(metricId); if (metric.hasLongValue()) { values[metricId] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[metricId] = metric.getDoubleValue(); } } else { Optional<Integer> columnIndex = Optional.ofNullable(metricIdToMetricTableColumnIndex.get(metric.getMetricId())); columnIndex.ifPresent(index -> { if (metric.hasLongValue()) { values[index] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[index] = metric.getDoubleValue(); } }); } } int count = 0; for (final Number value : values) { if (value != null) { if (isHashAgg && metricsTableColumnNames[count].contains("TIME")) { builder.appendNanosWithUnit(value.longValue()); } else { builder.appendFormattedNumber(value); } } else { builder.appendString(""); } count++; } builder.endEntry(); } builder.end(); } }
OperatorWrapper { public void addMetrics(JsonGenerator generator) throws IOException { if (operatorType == null) { return; } final Integer[] metricIds = OperatorMetricRegistry.getMetricIds(coreOperatorTypeMetricsMap, operatorType.getNumber()); if (metricIds.length == 0) { return; } generator.writeFieldName("metrics"); final String[] metricsTableColumnNames = new String[metricIds.length + 1]; metricsTableColumnNames[0] = "Thread"; Map<Integer, Integer> metricIdToMetricTableColumnIndex = new HashMap<Integer, Integer>(); int i = 1; for (final int metricId : metricIds) { Optional<MetricDef> metric = OperatorMetricRegistry.getMetricById(coreOperatorTypeMetricsMap, operatorType.getNumber(), metricId); assert metric.isPresent(); metricIdToMetricTableColumnIndex.put(metricId, i - 1); metricsTableColumnNames[i++] = metric.get().getName(); } final JsonBuilder builder = new JsonBuilder(generator, metricsTableColumnNames); for (final ImmutablePair<OperatorProfile, Integer> ip : ops) { builder.startEntry(); final OperatorProfile op = ip.getLeft(); builder.appendString( new OperatorPathBuilder() .setMajor(major) .setMinor(ip.getRight()) .setOperator(op) .build()); final boolean isHashAgg = operatorType.getNumber() == CoreOperatorType.HASH_AGGREGATE_VALUE; final boolean toSkip = isHashAgg && renderingOldProfiles(op); final Number[] values = new Number[metricIds.length]; for (final MetricValue metric : op.getMetricList()) { int metricId = metric.getMetricId(); if (toSkip) { metricId = HashAggStats.getCorrectOrdinalForOlderProfiles(metricId); if (metric.hasLongValue()) { values[metricId] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[metricId] = metric.getDoubleValue(); } } else { Optional<Integer> columnIndex = Optional.ofNullable(metricIdToMetricTableColumnIndex.get(metric.getMetricId())); columnIndex.ifPresent(index -> { if (metric.hasLongValue()) { values[index] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[index] = metric.getDoubleValue(); } }); } } int count = 0; for (final Number value : values) { if (value != null) { if (isHashAgg && metricsTableColumnNames[count].contains("TIME")) { builder.appendNanosWithUnit(value.longValue()); } else { builder.appendFormattedNumber(value); } } else { builder.appendString(""); } count++; } builder.endEntry(); } builder.end(); } OperatorWrapper(int major, List<ImmutablePair<OperatorProfile, Integer>> ops, CoreOperatorTypeMetricsMap coreOperatorTypeMetricsMap, Table<Integer, Integer, String> majorMinorHostTable, Set<HostProcessingRate> hostProcessingRateSet); }
OperatorWrapper { public void addMetrics(JsonGenerator generator) throws IOException { if (operatorType == null) { return; } final Integer[] metricIds = OperatorMetricRegistry.getMetricIds(coreOperatorTypeMetricsMap, operatorType.getNumber()); if (metricIds.length == 0) { return; } generator.writeFieldName("metrics"); final String[] metricsTableColumnNames = new String[metricIds.length + 1]; metricsTableColumnNames[0] = "Thread"; Map<Integer, Integer> metricIdToMetricTableColumnIndex = new HashMap<Integer, Integer>(); int i = 1; for (final int metricId : metricIds) { Optional<MetricDef> metric = OperatorMetricRegistry.getMetricById(coreOperatorTypeMetricsMap, operatorType.getNumber(), metricId); assert metric.isPresent(); metricIdToMetricTableColumnIndex.put(metricId, i - 1); metricsTableColumnNames[i++] = metric.get().getName(); } final JsonBuilder builder = new JsonBuilder(generator, metricsTableColumnNames); for (final ImmutablePair<OperatorProfile, Integer> ip : ops) { builder.startEntry(); final OperatorProfile op = ip.getLeft(); builder.appendString( new OperatorPathBuilder() .setMajor(major) .setMinor(ip.getRight()) .setOperator(op) .build()); final boolean isHashAgg = operatorType.getNumber() == CoreOperatorType.HASH_AGGREGATE_VALUE; final boolean toSkip = isHashAgg && renderingOldProfiles(op); final Number[] values = new Number[metricIds.length]; for (final MetricValue metric : op.getMetricList()) { int metricId = metric.getMetricId(); if (toSkip) { metricId = HashAggStats.getCorrectOrdinalForOlderProfiles(metricId); if (metric.hasLongValue()) { values[metricId] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[metricId] = metric.getDoubleValue(); } } else { Optional<Integer> columnIndex = Optional.ofNullable(metricIdToMetricTableColumnIndex.get(metric.getMetricId())); columnIndex.ifPresent(index -> { if (metric.hasLongValue()) { values[index] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[index] = metric.getDoubleValue(); } }); } } int count = 0; for (final Number value : values) { if (value != null) { if (isHashAgg && metricsTableColumnNames[count].contains("TIME")) { builder.appendNanosWithUnit(value.longValue()); } else { builder.appendFormattedNumber(value); } } else { builder.appendString(""); } count++; } builder.endEntry(); } builder.end(); } OperatorWrapper(int major, List<ImmutablePair<OperatorProfile, Integer>> ops, CoreOperatorTypeMetricsMap coreOperatorTypeMetricsMap, Table<Integer, Integer, String> majorMinorHostTable, Set<HostProcessingRate> hostProcessingRateSet); String getDisplayName(); String getId(); void addSummary(TableBuilder tb); void addOperator(JsonGenerator generator); void addInfo(JsonGenerator generator); void addMetrics(JsonGenerator generator); void addDetails(JsonGenerator generator); }
OperatorWrapper { public void addMetrics(JsonGenerator generator) throws IOException { if (operatorType == null) { return; } final Integer[] metricIds = OperatorMetricRegistry.getMetricIds(coreOperatorTypeMetricsMap, operatorType.getNumber()); if (metricIds.length == 0) { return; } generator.writeFieldName("metrics"); final String[] metricsTableColumnNames = new String[metricIds.length + 1]; metricsTableColumnNames[0] = "Thread"; Map<Integer, Integer> metricIdToMetricTableColumnIndex = new HashMap<Integer, Integer>(); int i = 1; for (final int metricId : metricIds) { Optional<MetricDef> metric = OperatorMetricRegistry.getMetricById(coreOperatorTypeMetricsMap, operatorType.getNumber(), metricId); assert metric.isPresent(); metricIdToMetricTableColumnIndex.put(metricId, i - 1); metricsTableColumnNames[i++] = metric.get().getName(); } final JsonBuilder builder = new JsonBuilder(generator, metricsTableColumnNames); for (final ImmutablePair<OperatorProfile, Integer> ip : ops) { builder.startEntry(); final OperatorProfile op = ip.getLeft(); builder.appendString( new OperatorPathBuilder() .setMajor(major) .setMinor(ip.getRight()) .setOperator(op) .build()); final boolean isHashAgg = operatorType.getNumber() == CoreOperatorType.HASH_AGGREGATE_VALUE; final boolean toSkip = isHashAgg && renderingOldProfiles(op); final Number[] values = new Number[metricIds.length]; for (final MetricValue metric : op.getMetricList()) { int metricId = metric.getMetricId(); if (toSkip) { metricId = HashAggStats.getCorrectOrdinalForOlderProfiles(metricId); if (metric.hasLongValue()) { values[metricId] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[metricId] = metric.getDoubleValue(); } } else { Optional<Integer> columnIndex = Optional.ofNullable(metricIdToMetricTableColumnIndex.get(metric.getMetricId())); columnIndex.ifPresent(index -> { if (metric.hasLongValue()) { values[index] = metric.getLongValue(); } else if (metric.hasDoubleValue()) { values[index] = metric.getDoubleValue(); } }); } } int count = 0; for (final Number value : values) { if (value != null) { if (isHashAgg && metricsTableColumnNames[count].contains("TIME")) { builder.appendNanosWithUnit(value.longValue()); } else { builder.appendFormattedNumber(value); } } else { builder.appendString(""); } count++; } builder.endEntry(); } builder.end(); } OperatorWrapper(int major, List<ImmutablePair<OperatorProfile, Integer>> ops, CoreOperatorTypeMetricsMap coreOperatorTypeMetricsMap, Table<Integer, Integer, String> majorMinorHostTable, Set<HostProcessingRate> hostProcessingRateSet); String getDisplayName(); String getId(); void addSummary(TableBuilder tb); void addOperator(JsonGenerator generator); void addInfo(JsonGenerator generator); void addMetrics(JsonGenerator generator); void addDetails(JsonGenerator generator); static final String[] OPERATOR_COLUMNS; static final String[] OPERATORS_OVERVIEW_COLUMNS; static final String[] SPLIT_INFO_COLUMNS; static final String[] HOST_METRICS_COLUMNS; static final String[] SLOW_IO_INFO_COLUMNS; }
@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)); }
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"; } }
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"; } } }
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"; } } }
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"; } } }
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"; } } }
@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()); }
@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() ); }
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() ); } }
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() ); } }
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); }
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); }
@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()); }
@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() ); }
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() ); } }
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() ); } }
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); }
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); }
@Test public void testToBuf() { JobProtobuf.JobAttempt resultJobAttempt = toBuf(jobAttemptProtostuff); assertEquals(resultJobAttempt, jobAttemptProtobuf); JobProtobuf.JobFailureInfo jobFailureInfo = toBuf(jobFailureInfoProtoStuff); assertEquals(jobFailureInfoProtoBuf, jobFailureInfo); JobProtobuf.JobCancellationInfo jobCancellationInfo = toBuf(jobCancellationInfoProtoStuff); assertNotEquals(jobCancellationInfoProtobuf, jobCancellationInfo); }
private static <M extends GeneratedMessageV3, T extends Message<T> & Schema<T>> M toBuf(Parser<M> protobufParser, T protostuff) { try { LinkedBuffer buffer = LinkedBuffer.allocate(); byte[] bytes = ProtobufIOUtil.toByteArray(protostuff, protostuff.cachedSchema(), buffer); return LegacyProtobufSerializer.parseFrom(protobufParser, bytes); } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException("Cannot convert from protostuff to protobuf"); } }
JobsProtoUtil { private static <M extends GeneratedMessageV3, T extends Message<T> & Schema<T>> M toBuf(Parser<M> protobufParser, T protostuff) { try { LinkedBuffer buffer = LinkedBuffer.allocate(); byte[] bytes = ProtobufIOUtil.toByteArray(protostuff, protostuff.cachedSchema(), buffer); return LegacyProtobufSerializer.parseFrom(protobufParser, bytes); } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException("Cannot convert from protostuff to protobuf"); } } }
JobsProtoUtil { private static <M extends GeneratedMessageV3, T extends Message<T> & Schema<T>> M toBuf(Parser<M> protobufParser, T protostuff) { try { LinkedBuffer buffer = LinkedBuffer.allocate(); byte[] bytes = ProtobufIOUtil.toByteArray(protostuff, protostuff.cachedSchema(), buffer); return LegacyProtobufSerializer.parseFrom(protobufParser, bytes); } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException("Cannot convert from protostuff to protobuf"); } } private JobsProtoUtil(); }
JobsProtoUtil { private static <M extends GeneratedMessageV3, T extends Message<T> & Schema<T>> M toBuf(Parser<M> protobufParser, T protostuff) { try { LinkedBuffer buffer = LinkedBuffer.allocate(); byte[] bytes = ProtobufIOUtil.toByteArray(protostuff, protostuff.cachedSchema(), buffer); return LegacyProtobufSerializer.parseFrom(protobufParser, bytes); } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException("Cannot convert from protostuff to protobuf"); } } 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); }
JobsProtoUtil { private static <M extends GeneratedMessageV3, T extends Message<T> & Schema<T>> M toBuf(Parser<M> protobufParser, T protostuff) { try { LinkedBuffer buffer = LinkedBuffer.allocate(); byte[] bytes = ProtobufIOUtil.toByteArray(protostuff, protostuff.cachedSchema(), buffer); return LegacyProtobufSerializer.parseFrom(protobufParser, bytes); } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException("Cannot convert from protostuff to protobuf"); } } 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); }
@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); }
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; }
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; } }
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(); }
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); }
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); }
@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)); }
@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 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 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(); }
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(); }
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(); }
@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)); }
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 { 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 { 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); }
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(); }
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(); }
@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)); }
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 { 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 { 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); }
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(); }
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(); }
@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)); }
public Long getPlanningTime() { return getDuration(State.PLANNING); }
AttemptsHelper { public Long getPlanningTime() { return getDuration(State.PLANNING); } }
AttemptsHelper { public Long getPlanningTime() { return getDuration(State.PLANNING); } AttemptsHelper(JobAttempt jobAttempt); }
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(); }
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(); }
@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)); }
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 { 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 { 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); }
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(); }
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(); }
@Test public void testGetPendingTime() { Preconditions.checkNotNull(attemptsHelper.getPendingTime()); assertTrue(1L == attemptsHelper.getPendingTime()); }
public Long getPendingTime() { return getDuration(State.PENDING); }
AttemptsHelper { public Long getPendingTime() { return getDuration(State.PENDING); } }
AttemptsHelper { public Long getPendingTime() { return getDuration(State.PENDING); } AttemptsHelper(JobAttempt jobAttempt); }
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(); }
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(); }
@Test public void testGetMetadataRetrievalTime() { Preconditions.checkNotNull(attemptsHelper.getMetadataRetrievalTime()); assertTrue(1L == attemptsHelper.getMetadataRetrievalTime()); }
public Long getMetadataRetrievalTime() { return getDuration(State.METADATA_RETRIEVAL); }
AttemptsHelper { public Long getMetadataRetrievalTime() { return getDuration(State.METADATA_RETRIEVAL); } }
AttemptsHelper { public Long getMetadataRetrievalTime() { return getDuration(State.METADATA_RETRIEVAL); } AttemptsHelper(JobAttempt jobAttempt); }
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(); }
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(); }
@Test public void testPlanningTime() { Preconditions.checkNotNull(attemptsHelper.getPlanningTime()); assertTrue(1L == attemptsHelper.getPlanningTime()); }
public Long getPlanningTime() { return getDuration(State.PLANNING); }
AttemptsHelper { public Long getPlanningTime() { return getDuration(State.PLANNING); } }
AttemptsHelper { public Long getPlanningTime() { return getDuration(State.PLANNING); } AttemptsHelper(JobAttempt jobAttempt); }
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(); }
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(); }
@Test public void testGetEngineStartTime() { Preconditions.checkNotNull(attemptsHelper.getEngineStartTime()); assertTrue(1L == attemptsHelper.getEngineStartTime()); }
public Long getEngineStartTime() { return getDuration(State.ENGINE_START); }
AttemptsHelper { public Long getEngineStartTime() { return getDuration(State.ENGINE_START); } }
AttemptsHelper { public Long getEngineStartTime() { return getDuration(State.ENGINE_START); } AttemptsHelper(JobAttempt jobAttempt); }
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(); }
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(); }
@Test public void testGetQueuedTime() { Preconditions.checkNotNull(attemptsHelper.getQueuedTime()); assertTrue(1L == attemptsHelper.getQueuedTime()); }
public Long getQueuedTime() { return getDuration(State.QUEUED); }
AttemptsHelper { public Long getQueuedTime() { return getDuration(State.QUEUED); } }
AttemptsHelper { public Long getQueuedTime() { return getDuration(State.QUEUED); } AttemptsHelper(JobAttempt jobAttempt); }
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(); }
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(); }
@Test public void testGetExecutionPlanningTime() { Preconditions.checkNotNull(attemptsHelper.getExecutionPlanningTime()); assertTrue(1L == attemptsHelper.getExecutionPlanningTime()); }
public Long getExecutionPlanningTime() { return getDuration(State.EXECUTION_PLANNING); }
AttemptsHelper { public Long getExecutionPlanningTime() { return getDuration(State.EXECUTION_PLANNING); } }
AttemptsHelper { public Long getExecutionPlanningTime() { return getDuration(State.EXECUTION_PLANNING); } AttemptsHelper(JobAttempt jobAttempt); }
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(); }
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(); }
@Test public void testDependencySort() throws Exception { UpgradeTask1 upgradeTask1 = new UpgradeTask1(ImmutableList.of()); UpgradeTask2 upgradeTask2 = new UpgradeTask2(ImmutableList.of(upgradeTask1.getTaskUUID())); UpgradeTask3 upgradeTask3 = new UpgradeTask3(ImmutableList.of(upgradeTask1.getTaskUUID(), upgradeTask2.getTaskUUID())); UpgradeTask4 upgradeTask4 = new UpgradeTask4(ImmutableList.of(upgradeTask3.getTaskUUID())); UpgradeTaskDependencyResolver upgradeTaskDependencyResolver = new UpgradeTaskDependencyResolver( ImmutableList.of(upgradeTask1, upgradeTask2, upgradeTask3, upgradeTask4) ); List<UpgradeTask> sortedUpgradeTasks = upgradeTaskDependencyResolver.topologicalTasksSort(); assertThat(sortedUpgradeTasks, contains( instanceOf(UpgradeTask1.class), instanceOf(UpgradeTask2.class), instanceOf(UpgradeTask3.class), instanceOf(UpgradeTask4.class) )); }
public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks.add(uuidToTask.get(dep)); } return resolvedTasks; }
UpgradeTaskDependencyResolver { public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks.add(uuidToTask.get(dep)); } return resolvedTasks; } }
UpgradeTaskDependencyResolver { public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks.add(uuidToTask.get(dep)); } return resolvedTasks; } UpgradeTaskDependencyResolver(List<? extends UpgradeTask> fullList); }
UpgradeTaskDependencyResolver { public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks.add(uuidToTask.get(dep)); } return resolvedTasks; } UpgradeTaskDependencyResolver(List<? extends UpgradeTask> fullList); List<UpgradeTask> topologicalTasksSort(); }
UpgradeTaskDependencyResolver { public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks.add(uuidToTask.get(dep)); } return resolvedTasks; } UpgradeTaskDependencyResolver(List<? extends UpgradeTask> fullList); List<UpgradeTask> topologicalTasksSort(); }
@Test public void testGetStartingTime() { Preconditions.checkNotNull(attemptsHelper.getStartingTime()); assertTrue(1L == attemptsHelper.getStartingTime()); }
public Long getStartingTime() { return getDuration(State.STARTING); }
AttemptsHelper { public Long getStartingTime() { return getDuration(State.STARTING); } }
AttemptsHelper { public Long getStartingTime() { return getDuration(State.STARTING); } AttemptsHelper(JobAttempt jobAttempt); }
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(); }
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(); }
@Test public void testGetRunningTime() { Preconditions.checkNotNull(attemptsHelper.getRunningTime()); assertTrue(1L == attemptsHelper.getRunningTime()); }
public Long getRunningTime() { return getDuration(State.RUNNING); }
AttemptsHelper { public Long getRunningTime() { return getDuration(State.RUNNING); } }
AttemptsHelper { public Long getRunningTime() { return getDuration(State.RUNNING); } AttemptsHelper(JobAttempt jobAttempt); }
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(); }
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(); }
@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))); } }
@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); }
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); } }
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); }
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); }
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; }
@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()); }
private QueryProgressMetrics combine() { long rowsProcessed = executorMetrics .mapToLong(QueryProgressMetrics::getRowsProcessed) .sum(); return QueryProgressMetrics.newBuilder() .setRowsProcessed(rowsProcessed) .build(); }
MetricsCombiner { private QueryProgressMetrics combine() { long rowsProcessed = executorMetrics .mapToLong(QueryProgressMetrics::getRowsProcessed) .sum(); return QueryProgressMetrics.newBuilder() .setRowsProcessed(rowsProcessed) .build(); } }
MetricsCombiner { private QueryProgressMetrics combine() { long rowsProcessed = executorMetrics .mapToLong(QueryProgressMetrics::getRowsProcessed) .sum(); return QueryProgressMetrics.newBuilder() .setRowsProcessed(rowsProcessed) .build(); } private MetricsCombiner(Stream<QueryProgressMetrics> executorMetrics); }
MetricsCombiner { private QueryProgressMetrics combine() { long rowsProcessed = executorMetrics .mapToLong(QueryProgressMetrics::getRowsProcessed) .sum(); return QueryProgressMetrics.newBuilder() .setRowsProcessed(rowsProcessed) .build(); } private MetricsCombiner(Stream<QueryProgressMetrics> executorMetrics); }
MetricsCombiner { private QueryProgressMetrics combine() { long rowsProcessed = executorMetrics .mapToLong(QueryProgressMetrics::getRowsProcessed) .sum(); return QueryProgressMetrics.newBuilder() .setRowsProcessed(rowsProcessed) .build(); } private MetricsCombiner(Stream<QueryProgressMetrics> executorMetrics); }
@Test public void testMergeWithOnlyPlanningProfile() { final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.COMPLETED) .addStateList(AttemptEvent.newBuilder() .setState(State.COMPLETED).setStartTime(20L).build()) .build(); final UserBitShared.QueryProfile expectedMergedProfile = planningProfile.toBuilder() .setTotalFragments(0) .setFinishedFragments(0) .build(); assertEquals(expectedMergedProfile, ProfileMerger.merge(planningProfile, null, Stream.empty())); }
static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
@Test public void testMergeWithOnlyPlanningAndTailProfile() { final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .addStateList(AttemptEvent.newBuilder() .setState(State.QUEUED).setStartTime(20L).build()) .build(); final UserBitShared.QueryProfile tailProfile = UserBitShared.QueryProfile.newBuilder() .setErrorNode("ERROR_NODE") .setState(UserBitShared.QueryResult.QueryState.CANCELED) .addStateList(AttemptEvent.newBuilder() .setState(State.CANCELED).setStartTime(20L).build()) .build(); final UserBitShared.QueryProfile expectedMergedProfile = UserBitShared.QueryProfile.newBuilder() .setErrorNode("ERROR_NODE") .setState(UserBitShared.QueryResult.QueryState.CANCELED) .addStateList(AttemptEvent.newBuilder() .setState(State.CANCELED).setStartTime(20L).build()) .setTotalFragments(0) .setFinishedFragments(0) .build(); assertEquals(expectedMergedProfile, ProfileMerger.merge(planningProfile, tailProfile, Stream.empty())); }
static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
@Test public void testMergeWithOnlyPlanningAndExecutorProfiles() { final CoordinationProtos.NodeEndpoint nodeEndPoint = CoordinationProtos.NodeEndpoint .newBuilder() .setAddress("190.190.0.666") .build(); final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .addStateList(AttemptEvent.newBuilder() .setState(State.QUEUED).setStartTime(20L).build()) .build(); final CoordExecRPC.ExecutorQueryProfile executorQueryProfile = CoordExecRPC.ExecutorQueryProfile.newBuilder() .setEndpoint(nodeEndPoint) .setNodeStatus( CoordExecRPC.NodeQueryStatus.newBuilder() .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .build() ) .build(); final UserBitShared.QueryProfile expectedMergedProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .addStateList(AttemptEvent.newBuilder() .setState(State.QUEUED).setStartTime(20L).build()) .addNodeProfile( UserBitShared.NodeQueryProfile.newBuilder() .setEndpoint(nodeEndPoint) .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .build() ) .setTotalFragments(0) .setFinishedFragments(0) .build(); assertEquals(expectedMergedProfile, ProfileMerger.merge(planningProfile, null, Stream.of(executorQueryProfile))); }
static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
@Test public void testMergeWithOnlyThreeParts() { final CoordinationProtos.NodeEndpoint nodeEndPoint = CoordinationProtos.NodeEndpoint .newBuilder() .setAddress("190.190.0.666") .build(); final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .build(); final CoordExecRPC.ExecutorQueryProfile executorQueryProfile = CoordExecRPC.ExecutorQueryProfile.newBuilder() .setEndpoint(nodeEndPoint) .setNodeStatus( CoordExecRPC.NodeQueryStatus.newBuilder() .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .build() ) .build(); final UserBitShared.QueryProfile tailProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setErrorNode("ERROR_NODE") .setState(UserBitShared.QueryResult.QueryState.CANCELED) .addStateList(AttemptEvent.newBuilder() .setState(State.CANCELED).setStartTime(20L).build()) .build(); final UserBitShared.QueryProfile expectedMergedProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setErrorNode("ERROR_NODE") .setState(UserBitShared.QueryResult.QueryState.CANCELED) .addStateList(AttemptEvent.newBuilder() .setState(State.CANCELED).setStartTime(20L).build()) .addNodeProfile( UserBitShared.NodeQueryProfile.newBuilder() .setEndpoint(nodeEndPoint) .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .build() ) .setTotalFragments(0) .setFinishedFragments(0) .build(); assertEquals(expectedMergedProfile, ProfileMerger.merge(planningProfile, tailProfile, Stream.of(executorQueryProfile))); }
static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
@Test public void testMergeWithMultipleExecutorProfiles() { final CoordinationProtos.NodeEndpoint nodeEndPoint1 = CoordinationProtos.NodeEndpoint .newBuilder() .setAddress("190.190.0.66") .build(); final CoordinationProtos.NodeEndpoint nodeEndPoint2 = CoordinationProtos.NodeEndpoint .newBuilder() .setAddress("190.190.0.67") .build(); final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .build(); CoordExecRPC.NodePhaseStatus node1Phase0 = CoordExecRPC.NodePhaseStatus.newBuilder() .setMajorFragmentId(0) .setMaxMemoryUsed(10) .build(); CoordExecRPC.NodePhaseStatus node1Phase1 = CoordExecRPC.NodePhaseStatus.newBuilder() .setMajorFragmentId(1) .setMaxMemoryUsed(11) .build(); CoordExecRPC.FragmentStatus node1Frag0 = CoordExecRPC.FragmentStatus.newBuilder() .setHandle(ExecProtos.FragmentHandle.newBuilder().setMajorFragmentId(0).build()) .setProfile(UserBitShared.MinorFragmentProfile.newBuilder().setEndTime(116) .setState(FragmentState.FINISHED).build()) .build(); CoordExecRPC.FragmentStatus node1Frag1 = CoordExecRPC.FragmentStatus.newBuilder() .setHandle(ExecProtos.FragmentHandle.newBuilder().setMajorFragmentId(1).build()) .setProfile(UserBitShared.MinorFragmentProfile.newBuilder().setEndTime(117).build()) .build(); final CoordExecRPC.ExecutorQueryProfile executorQueryProfile1 = CoordExecRPC.ExecutorQueryProfile.newBuilder() .setEndpoint(nodeEndPoint1) .setNodeStatus( CoordExecRPC.NodeQueryStatus.newBuilder() .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .addPhaseStatus(node1Phase0) .addPhaseStatus(node1Phase1) .build() ) .addFragments(node1Frag0) .addFragments(node1Frag1) .build(); CoordExecRPC.NodePhaseStatus node2Phase0 = CoordExecRPC.NodePhaseStatus.newBuilder() .setMajorFragmentId(0) .setMaxMemoryUsed(20) .build(); CoordExecRPC.NodePhaseStatus node2Phase1 = CoordExecRPC.NodePhaseStatus.newBuilder() .setMajorFragmentId(1) .setMaxMemoryUsed(21) .build(); CoordExecRPC.FragmentStatus node2Frag0 = CoordExecRPC.FragmentStatus.newBuilder() .setHandle(ExecProtos.FragmentHandle.newBuilder().setMajorFragmentId(0).build()) .setProfile(UserBitShared.MinorFragmentProfile.newBuilder().setEndTime(216) .setState(FragmentState.FINISHED).build()) .build(); CoordExecRPC.FragmentStatus node2Frag1 = CoordExecRPC.FragmentStatus.newBuilder() .setHandle(ExecProtos.FragmentHandle.newBuilder().setMajorFragmentId(1).build()) .setProfile(UserBitShared.MinorFragmentProfile.newBuilder().setEndTime(217).build()) .build(); final CoordExecRPC.ExecutorQueryProfile executorQueryProfile2 = CoordExecRPC.ExecutorQueryProfile.newBuilder() .setEndpoint(nodeEndPoint2) .setNodeStatus( CoordExecRPC.NodeQueryStatus.newBuilder() .setMaxMemoryUsed(666667) .setTimeEnqueuedBeforeSubmitMs(3) .addPhaseStatus(node2Phase0) .addPhaseStatus(node2Phase1) .build() ) .addFragments(node2Frag0) .addFragments(node2Frag1) .build(); final UserBitShared.QueryProfile expectedMergedProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .addNodeProfile( UserBitShared.NodeQueryProfile.newBuilder() .setEndpoint(nodeEndPoint1) .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .build() ) .addNodeProfile( UserBitShared.NodeQueryProfile.newBuilder() .setEndpoint(nodeEndPoint2) .setMaxMemoryUsed(666667) .setTimeEnqueuedBeforeSubmitMs(3) .build() ) .addFragmentProfile( UserBitShared.MajorFragmentProfile.newBuilder() .setMajorFragmentId(0) .addNodePhaseProfile( UserBitShared.NodePhaseProfile.newBuilder() .setEndpoint(nodeEndPoint1) .setMaxMemoryUsed(node1Phase0.getMaxMemoryUsed()) .build() ) .addNodePhaseProfile( UserBitShared.NodePhaseProfile.newBuilder() .setEndpoint(nodeEndPoint2) .setMaxMemoryUsed(node2Phase0.getMaxMemoryUsed()) .build() ) .addMinorFragmentProfile(node1Frag0.getProfile()) .addMinorFragmentProfile(node2Frag0.getProfile()) .build() ) .addFragmentProfile( UserBitShared.MajorFragmentProfile.newBuilder() .setMajorFragmentId(1) .addNodePhaseProfile( UserBitShared.NodePhaseProfile.newBuilder() .setEndpoint(nodeEndPoint1) .setMaxMemoryUsed(node1Phase1.getMaxMemoryUsed()) .build() ) .addNodePhaseProfile( UserBitShared.NodePhaseProfile.newBuilder() .setEndpoint(nodeEndPoint2) .setMaxMemoryUsed(node2Phase1.getMaxMemoryUsed()) .build() ) .addMinorFragmentProfile(node1Frag1.getProfile()) .addMinorFragmentProfile(node2Frag1.getProfile()) .build() ) .setTotalFragments(4) .setFinishedFragments(2) .build(); assertEquals(expectedMergedProfile, ProfileMerger.merge(planningProfile, null, Stream.of(executorQueryProfile1, executorQueryProfile2))); }
static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
@Test public void testFragmentCountFromPlanningProfile() { final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.COMPLETED) .setTotalFragments(5) .build(); final UserBitShared.QueryProfile expectedMergedProfile = planningProfile.toBuilder() .setTotalFragments(5) .setFinishedFragments(0) .build(); assertEquals(expectedMergedProfile, ProfileMerger.merge(planningProfile, null, Stream.empty())); }
static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
@Test public void testDependencySortLargeTasksNumber() throws Exception { UpgradeTaskAny upgradeTaskAny1 = new UpgradeTaskAny("upgradeTaskAny1","5", ImmutableList.of()); UpgradeTaskAny upgradeTaskAny2 = new UpgradeTaskAny("upgradeTaskAny2", "7", ImmutableList.of()); UpgradeTaskAny upgradeTaskAny3 = new UpgradeTaskAny("upgradeTaskAny3","3", ImmutableList.of()); UpgradeTaskAny upgradeTaskAny4 = new UpgradeTaskAny("upgradeTaskAny4", "11", ImmutableList.of(upgradeTaskAny1.getTaskUUID(), upgradeTaskAny2.getTaskUUID())); UpgradeTaskAny upgradeTaskAny5 = new UpgradeTaskAny("upgradeTaskAny5", "8", ImmutableList.of(upgradeTaskAny2.getTaskUUID(), upgradeTaskAny3.getTaskUUID())); UpgradeTaskAny upgradeTaskAny6 = new UpgradeTaskAny("upgradeTaskAny6","2", ImmutableList.of (upgradeTaskAny4.getTaskUUID())); UpgradeTaskAny upgradeTaskAny7 = new UpgradeTaskAny("upgradeTaskAny7","9", ImmutableList.of(upgradeTaskAny4.getTaskUUID(), upgradeTaskAny5.getTaskUUID())); UpgradeTaskAny upgradeTaskAny8 = new UpgradeTaskAny("upgradeTaskAny8", "10", ImmutableList.of(upgradeTaskAny4.getTaskUUID(), upgradeTaskAny3.getTaskUUID())); List<UpgradeTask> upgradeTasks = new ArrayList<>(); upgradeTasks.add(upgradeTaskAny1); upgradeTasks.add(upgradeTaskAny2); upgradeTasks.add(upgradeTaskAny3); upgradeTasks.add(upgradeTaskAny4); upgradeTasks.add(upgradeTaskAny5); upgradeTasks.add(upgradeTaskAny6); upgradeTasks.add(upgradeTaskAny7); upgradeTasks.add(upgradeTaskAny8); Collections.shuffle(upgradeTasks); UpgradeTaskDependencyResolver upgradeTaskDependencyResolver = new UpgradeTaskDependencyResolver(upgradeTasks); List<UpgradeTask> sortedUpgradeTasks = upgradeTaskDependencyResolver.topologicalTasksSort(); Map<String, Integer> nameToIndexMap = Maps.newHashMap(); int i = 0; for (UpgradeTask upgradeTask : sortedUpgradeTasks) { nameToIndexMap.put(upgradeTask.getDescription(), i); i++; } assertTrue(nameToIndexMap.get("upgradeTaskAny8") > nameToIndexMap.get("upgradeTaskAny4")); assertTrue(nameToIndexMap.get("upgradeTaskAny8") > nameToIndexMap.get("upgradeTaskAny3")); assertTrue(nameToIndexMap.get("upgradeTaskAny7") > nameToIndexMap.get("upgradeTaskAny4")); assertTrue(nameToIndexMap.get("upgradeTaskAny7") > nameToIndexMap.get("upgradeTaskAny5")); assertTrue(nameToIndexMap.get("upgradeTaskAny5") > nameToIndexMap.get("upgradeTaskAny2")); assertTrue(nameToIndexMap.get("upgradeTaskAny5") > nameToIndexMap.get("upgradeTaskAny3")); assertTrue(nameToIndexMap.get("upgradeTaskAny6") > nameToIndexMap.get("upgradeTaskAny4")); assertTrue(nameToIndexMap.get("upgradeTaskAny4") > nameToIndexMap.get("upgradeTaskAny1")); assertTrue(nameToIndexMap.get("upgradeTaskAny4") > nameToIndexMap.get("upgradeTaskAny2")); }
public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks.add(uuidToTask.get(dep)); } return resolvedTasks; }
UpgradeTaskDependencyResolver { public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks.add(uuidToTask.get(dep)); } return resolvedTasks; } }
UpgradeTaskDependencyResolver { public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks.add(uuidToTask.get(dep)); } return resolvedTasks; } UpgradeTaskDependencyResolver(List<? extends UpgradeTask> fullList); }
UpgradeTaskDependencyResolver { public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks.add(uuidToTask.get(dep)); } return resolvedTasks; } UpgradeTaskDependencyResolver(List<? extends UpgradeTask> fullList); List<UpgradeTask> topologicalTasksSort(); }
UpgradeTaskDependencyResolver { public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks.add(uuidToTask.get(dep)); } return resolvedTasks; } UpgradeTaskDependencyResolver(List<? extends UpgradeTask> fullList); List<UpgradeTask> topologicalTasksSort(); }
@Test public void testMergeWithInconsistentExecutorProfiles() { final CoordinationProtos.NodeEndpoint nodeEndPoint = CoordinationProtos.NodeEndpoint .newBuilder() .setAddress("190.190.0.666") .build(); final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .build(); CoordExecRPC.NodePhaseStatus phase0 = CoordExecRPC.NodePhaseStatus.newBuilder() .setMajorFragmentId(0) .setMaxMemoryUsed(20) .build(); CoordExecRPC.FragmentStatus frag0 = CoordExecRPC.FragmentStatus.newBuilder() .setHandle(ExecProtos.FragmentHandle.newBuilder().setMajorFragmentId(0).build()) .setProfile(UserBitShared.MinorFragmentProfile.newBuilder().setEndTime(216) .setState(FragmentState.FINISHED).build()) .build(); CoordExecRPC.FragmentStatus frag1 = CoordExecRPC.FragmentStatus.newBuilder() .setHandle(ExecProtos.FragmentHandle.newBuilder().setMajorFragmentId(1).build()) .setProfile(UserBitShared.MinorFragmentProfile.newBuilder().setEndTime(216) .setState(FragmentState.FINISHED).build()) .build(); final CoordExecRPC.ExecutorQueryProfile executorQueryProfile = CoordExecRPC.ExecutorQueryProfile.newBuilder() .setEndpoint(nodeEndPoint) .setNodeStatus( CoordExecRPC.NodeQueryStatus.newBuilder() .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .addPhaseStatus(phase0) .build() ) .addFragments(frag0) .addFragments(frag1) .build(); final UserBitShared.QueryProfile expectedMergedProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .addNodeProfile( UserBitShared.NodeQueryProfile.newBuilder() .setEndpoint(nodeEndPoint) .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .build() ) .addFragmentProfile( UserBitShared.MajorFragmentProfile.newBuilder() .setMajorFragmentId(0) .addNodePhaseProfile( UserBitShared.NodePhaseProfile.newBuilder() .setEndpoint(nodeEndPoint) .setMaxMemoryUsed(phase0.getMaxMemoryUsed()) .build() ) .addMinorFragmentProfile(frag0.getProfile()) .build() ) .addFragmentProfile( UserBitShared.MajorFragmentProfile.newBuilder() .setMajorFragmentId(1) .addMinorFragmentProfile(frag1.getProfile()) .build() ) .setTotalFragments(2) .setFinishedFragments(2) .build(); assertEquals(expectedMergedProfile, ProfileMerger.merge(planningProfile, null, Stream.of(executorQueryProfile))); }
static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
@Test public void testMergeWithInconsistentExecutorProfiles2() { final CoordinationProtos.NodeEndpoint nodeEndPoint = CoordinationProtos.NodeEndpoint .newBuilder() .setAddress("190.190.0.666") .build(); final UserBitShared.QueryProfile planningProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .build(); CoordExecRPC.NodePhaseStatus phase0 = CoordExecRPC.NodePhaseStatus.newBuilder() .setMajorFragmentId(0) .setMaxMemoryUsed(20) .build(); CoordExecRPC.NodePhaseStatus phase1 = CoordExecRPC.NodePhaseStatus.newBuilder() .setMajorFragmentId(1) .setMaxMemoryUsed(30) .build(); CoordExecRPC.FragmentStatus frag0 = CoordExecRPC.FragmentStatus.newBuilder() .setHandle(ExecProtos.FragmentHandle.newBuilder().setMajorFragmentId(0).build()) .setProfile(UserBitShared.MinorFragmentProfile.newBuilder().setEndTime(216) .setState(FragmentState.FINISHED).build()) .build(); final CoordExecRPC.ExecutorQueryProfile executorQueryProfile = CoordExecRPC.ExecutorQueryProfile.newBuilder() .setEndpoint(nodeEndPoint) .setNodeStatus( CoordExecRPC.NodeQueryStatus.newBuilder() .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .addPhaseStatus(phase0) .addPhaseStatus(phase1) .build() ) .addFragments(frag0) .build(); final UserBitShared.QueryProfile expectedMergedProfile = UserBitShared.QueryProfile.newBuilder() .setPlan("PLAN_VALUE") .setQuery("Select * from plan") .setState(UserBitShared.QueryResult.QueryState.ENQUEUED) .addNodeProfile( UserBitShared.NodeQueryProfile.newBuilder() .setEndpoint(nodeEndPoint) .setMaxMemoryUsed(666666) .setTimeEnqueuedBeforeSubmitMs(2) .build() ) .addFragmentProfile( UserBitShared.MajorFragmentProfile.newBuilder() .setMajorFragmentId(0) .addNodePhaseProfile( UserBitShared.NodePhaseProfile.newBuilder() .setEndpoint(nodeEndPoint) .setMaxMemoryUsed(phase0.getMaxMemoryUsed()) .build() ) .addMinorFragmentProfile(frag0.getProfile()) .build() ) .addFragmentProfile( UserBitShared.MajorFragmentProfile.newBuilder() .setMajorFragmentId(1) .addNodePhaseProfile( UserBitShared.NodePhaseProfile.newBuilder() .setEndpoint(nodeEndPoint) .setMaxMemoryUsed(phase1.getMaxMemoryUsed()) .build() ) .build() ) .setTotalFragments(1) .setFinishedFragments(1) .build(); assertEquals(expectedMergedProfile, ProfileMerger.merge(planningProfile, null, Stream.of(executorQueryProfile))); }
static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
ProfileMerger { static QueryProfile merge(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles) { return new ProfileMerger(planningProfile, tailProfile, executorProfiles).merge(); } private ProfileMerger(QueryProfile planningProfile, QueryProfile tailProfile, Stream<ExecutorQueryProfile> executorProfiles); }
@Test public void ensureDirectFailureOnRpcException() { conn().runCommand(Cmd.expectFail()); }
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 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 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); }
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(); }
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(); }
@Test public void ensureSecondSuccess() { conn( r -> r.connectionFailed(FailureType.CONNECTION, new IllegalStateException()), r -> r.connectionSucceeded(newRemoteConnection()) ).runCommand(Cmd.expectSucceed()); }
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 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 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); }
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(); }
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(); }
@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()); }
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 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 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); }
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(); }
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(); }
@Test public void ensureSuccessThenAvailable() { TestReConnection c = conn(r -> r.connectionSucceeded(newRemoteConnection())); c.runCommand(Cmd.expectSucceed()); c.runCommand(Cmd.expectAvailable()); }
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 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 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); }
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(); }
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(); }
@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()); }
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 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 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); }
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(); }
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(); }
@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(); }
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 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 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); }
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(); }
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(); }
@Test public void testNullException() throws Exception { RpcException.propagateIfPossible(null, Exception.class); }
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 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 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); }
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(); }
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(); }
@Test public void testNonRemoteException() throws Exception { RpcException e = new RpcException("Test message", new Exception()); RpcException.propagateIfPossible(e, Exception.class); }
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 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 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); }
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(); }
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(); }
@Test public void detectLoopTest() throws Exception { UpgradeTask1 upgradeTask1 = new UpgradeTask1(ImmutableList.of()); UpgradeTask2 upgradeTask2 = new UpgradeTask2(ImmutableList.of("UpgradeTask4")); UpgradeTask3 upgradeTask3 = new UpgradeTask3(ImmutableList.of(upgradeTask1.getTaskUUID(), upgradeTask2.getTaskUUID())); UpgradeTask4 upgradeTask4 = new UpgradeTask4(ImmutableList.of(upgradeTask3.getTaskUUID())); UpgradeTaskDependencyResolver upgradeTaskDependencyResolver = new UpgradeTaskDependencyResolver( ImmutableList.of(upgradeTask1, upgradeTask2, upgradeTask3, upgradeTask4) ); thrown.expect(IllegalStateException.class); thrown.expectMessage("Dependencies loop detected: UpgradeTask2"); upgradeTaskDependencyResolver.topologicalTasksSort(); }
public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks.add(uuidToTask.get(dep)); } return resolvedTasks; }
UpgradeTaskDependencyResolver { public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks.add(uuidToTask.get(dep)); } return resolvedTasks; } }
UpgradeTaskDependencyResolver { public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks.add(uuidToTask.get(dep)); } return resolvedTasks; } UpgradeTaskDependencyResolver(List<? extends UpgradeTask> fullList); }
UpgradeTaskDependencyResolver { public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks.add(uuidToTask.get(dep)); } return resolvedTasks; } UpgradeTaskDependencyResolver(List<? extends UpgradeTask> fullList); List<UpgradeTask> topologicalTasksSort(); }
UpgradeTaskDependencyResolver { public List<UpgradeTask> topologicalTasksSort() { List<String> resolved = Lists.newArrayList(); for(UpgradeTask task : uuidToTask.values()) { visit(task, resolved, Lists.newArrayList()); } List<UpgradeTask> resolvedTasks = Lists.newArrayList(); for (String dep : resolved) { resolvedTasks.add(uuidToTask.get(dep)); } return resolvedTasks; } UpgradeTaskDependencyResolver(List<? extends UpgradeTask> fullList); List<UpgradeTask> topologicalTasksSort(); }
@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); }
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 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 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); }
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(); }
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(); }
@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); }
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 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 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); }
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(); }
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(); }
@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); }
@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 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 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); }
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(); }
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(); }
@Test public void testEqualsReturnsFalseAllNull() { assertTrue(KeyUtils.equals(null, null)); }
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); }
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); } }
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(); }
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); }
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); }
@Test public void testEqualsReturnsFalseLeftNull() { assertFalse(KeyUtils.equals(null, Boolean.TRUE)); }
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); }
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); } }
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(); }
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); }
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); }
@Test public void testEqualsReturnsFalseRightNull() { assertFalse(KeyUtils.equals(Boolean.TRUE, null)); }
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); }
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); } }
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(); }
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); }
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); }
@Test public void testEqualsReturnsTrueWithBooleanTrueTrue() { assertTrue(KeyUtils.equals(Boolean.TRUE, Boolean.TRUE)); }
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); }
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); } }
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(); }
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); }
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); }