com.jcabi.xml.XMLDocument Java Examples

The following examples show how to use com.jcabi.xml.XMLDocument. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XmlMethodCallTest.java    From jpeek with MIT License 6 votes vote down vote up
@Test
void hasClassMethodAndArgs() throws IOException {
    new Assertion<>(
        "Must have class name, method name and args.",
        new XmlMethodCall(
            new XMLDocument(
                new Joined(
                    "",
                    "<op code=\"call\">",
                    "  <name>OverloadMethods.methodOne</name>",
                    "  <args>",
                    "    <arg type=\"Ljava/lang/String\">?</arg>",
                    "    <arg type=\"Z\">?</arg>",
                    "  </args>",
                    "</op>"
                ).asString()
            ).nodes("//op").get(0)
        ).asString(),
        new IsEqual<>(
            "OverloadMethods.methodOne.Ljava/lang/String:Z"
        )
    ).affirm();
}
 
Example #2
Source File: Sigmas.java    From jpeek with MIT License 6 votes vote down vote up
/**
 * Add result.
 * @param dir Directory with files
 * @throws IOException If fails
 */
public void add(final Path dir) throws IOException {
    final XML index = new XMLDocument(
        dir.resolve("index.xml").toFile()
    );
    final double defects = Double.parseDouble(
        index.xpath("/index/@defects").get(0)
    );
    final int classes = Integer.parseInt(
        index.xpath("/index/metric[1]/classes/text()").get(0)
    );
    // @checkstyle MagicNumber (1 line)
    if (defects < 0.15d && classes > 200) {
        for (final XML metric : index.nodes("//metric")) {
            this.add(metric);
        }
    }
}
 
Example #3
Source File: AppTest.java    From jpeek with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public void isXsdDocumented() throws IOException {
    final List<XML> elements = new XMLDocument(
        AppTest.class.getResourceAsStream("xsd/metric.xsd")
    ).nodes("//node()[@name]");
    final IsNot<? super List<?>> populated = new IsNot<>(
        new IsEmptyIterable<>()
    );
    new Assertion<>(
        "Nodes must not be empty",
        elements,
        populated
    ).affirm();
    for (final XML element : elements) {
        new Assertion<>(
            String.format(
                "element '%s' must have a documentation",
                element.xpath("@name").get(0)
            ),
            element.xpath("xs:annotation/xs:documentation/text()"),
            populated
        ).affirm();
    }
}
 
Example #4
Source File: AppTest.java    From jpeek with MIT License 6 votes vote down vote up
@Test
public void createsXmlReports(@TempDir final Path output) throws IOException {
    final Path input = Paths.get(".");
    new App(input, output).analyze();
    new Assertion<>(
        "Must LCOM.xml file exists",
        Files.exists(output.resolve("LCOM.xml")),
        new IsTrue()
    ).affirm();
    new Assertion<>(
        "Must create LCOM report",
        XSLDocument
            .make(
                AppTest.class.getResourceAsStream("xsl/metric.xsl")
            )
            .with(new ClasspathSources())
            .applyTo(new XMLDocument(output.resolve("LCOM.xml").toFile())),
        XhtmlMatchers.hasXPath("//xhtml:body")
    ).affirm();
}
 
Example #5
Source File: XslReport.java    From jpeek with MIT License 6 votes vote down vote up
/**
 * Make XML.
 * @return XML
 * @throws IOException If fails
 * @todo #227:30min Add a test to check whether passing params to
 *  XSLDocument really works. Currently only C3 metric template
 *  is known to use parameter named 'ctors'. However C3.xsl is a
 *  work in progress and has impediments, see #175. In case the
 *  parameter becomes obsolete, consider simplifying construction
 *  of XSLDocument without params (see reviews to #326).
 */
private XML xml() throws IOException {
    return new XMLDocument(
        new Xembler(
            new Directives()
                .xpath("/metric")
                .attr(
                    "xmlns:xsi",
                    "http://www.w3.org/2001/XMLSchema-instance"
                )
                .attr(
                    "xsi:noNamespaceSchemaLocation",
                    XslReport.SCHEMA_FILE
                )
        ).applyQuietly(
            this.calculus.node(
                this.metric, this.params, this.skeleton
            ).node()
        )
    );
}
 
Example #6
Source File: XmlBodyTest.java    From verano-http with MIT License 5 votes vote down vote up
@Test
public void appliesJXmlBodyToRequest() {
    MatcherAssert.assertThat(
        new XmlBody(new XMLDocument("<test></test>"))
            .apply(new HashDict()).get("body"),
        Matchers.containsString("test")
    );
}
 
Example #7
Source File: DyUsage.java    From jare with MIT License 5 votes vote down vote up
/**
 * Load XML.
 * @return The XML with usage
 * @throws IOException If fails
 */
private XML xml() throws IOException {
    if (!this.item.has("usage")) {
        this.save("<usage/>");
    }
    return new XMLDocument(this.item.get("usage").getS());
}
 
Example #8
Source File: DyUsage.java    From jare with MIT License 5 votes vote down vote up
@Override
public void add(final Date date, final long bytes) throws IOException {
    final int day = DyUsage.asNumber(date);
    final XML xml = this.xml();
    final String xpath = String.format("/usage/day[@id='%d']/text()", day);
    final List<String> items = xml.xpath(xpath);
    final long before;
    if (items.isEmpty()) {
        before = 0L;
    } else {
        before = Long.parseLong(items.get(0));
    }
    final Node node = xml.node();
    new Xembler(
        new Directives()
            .xpath(xpath).up().remove()
            .xpath("/usage").add("day").attr("id", day).set(before + bytes)
    ).applyQuietly(node);
    new Xembler(
        new Directives().xpath(
            String.format(
                "/usage/day[number(@id) < %d]",
                DyUsage.asNumber(DateUtils.addDays(new Date(), -Tv.THIRTY))
            )
        ).remove()
    ).applyQuietly(node);
    final XML after = new XMLDocument(node);
    this.save(after.toString());
    this.save(Long.parseLong(after.xpath("sum(/usage/day)").get(0)));
}
 
Example #9
Source File: ReportWithStatisticsTest.java    From jpeek with MIT License 5 votes vote down vote up
@Test
public void createsXml() {
    final XML xml = new ReportWithStatistics(
        new XMLDocument("<metric/>")
    );
    final int threads = 10;
    final ExecutorService service = Executors.newFixedThreadPool(threads);
    final CountDownLatch latch = new CountDownLatch(1);
    for (int thread = 0; thread < threads; ++thread) {
        service.submit(
            () -> {
                latch.await();
                xml.toString();
                return null;
            }
        );
    }
    latch.countDown();
    service.shutdown();
    new Assertion<>(
        "Must create report with statics",
        XhtmlMatchers.xhtml(
            xml.toString()
        ),
        XhtmlMatchers.hasXPaths("/metric/statistics[total='0']")
    ).affirm();
}
 
Example #10
Source File: XslReportTest.java    From jpeek with MIT License 5 votes vote down vote up
@Test
public void createsFullXmlReport(@TempDir final Path output) throws IOException {
    new XslReport(
        new XMLDocument(
            new Xembler(
                new Directives()
                    .add("skeleton")
                    .append(new Header())
                    .add("app").attr("id", ".")
                    .add("package").attr("id", ".")
                    .add("class").attr("id", "A").attr("value", "0.1").up()
                    .add("class").attr("id", "B").attr("value", "0.5").up()
                    .add("class").attr("id", "C").attr("value", "0.6").up()
                    .add("class").attr("id", "D").attr("value", "0.7").up()
                    .add("class").attr("id", "E").attr("value", "NaN").up()
            ).xmlQuietly()
        ), new XslCalculus(), new ReportData("LCOM")
    ).save(output);
    new Assertion<>(
        "Must create full report",
        XhtmlMatchers.xhtml(
            new TextOf(output.resolve("LCOM.xml")).asString()
        ),
        XhtmlMatchers.hasXPaths(
            "/metric[min='0.5' and max='0.6']",
            "//class[@id='B' and @element='true']",
            "//class[@id='D' and @element='false']",
            "//class[@id='E' and @element='false']",
            "//statistics[total='5']",
            "//statistics[elements='2']",
            "//statistics[mean='0.55']"
        )
    ).affirm();
}
 
Example #11
Source File: Mistakes.java    From jpeek with MIT License 5 votes vote down vote up
/**
 * Add result.
 * @param dir Directory with files
 * @throws IOException If fails
 */
public void add(final Path dir) throws IOException {
    final XML index = new XMLDocument(
        dir.resolve("index.xml").toFile()
    );
    for (final XML metric : index.nodes("//metric")) {
        this.add(
            metric.xpath("@name").get(0),
            Double.parseDouble(metric.xpath("@diff").get(0))
        );
    }
}
 
Example #12
Source File: XmlBodyTest.java    From verano-http with MIT License 5 votes vote down vote up
@Test
public void appliesJXmlSourceToRequest() {
    MatcherAssert.assertThat(
        new XmlBody(() -> new XMLDocument("<test></test>"))
            .apply(new HashDict()).get("body"),
        Matchers.containsString("test")
    );
}
 
Example #13
Source File: ReportWithStatistics.java    From jpeek with MIT License 4 votes vote down vote up
/**
 * Ctor.
 * @param xml The XML
 */
ReportWithStatistics(final XML xml) {
    this.output = new Unchecked<>(
        new Solid<XML>(
            () -> {
                final Collection<Double> values = new Mapped<>(
                    Double::parseDouble,
                    xml.xpath(
                        // @checkstyle LineLength (1 line)
                        "//class[@value<=/metric/max and @value>=/metric/min]/@value"
                    )
                );
                final double total = (double) values.size();
                double sum = 0.0d;
                for (final Double value : values) {
                    sum += value;
                }
                final double mean = sum / total;
                double squares = 0.0d;
                for (final Double value : values) {
                    squares += Math.pow(value - mean, 2.0d);
                }
                final double variance = squares / total;
                final double sigma = Math.sqrt(variance);
                double defects = 0.0d;
                for (final Double value : values) {
                    if (value < mean - sigma || value > mean + sigma) {
                        ++defects;
                    }
                }
                return new XMLDocument(
                    new Xembler(
                        new Directives()
                            .xpath("/metric")
                            .add("statistics")
                            .add("total").set(xml.nodes("//class").size())
                            .up()
                            .add("elements").set((long) total).up()
                            .add("mean").set(Double.toString(mean)).up()
                            .add("sigma").set(Double.toString(sigma)).up()
                            .add("variance").set(Double.toString(variance))
                            .up()
                            .add("defects")
                            .set(Double.toString(defects / total)).up()
                    ).applyQuietly(xml.node())
                );
            }
        )
    );
}
 
Example #14
Source File: Index.java    From jpeek with MIT License 4 votes vote down vote up
/**
 * Metric to Xembly.
 * @param file The XML file with metric report
 * @return Xembly
 * @throws FileNotFoundException If fails
 */
private static Iterable<Directive> metric(final Path file)
    throws FileNotFoundException {
    final String name = file.getFileName()
        .toString().replaceAll("\\.xml$", "");
    final XML xml = new XMLDocument(file.toFile());
    final List<Double> values = new Sorted<>(
        new org.cactoos.list.Mapped<>(
            Double::parseDouble,
            xml.xpath("//class[@element='true' and @value!='NaN']/@value")
        )
    );
    final double green = (double) xml.nodes(
        "//*[@element='true' and @color='green']"
    ).size();
    final double yellow = (double) xml.nodes(
        "//*[@element='true' and @color='yellow']"
    ).size();
    final double red = (double) xml.nodes(
        "//*[@element='true' and @color='red']"
    ).size();
    double all = green + yellow + red;
    if (all == 0.0d) {
        all = 1.0d;
    }
    final double score = 10.0d
        * (green + yellow * 0.25d + red * 0.05d) / all;
    final Directives dirs = new Directives()
        .add("metric")
        .attr("name", name)
        .add("html").set(String.format("%s.html", name)).up()
        .add("xml").set(String.format("%s.xml", name)).up()
        .add("elements").set(values.size()).up()
        .add("classes").set(xml.nodes("//class").size()).up()
        .add("green").set((int) green).up()
        .add("yellow").set((int) yellow).up()
        .add("red").set((int) red).up()
        .add("score").set(score).up()
        .add("reverse")
        .set(
            Boolean.toString(
                Double.parseDouble(xml.xpath("/metric/colors/@high").get(0))
                > Double.parseDouble(
                    xml.xpath("/metric/colors/@low").get(0)
                )
            )
        )
        .up();
    if (!values.isEmpty()) {
        dirs.add("min").set(values.get(0)).up()
            .add("max").set(values.get(values.size() - 1)).up();
    }
    final Iterator<XML> bars = xml.nodes("/metric/bars").iterator();
    if (bars.hasNext()) {
        dirs.add("bars").append(Directives.copyOf(bars.next().node())).up();
    }
    final Iterator<XML> stats = xml.nodes("/metric/statistics").iterator();
    if (stats.hasNext()) {
        final XML stat = stats.next();
        dirs.add("defects").set(stat.xpath("defects/text()").get(0)).up()
            .add("sigma").set(stat.xpath("sigma/text()").get(0)).up()
            .add("mean").set(stat.xpath("mean/text()").get(0)).up();
    }
    return dirs.up();
}
 
Example #15
Source File: Results.java    From jpeek with MIT License 4 votes vote down vote up
/**
 * Add result.
 * @param artifact The artifact, like "org.jpeek:jpeek"
 * @param dir Directory with files
 * @throws IOException If fails
 */
public void add(final String artifact, final Path dir)
    throws IOException {
    final XML index = new XMLDocument(
        dir.resolve("index.xml").toFile()
    );
    final int elements = Integer.parseInt(
        index.xpath("max(/index/metric/elements/number(text()))").get(0)
    );
    final Number diff = new DyNum(index.xpath("/index/@diff").get(0));
    final long score = new DyNum(
        index.xpath("/index/@score").get(0)
    ).longValue();
    final long rank = (long) ((double) score * (1.0d - diff.doubleValue()));
    // @checkstyle MagicNumber (1 line)
    if (elements < 100) {
        Logger.info(
            this, "%d elements NOT saved for %s by %s, rank=%d, score=%d, metrics=%d",
            elements, artifact, new Version().value(), rank, score,
            Integer.parseInt(index.xpath("count(/index/metric)").get(0))
        );
    } else {
        this.table.put(
            new Attributes()
                .with("good", "true")
                .with("artifact", artifact)
                .with("rank", rank)
                .with("score", score)
                .with("diff", diff.longValue())
                .with(
                    "defects",
                    new DyNum(
                        index.xpath("/index/@defects").get(0)
                    ).longValue()
                )
                .with("elements", elements)
                .with(
                    "classes",
                    Integer.parseInt(
                        index.xpath(
                            "/index/metric[1]/classes/text()"
                        ).get(0)
                    )
                )
                .with("version", new Version().value())
                .with("added", System.currentTimeMillis())
                .with(
                    "ttl",
                    System.currentTimeMillis()
                        / TimeUnit.SECONDS.toMillis(1L)
                        // @checkstyle MagicNumber (1 line)
                        + TimeUnit.DAYS.toSeconds(100L)
                )
        );
        Logger.info(
            this, "%d elements saved for %s by %s, rank=%d, score=%d",
            elements, artifact, new Version().value(), rank, score
        );
    }
}
 
Example #16
Source File: Reports.java    From jpeek with MIT License 4 votes vote down vote up
@SuppressWarnings("PMD.CyclomaticComplexity")
@Override
public Func<String, Response> apply(final String group,
    final String artifact) throws IOException {
    final String grp = group.replace(".", "/");
    final Path input = this.sources.resolve(grp).resolve(artifact);
    Reports.deleteIfPresent(input);
    final String version = new XMLDocument(
        new TextOf(
            new URL(
                String.format(
                    // @checkstyle LineLength (1 line)
                    "https://repo1.maven.org/maven2/%s/%s/maven-metadata.xml",
                    grp, artifact
                )
            )
        ).asString()
    ).xpath("/metadata/versioning/latest/text()").get(0);
    final String name = String.format("%s-%s.jar", artifact, version);
    new IoChecked<>(
        new LengthOf(
            new TeeInput(
                new URL(
                    String.format(
                        "https://repo1.maven.org/maven2/%s/%s/%s/%s",
                        grp, artifact, version, name
                    )
                ),
                input.resolve(name)
            )
        )
    ).value();
    extractClasses(input.resolve(name));
    final Path output = this.target.resolve(grp).resolve(artifact);
    Reports.deleteIfPresent(output);
    new App(input, output).analyze();
    synchronized (this.sources) {
        new Results().add(String.format("%s:%s", group, artifact), output);
        new Mistakes().add(output);
        new Sigmas().add(output);
    }
    return new TypedPages(new Pages(output));
}
 
Example #17
Source File: Matrix.java    From jpeek with MIT License 4 votes vote down vote up
@Override
public Iterator<Directive> iterator() {
    final SortedMap<String, Map<String, String>> matrix = new TreeMap<>();
    new Unchecked<>(
        new And(
            path -> {
                new And(
                    node -> {
                        final String name = String.format(
                            "%s.%s",
                            node.xpath("../../package/@id").get(0),
                            node.xpath("@id").get(0)
                        );
                        matrix.putIfAbsent(name, new TreeMap<>());
                        matrix.get(name).put(
                            node.xpath("/metric/title/text()").get(0),
                            node.xpath("@color").get(0)
                        );
                    },
                    new XMLDocument(path.toFile()).nodes("//class")
                ).value();
            },
            new Filtered<>(
                path -> path.getFileName().toString().matches(
                    "^[A-Z].+\\.xml$"
                ),
                new Directory(this.output)
            )
        )
    ).value();
    return new Directives()
        .add("matrix")
        .append(new Header())
        .append(
            () -> new Directives()
                .attr(
                    "xmlns:xsi",
                    "http://www.w3.org/2001/XMLSchema-instance"
                )
                .attr(
                    "xsi:noNamespaceSchemaLocation",
                    "xsd/matrix.xsd"
                )
                .iterator())
        .add("classes")
        .append(
            new Joined<Directive>(
                new Mapped<>(
                    ent -> new Directives().add("class").append(
                        new Joined<Directive>(
                            new Mapped<>(
                                mtd -> new Directives()
                                    .add("metric")
                                    .attr("name", mtd.getKey())
                                    .attr("color", mtd.getValue())
                                    .attr(
                                        "rank",
                                        Matrix.rank(mtd.getValue())
                                    )
                                    .up(),
                                ent.getValue().entrySet()
                            )
                        )
                    ).attr("id", ent.getKey()).up(),
                    matrix.entrySet()
                )
            )
        )
        .iterator();
}
 
Example #18
Source File: XmlBody.java    From verano-http with MIT License 2 votes vote down vote up
/**
 * Xml from response body.
 * @return Element Html
 */
public final XML xml() {
    return new XMLDocument(this.asString());
}