org.xembly.Directives Java Examples

The following examples show how to use org.xembly.Directives. 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: MistakesTest.java    From jpeek with MIT License 6 votes vote down vote up
@Test
@Disabled
public void acceptsAndRenders(@TempDir final Path output) throws Exception {
    final Path input = Paths.get(".");
    new App(input, output).analyze();
    final Mistakes mistakes = new Mistakes();
    mistakes.add(output);
    new Assertion<>(
        "Must accept and render",
        XhtmlMatchers.xhtml(
            new Xembler(
                new Directives().add("metrics").append(
                    new Joined<>(mistakes.worst())
                )
            ).xmlQuietly()
        ),
        XhtmlMatchers.hasXPath("/metrics/metric[@id='LCOM']/avg")
    ).affirm();
}
 
Example #2
Source File: OozieWorkflowGenerator.java    From arbiter with Apache License 2.0 6 votes vote down vote up
/**
 * Add elements to the inner action tag (e.g. java as opposed to the outer action tag)
 *
 * @param properties The configuration properties for this action
 * @param configurationPosition The position within the tag where the configuration should be placed
 * @param directives The Xembly Directives object to which to add the new XML elements
 * @param interpolated Interpolated arguments from the YAML workflow definition
 * @param positional Positional arguments from the YAML workflow definition
 */
private void addInnerActionElements(Map<String, String> properties, int configurationPosition, Directives directives, Map<String, List<String>> interpolated, Map<String, List<String>> positional) {
    List<Map.Entry<String, List<String>>> entries = new ArrayList<>();
    if (interpolated != null) {
        entries.addAll(interpolated.entrySet());
    }
    if (positional != null) {
        entries.addAll(positional.entrySet());
    }

    for (int i = 0; i < entries.size(); i++) {
        if (configurationPosition == i) {
            createConfigurationElement(properties, directives);
        }
        addKeyMultiValueElements(entries.get(i), directives);
    }

    if (entries.size() < configurationPosition) {
        createConfigurationElement(properties, directives);
    }
}
 
Example #3
Source File: XmlTypeDef.java    From eo with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
public Iterator<Directive> iterator() {
    final Directives dir = new Directives().add("type")
        .attr("name", this.name);
    dir.add("super");
    for (final String type : this.spr) {
        dir.add("type").attr("name", type).up();
    }
    dir.up();
    dir.add("methods");
    for (final Method method : this.methods) {
        dir.append(method.xml());
    }
    dir.up();
    return dir.up().iterator();
}
 
Example #4
Source File: OozieWorkflowGenerator.java    From arbiter with Apache License 2.0 6 votes vote down vote up
/**
 * Add the configuration element for a workflow action
 *
 * @param properties The configuration properties
 * @param directives The Xembly Directives object to which to add the new XML elements
 */
private void createConfigurationElement(Map<String, String> properties, Directives directives) {
    if (properties == null) {
        return;
    }

    directives.add("configuration");

    for (Map.Entry<String, String> entry : properties.entrySet()) {
        directives.add("property")
                .add("name")
                .set(entry.getKey())
                .up()
                .add("value")
                .set(entry.getValue())
                .up()
                .up();
    }
    directives.up();
}
 
Example #5
Source File: XeIdentity.java    From takes with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param req Request
 */
public XeIdentity(final Request req) {
    super(
        new XeSource() {
            @Override
            public Iterable<Directive> toXembly() throws IOException {
                final Identity identity = new RqAuth(req).identity();
                final Directives dirs = new Directives();
                if (!identity.equals(Identity.ANONYMOUS)) {
                    dirs.add("identity")
                        .add("urn").set(identity.urn()).up();
                    for (final Map.Entry<String, String> prop
                        : identity.properties().entrySet()) {
                        dirs.add(prop.getKey()).set(prop.getValue()).up();
                    }
                }
                return dirs;
            }
        }
    );
}
 
Example #6
Source File: XmlMethodDef.java    From eo with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
public Iterator<Directive> iterator() {
    final Directives dir = new Directives()
        .add("method")
        .attr("name", this.name)
        .add("type")
        .attr("name", this.type)
        .up();
    dir.add("params");
    for (final Parameter param : this.params) {
        dir.append(param.xml());
    }
    dir.up();
    return dir.up().iterator();
}
 
Example #7
Source File: XeFlash.java    From takes with MIT License 6 votes vote down vote up
@Override
public Iterable<Directive> toXembly() throws IOException {
    final Iterator<String> cookies =
        new RqCookies.Base(this.req).cookie(this.cookie).iterator();
    final Directives dirs = new Directives();
    if (cookies.hasNext()) {
        final Matcher matcher = XeFlash.PTN.matcher(cookies.next());
        if (matcher.find()) {
            dirs.add("flash")
                .add("message").set(
                    URLDecoder.decode(
                        matcher.group(1),
                        Charset.defaultCharset().name()
                    )
                ).up()
                .add("level").set(matcher.group(2));
        }
    }
    return dirs;
}
 
Example #8
Source File: XeLocalhost.java    From takes with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param attr Attribute name
 */
@SuppressWarnings
    (
        {
            "PMD.CallSuperInConstructor",
            "PMD.ConstructorOnlyInitializesOrCallOtherConstructors"
        }
    )
public XeLocalhost(final CharSequence attr) {
    super(
        new XeSource() {
            @Override
            public Iterable<Directive> toXembly() {
                String addr;
                try {
                    addr = InetAddress.getLocalHost().getHostAddress();
                } catch (final UnknownHostException ex) {
                    addr = ex.getClass().getCanonicalName();
                }
                return new Directives().attr(attr.toString(), addr);
            }
        }
    );
}
 
Example #9
Source File: XeSla.java    From takes with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param attr Attribute name
 */
public XeSla(final CharSequence attr) {
    super(
        new XeSource() {
            @Override
            public Iterable<Directive> toXembly() {
                return new Directives().attr(
                    attr.toString(),
                    String.format(
                        "%.3f",
                        ManagementFactory.getOperatingSystemMXBean()
                            .getSystemLoadAverage()
                    )
                );
            }
        }
    );
}
 
Example #10
Source File: TkDomains.java    From jare with MIT License 6 votes vote down vote up
/**
 * Convert event to Xembly.
 * @param domain The event
 * @return Xembly
 * @throws IOException If fails
 */
private static XeSource source(final Domain domain) throws IOException {
    final String name = domain.name();
    final Usage usage = domain.usage();
    return new XeDirectives(
        new Directives()
            .add("domain")
            .add("name").set(name).up()
            .add("usage").set(usage.total()).up()
            .append(
                new XeLink(
                    "delete",
                    new Href("/delete").with("name", name)
                ).toXembly()
            )
            .up()
    );
}
 
Example #11
Source File: XeDate.java    From takes with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param attr Attribute name
 */
public XeDate(final CharSequence attr) {
    super(
        new XeSource() {
            @Override
            public Iterable<Directive> toXembly() {
                final DateFormat fmt = new SimpleDateFormat(
                    "yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH
                );
                fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
                return new Directives().attr(
                    attr.toString(), fmt.format(new Date())
                );
            }
        }
    );
}
 
Example #12
Source File: TypesOfTest.java    From jpeek with MIT License 6 votes vote down vote up
@Test
public void parsesSignature() {
    new Assertion<>(
        "Must parse signature",
        XhtmlMatchers.xhtml(
            new Xembler(
                new Directives().add("method").append(
                    new TypesOf("(Ljava/lang/String;Lorg/jpeek/Test;)Z")
                )
            ).xmlQuietly()
        ),
        XhtmlMatchers.hasXPaths(
            "/method/args[count(arg) = 2]",
            "/method/args/arg[@type = 'Ljava/lang/String']",
            "/method[return='Z']"
        )
    ).affirm();
}
 
Example #13
Source File: XeLifetime.java    From takes with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param elm Element name
 */
public XeLifetime(final CharSequence elm) {
    super(
        new XeSource() {
            @Override
            public Iterable<Directive> toXembly() {
                return new Directives().attr(
                    elm.toString(),
                    Long.toString(
                        System.currentTimeMillis() - XeLifetime.START
                    )
                );
            }
        }
    );
}
 
Example #14
Source File: ResultsTest.java    From jpeek with MIT License 6 votes vote down vote up
@Test
@Disabled
public void acceptsAndRenders(@TempDir final Path output) throws Exception {
    final Path input = Paths.get(".");
    new App(input, output).analyze();
    final Results results = new Results();
    results.add("org.takes:takes", output);
    new Assertion<>(
        "Must exists repos tag",
        XhtmlMatchers.xhtml(
            new Xembler(
                new Directives().add("repos").append(
                    new Joined<>(results.recent())
                )
            ).xmlQuietly()
        ),
        XhtmlMatchers.hasXPath("/repos")
    ).affirm();
}
 
Example #15
Source File: Results.java    From jpeek with MIT License 6 votes vote down vote up
/**
 * Recent artifacts..
 * @return List of them
 */
public Iterable<Iterable<Directive>> recent() {
    return new Mapped<>(
        item -> {
            final String[] parts = item.get("artifact").getS().split(":");
            return new Directives()
                .add("repo")
                .add("group").set(parts[0]).up()
                .add("artifact").set(parts[1]).up()
                .up();
        },
        this.table.frame()
            .where("good", "true")
            .through(
                new QueryValve()
                    .withScanIndexForward(false)
                    .withIndexName("recent")
                    .withConsistentRead(false)
                    // @checkstyle MagicNumber (1 line)
                    .withLimit(25)
                    .withAttributesToGet("artifact")
            )
    );
}
 
Example #16
Source File: XeLink.java    From takes with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param rel Related
 * @param href HREF
 * @param type Content type
 */
public XeLink(final CharSequence rel, final CharSequence href,
    final CharSequence type) {
    super(
        new XeSource() {
            @Override
            public Iterable<Directive> toXembly() {
                return new Directives()
                    .addIf("links")
                    .add("link")
                    .attr("rel", rel.toString())
                    .attr("href", href.toString())
                    .attr("type", type.toString())
                    .up()
                    .up();
            }
        }
    );
}
 
Example #17
Source File: Skeleton.java    From jpeek with MIT License 6 votes vote down vote up
/**
 * Calculate Xembly for a single .class file.
 * @param ctc The class
 * @return Metrics
 */
private static Map.Entry<String, Directives> xembly(final CtClass ctc) {
    ctc.defrost();
    String pkg = ctc.getPackageName();
    if (pkg == null) {
        pkg = "";
    }
    return new MapEntry<>(
        pkg,
        new Directives()
            .add("class")
            .comment(
                Xembler.escape(
                    String.format(
                        "Package: %s; name: %s; file: %s",
                        ctc.getPackageName(),
                        ctc.getName(),
                        ctc.getClassFile().getName()
                    )
                )
            )
            .attr("id", ctc.getSimpleName())
            .append(new XmlClass(ctc))
            .up()
    );
}
 
Example #18
Source File: XeMillis.java    From takes with MIT License 6 votes vote down vote up
@Override
public Iterable<Directive> toXembly() {
    final Directives dirs = new Directives();
    if (this.finish) {
        dirs.xpath(this.name.toString())
            .strict(1)
            .xset(
                String.format(
                    "%d - number(text())",
                    System.currentTimeMillis()
                )
            );
    } else {
        dirs.add(this.name.toString())
            .set(Long.toString(System.currentTimeMillis()));
    }
    return dirs;
}
 
Example #19
Source File: XeMemory.java    From takes with MIT License 6 votes vote down vote up
/**
 * Ctor.
 * @param node Node name
 */
public XeMemory(final CharSequence node) {
    super(
        new XeSource() {
            @Override
            public Iterable<Directive> toXembly() {
                return new Directives().add(node.toString())
                    .attr(
                        "total",
                        XeMemory.mbs(Runtime.getRuntime().totalMemory())
                    )
                    .attr(
                        "free",
                        XeMemory.mbs(Runtime.getRuntime().freeMemory())
                    )
                    .attr(
                        "max",
                        XeMemory.mbs(Runtime.getRuntime().maxMemory())
                    );
            }
        }
    );
}
 
Example #20
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 #21
Source File: Header.java    From jpeek with MIT License 6 votes vote down vote up
@Override
public Iterator<Directive> iterator() {
    try {
        return new Directives()
            .attr(
                "date",
                ZonedDateTime.now().format(
                    DateTimeFormatter.ISO_INSTANT
                )
            )
            .attr("version", new Version().value())
            .iterator();
    } catch (final IOException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example #22
Source File: Item.java    From takes with MIT License 5 votes vote down vote up
@Override
public Iterable<Directive> toXembly() {
    final String name = this.file.getName();
    return new Directives().add("file")
        .add("name").set(name).up()
        .add("size").set(Long.toString(this.file.length()));
}
 
Example #23
Source File: XeTransformTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * XeTransform can build XML response.
 * @throws IOException If some problem inside
 */
@Test
public void buildsXmlResponse() throws IOException {
    MatcherAssert.assertThat(
        IOUtils.toString(
            new RsXembly(
                new XeAppend(
                    "root",
                    new XeTransform<String>(
                        Arrays.asList("Jeff", "Walter"),
                        new XeTransform.Func<String>() {
                            @Override
                            public XeSource transform(final String obj) {
                                return new XeDirectives(
                                    new Directives().add("bowler").set(
                                        obj.toUpperCase(Locale.ENGLISH)
                                    )
                                );
                            }
                        }
                    )
                )
            ).body(),
            StandardCharsets.UTF_8
        ),
        XhtmlMatchers.hasXPaths(
            "/root[count(bowler)=2]",
            "/root/bowler[.='JEFF']"
        )
    );
}
 
Example #24
Source File: RsXemblyTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * RsXembly can modify XML response.
 * @throws Exception If some problem inside
 */
@Test
public void modifiesXmlResponse() throws Exception {
    final Document dom = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder()
        .newDocument();
    final String root = "world";
    dom.appendChild(dom.createElement(root));
    final String query = "/world/hi";
    MatcherAssert.assertThat(
        IOUtils.toString(
            new RsXembly(
                dom,
                new XeDirectives(
                    new Directives()
                        .xpath("/world")
                        .add("hi")
                )
            ).body(),
            StandardCharsets.UTF_8
        ),
        XhtmlMatchers.hasXPath(query)
    );
    MatcherAssert.assertThat(
        dom,
        Matchers.not(
            XhtmlMatchers.hasXPath(query)
        )
    );
}
 
Example #25
Source File: OozieWorkflowGenerator.java    From arbiter with Apache License 2.0 5 votes vote down vote up
/**
 * Add the elements where a given key has multiple values
 * An example of this is the arg tag
 *
 * @param entry A mapping of key to a list of values
 * @param directives The Xembly Directives object to which to add the new XML elements
 */
private void addKeyMultiValueElements(Map.Entry<String, List<String>> entry, Directives directives) {
    for (String value : entry.getValue()) {
        directives.add(entry.getKey())
                .set(value)
                .up();
    }
}
 
Example #26
Source File: RsXemblyTest.java    From takes with MIT License 5 votes vote down vote up
/**
 * RsXembly can build XML response.
 * @throws IOException If some problem inside
 */
@Test
public void buildsXmlResponse() throws IOException {
    MatcherAssert.assertThat(
        IOUtils.toString(
            new RsXembly(
                new XeStylesheet("/a.xsl"),
                new XeAppend(
                    "root",
                    new XeMillis(false),
                    new XeSource() {
                        @Override
                        public Iterable<Directive> toXembly() {
                            return new Directives().add("hey");
                        }
                    },
                    new XeMillis(true)
                )
            ).body(),
            StandardCharsets.UTF_8
        ),
        XhtmlMatchers.hasXPaths(
            "/root/hey",
            "/root/millis",
            "/processing-instruction('xml-stylesheet')[contains(.,'/a')]"
        )
    );
}
 
Example #27
Source File: Items.java    From takes with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public Iterable<Directive> toXembly() throws IOException {
    final Collection<XeSource> items = new LinkedList<>();
    final File[] files = this.home.listFiles();
    if (files != null) {
        for (final File file : files) {
            items.add(new Item(file));
        }
    }
    return new Directives().add("files").append(
        new XeChain(items).toXembly()
    );
}
 
Example #28
Source File: XeAppend.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param target Name of XML element
 * @param src Source
 * @since 1.4
 */
public XeAppend(final CharSequence target, final Scalar<XeSource> src) {
    super(
        new XeSource() {
            @Override
            public Iterable<Directive> toXembly() throws IOException {
                return new Directives().add(target.toString()).append(
                    src.get().toXembly()
                );
            }
        }
    );
}
 
Example #29
Source File: XeChain.java    From takes with MIT License 5 votes vote down vote up
/**
 * Ctor.
 * @param items Sources
 * @since 1.5
 */
public XeChain(final Scalar<Iterable<XeSource>> items) {
    super(
        new XeSource() {
            @Override
            public Iterable<Directive> toXembly() throws IOException {
                final Directives dirs = new Directives();
                for (final XeSource src : items.get()) {
                    dirs.push().append(src.toXembly()).pop();
                }
                return dirs;
            }
        }
    );
}
 
Example #30
Source File: XeDirectives.java    From takes with MIT License 5 votes vote down vote up
/**
 * Transform strings to directives.
 * @param texts Texts
 * @return Directives
 */
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
private static Iterable<Directive> transform(final Iterable<String> texts) {
    final Collection<Directive> list = new LinkedList<>();
    for (final String text : texts) {
        try {
            for (final Directive dir : new Directives(text)) {
                list.add(dir);
            }
        } catch (final SyntaxException ex) {
            throw new IllegalStateException(ex);
        }
    }
    return list;
}