Example usage for org.dom4j Element add

List of usage examples for org.dom4j Element add

Introduction

In this page you can find the example usage for org.dom4j Element add.

Prototype

void add(Namespace namespace);

Source Link

Document

Adds the given Namespace to this element.

Usage

From source file:nl.tue.gale.ae.processor.xmlmodule.ExampleModule.java

License:Open Source License

@Override
public Element traverse(Element element, Resource resource) throws ProcessorException {
    Element pre = createHTMLElement("pre");
    @SuppressWarnings("unchecked")
    List<Node> content = (List<Node>) element.content();
    content = ImmutableList.copyOf(content);
    for (Node node : content) {
        node.detach();/*w w w.  j a  v  a 2  s.co m*/
        pre.add(node);
    }
    replaceNode(element, pre);
    return pre;
}

From source file:nl.tue.gale.ae.processor.xmlmodule.MCModule.java

License:Open Source License

public Element traverse(Element element, Resource resource) throws ProcessorException {
    try {//from   ww  w.j  ava2s.c om
        GaleContext gale = GaleContext.of(resource);

        Element resultElement = element.element("result");
        if (resultElement != null)
            element.remove(resultElement);
        processor.traverseChildren(element, resource);
        if (resultElement != null)
            element.add(resultElement);

        Test test = readTest(element);

        boolean eval = (Boolean) gale.eval(test.expr);
        if (!eval) {
            GaleUtil.replaceNode(element,
                    DocumentFactory.getInstance().createText((test.alt == null ? "" : test.alt)));
            return null;
        }

        test.create();
        String guid = GaleUtil.newGUID();
        gale.req().getSession().setAttribute(guid, test);
        String url = GaleUtil.getRequestURL(gale.req());
        UrlEncodedQueryString qs = UrlEncodedQueryString.parse(URIs.of(url));
        if ("true".equals(qs.get("frame"))) {
            qs.remove("frame");
            qs.append("framewait", "true");
        }
        qs.append("plugin", plugin);
        qs.append("guid", guid);
        url = qs.apply(URIs.of(url)).toString();
        Node n = resource.getTyped(Node.class, "nl.tue.gale.ae.processor.xmlmodule.AdaptLinkModule.content");
        Element result = test.toXHTML(url, n);

        return (Element) GaleUtil.replaceNode(element, result);
    } catch (Exception e) {
        e.printStackTrace();
        return (Element) GaleUtil.replaceNode(element, GaleUtil.createErrorElement("[" + e.getMessage() + "]"));
    }
}

From source file:nl.tue.gale.ae.processor.xmlmodule.MCModule.java

License:Open Source License

@SuppressWarnings("unchecked")
private Question readQuestion(Element element) {
    Element q = DocumentFactory.getInstance().createElement("span", xhtmlns);
    for (Node n : (List<Node>) element.content()) {
        boolean b = true;
        if (n instanceof Element)
            if (((Element) n).getName().equals("answer") || ((Element) n).getName().equals("concept_relation"))
                b = false;/* w w  w  . j  ava2s. c o  m*/
        if (b)
            q.add((Node) n.clone());
    }
    Question result = (new Question()).setQuestion(q).setCount(new Integer(element.attributeValue("answers")))
            .setRight(new Integer(element.attributeValue("right")));
    //Check if the question has an ID.
    if (element.attributeValue("id") != null && !"".equals(element.attributeValue("id")))
        result.setId(new Integer(element.attributeValue("id")));
    if ("checkbox".equals(element.attributeValue("type")))
        result.setType(1);
    for (Element a : (List<Element>) element.elements("answer"))
        result.getAnswers().add(readAnswer(a));

    /*
     * Created by: Vinicius Ramos
     * DATE: Sept 13th 2012
     * 
     * READ the concepts in XHTML
     */
    int v = 0;
    //Read in xml file all the concepts related to the question
    for (Element c : (List<Element>) element.elements("concept_relation")) {
        result.getConcepts().add(c.getText());
    }

    return result;
}

From source file:nl.tue.gale.ae.processor.xmlmodule.MCModule.java

License:Open Source License

@SuppressWarnings("unchecked")
private Answer readAnswer(Element element) {
    Element a = DocumentFactory.getInstance().createElement("span", xhtmlns);
    for (Node n : (List<Node>) element.content()) {
        boolean b = true;
        if (n instanceof Element)
            if (((Element) n).getName().equals("explain"))
                b = false;// www. j a va  2s. c  o  m
        if (b)
            a.add((Node) n.clone());
    }
    Answer result = (new Answer()).setAnswer(a).setExplain(element.element("explain"))
            .setCorrect(new Boolean(element.attributeValue("correct")));
    //Check if the answer has an ID.
    if (element.attributeValue("id") != null && !"".equals(element.attributeValue("id")))
        result.setId(new Integer(element.attributeValue("id")));

    return result;
}

From source file:nl.tue.gale.ae.processor.xmlmodule.ObjectModule.java

License:Open Source License

public Element traverse(Element element, Resource resource) throws ProcessorException {
    try {/* w  w  w  .ja v  a 2s.  c om*/
        GaleContext gc = GaleContext.of(resource);
        processor.traverseChildren(element, resource);
        Element xml = null;
        if (getDepth(resource) > MAX_DEPTH)
            throw new IllegalArgumentException(
                    "maximum object inclusion reached (possible recursion detected)");
        if (element.attributeValue("data") != null) {
            if (element.attributeValue("data").trim().equals(""))
                throw new IllegalArgumentException("object inclusion with empty 'data' attribute");
            URI orgURI = URIs.of(resource.get("original-url").toString());
            URI uri = orgURI.resolve(element.attributeValue("data"));
            URL location = GaleUtil.generateURL(uri.toString(), gc.gc().getHomeDir());
            resource.put("original-url", uri.toString());
            String orgMime = gc.mime();
            resource.put("mime", GaleUtil.getMime(location.toString()));
            String orgObject = (String) resource.get("nl.tue.gale.object");
            resource.put("nl.tue.gale.object", "true");
            xml = GaleUtil.parseXML(location).getRootElement();
            Element root = GaleUtil.createNSElement("root", "");
            root.add(xml);
            incDepth(resource);
            processor.traverse(root, resource);
            decDepth(resource);
            xml = (Element) root.elements().get(0);
            resource.put("mime", orgMime);
            resource.put("original-url", orgURI.toString());
            if (orgObject == null)
                resource.remove("nl.tue.gale.object");
            else
                resource.put("nl.tue.gale.object", orgObject);
        } else if (element.attributeValue("name") != null) {
            URI objectURI = gc.conceptUri().resolve(element.attributeValue("name"));
            URL url = new URL(GaleUtil.getContextURL(gc.req()).toString() + "/concept/" + objectURI.toString());
            objectURI = URIs.builder().uri(objectURI).query(null).build();
            Resource objectResource = gc.pm().createResource(GaleUtil.wrappedRequest(gc.req(), url),
                    GaleUtil.wrappedResponse(gc.resp()));
            objectResource.put("nl.tue.gale.userUri", gc.userUri());
            objectResource.put("nl.tue.gale.conceptUri", objectURI);
            objectResource.put("nl.tue.gale.parentConceptUri", gc.conceptUri());
            objectResource.put("nl.tue.gale.object", "true");
            objectResource.setUsed("response");
            setDepth(objectResource, getDepth(resource) + 1);

            gc.pm().processResource(objectResource);
            if (GaleContext.resp(objectResource).getBufferSize() != 0)
                throw new IllegalArgumentException("object not found");
            xml = GaleContext.xml(objectResource);
        }
        GaleUtil.replaceNode(element, xml);
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return (Element) GaleUtil.replaceNode(element, GaleUtil.createErrorElement("[" + e.getMessage() + "]"));
    }
}

From source file:nl.tue.gale.ae.processor.xmlmodule.RepositoryModule.java

License:Open Source License

private void moveContent(Element source, Element target) {
    @SuppressWarnings("unchecked")
    List<Node> content = (List<Node>) source.content();
    for (Node node : ImmutableList.copyOf(content)) {
        node.detach();// w ww .  j  a v a2s  .  co  m
        target.add(node);
    }
}

From source file:nl.tue.gale.ae.processor.xmlmodule.TextModule.java

License:Open Source License

@Override
public Element traverse(Element element, Resource resource) throws ProcessorException {
    GaleContext gale = GaleContext.of(resource);

    if (!includeBlock(element, resource))
        return (Element) replaceNode(element, null);

    // find possible class
    String classexpr = null;//  w w  w.j a  v a 2s  . c o m
    EntityValue ev = gale.um()
            .get(URIs.builder().uri(gale.conceptUri()).userInfo(gale.userId()).fragment("tags.class").build());
    if (ev != null)
        classexpr = ev.getValueString();
    if (classexpr != null && !"".equals(classexpr)) {
        CacheSession<EntityValue> session = gale.um().openSession();
        try {
            String cl = (String) gale.cm().evaluate(gale.cr(), classexpr,
                    Argument.of("gale", "nl.tue.gale.ae.GaleContext", gale, "session",
                            "nl.tue.gale.common.cache.CacheSession", session, "element", "org.dom4j.Element",
                            element));
            if (cl != null)
                element.addAttribute("class", cl);
        } catch (Exception e) {
            e.printStackTrace();
            return (Element) replaceNode(element, GaleUtil.createErrorElement("[" + e.getMessage() + "]"));
        }
    }

    // create result element
    Element result;
    if (element.attributeValue("class") != null)
        result = createHTMLElement("div").addAttribute("class", element.attributeValue("class"));
    else if (element.attributeValue("id") != null)
        result = createHTMLElement("div").addAttribute("id", element.attributeValue("id"));
    else
        result = createHTMLElement("span");

    // handle textual content
    TextHandler handler = handlerMap.get(element.attributeValue("type"));
    if (handler != null) {
        processor.traverseChildren(element, resource);
        handler.handleTextElement(element);
    }

    // copy the content to the new node
    @SuppressWarnings("unchecked")
    List<Node> content = ImmutableList.copyOf((List<Node>) element.content());
    for (Node node : content) {
        node.detach();
        result.add(node);
    }
    replaceNode(element, result);
    return result;
}

From source file:nl.tue.gale.ae.processor.XMLProcessor.java

License:Open Source License

public void processResource(Resource resource) throws ProcessorException {
    if (resource.isUsed("xml"))
        return;//from  w  w  w  .  jav  a 2 s. c o  m
    try {
        GaleContext gale = GaleContext.of(resource);
        String mime = gale.mime();
        if (!("text/xhtml".equals(mime) || "text/xml".equals(mime) || "application/xml".equals(mime)
                || "application/smil".equals(mime)))
            return;
        Element xml = GaleUtil.createNSElement("root", "");
        xml.add(gale.xml());
        traverse(xml, resource);
        gale.getResource().put("xml", xml.elements().get(0));
    } catch (Exception e) {
        throw new ProcessorException("unable to process xml document", e);
    }
}

From source file:nl.tue.gale.common.XPPEntityReader.java

License:Open Source License

protected Document parseDocument() throws DocumentException, IOException, XmlPullParserException {
    DocumentFactory df = getDocumentFactory();
    Document document = df.createDocument();
    Element parent = null;
    XmlPullParser pp = getXPPParser();//w  ww .  j av  a 2 s  .com
    pp.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
    pp.setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false);
    defineEntities(pp);

    while (true) {
        int type = pp.nextToken();

        switch (type) {
        case XmlPullParser.PROCESSING_INSTRUCTION: {
            String text = pp.getText();
            int loc = text.indexOf(" ");

            if (loc >= 0) {
                String target = text.substring(0, loc);
                String txt = text.substring(loc + 1);
                document.addProcessingInstruction(target, txt);
            } else {
                document.addProcessingInstruction(text, "");
            }

            break;
        }

        case XmlPullParser.COMMENT: {
            if (parent != null) {
                parent.addComment(pp.getText());
            } else {
                document.addComment(pp.getText());
            }

            break;
        }

        case XmlPullParser.CDSECT: {
            if (parent != null) {
                parent.addCDATA(pp.getText());
            } else {
                String msg = "Cannot have text content outside of the " + "root document";
                throw new DocumentException(msg);
            }

            break;
        }

        case XmlPullParser.ENTITY_REF:
            if (parent != null) {
                if (pp.getName().equals("gt")) {
                    parent.addText(">");
                } else if (pp.getName().equals("lt")) {
                    parent.addText("<");
                } else if (pp.getName().equals("amp")) {
                    parent.addText("&");
                } else if (pp.getName().equals("quot")) {
                    parent.addText("\"");
                } else
                    parent.addEntity(pp.getName(), "&" + pp.getName() + ";");
            }
            break;

        case XmlPullParser.END_DOCUMENT:
            return document;

        case XmlPullParser.START_TAG: {
            QName qname = (pp.getPrefix() == null) ? df.createQName(pp.getName(), pp.getNamespace())
                    : df.createQName(pp.getName(), pp.getPrefix(), pp.getNamespace());
            Element newElement = df.createElement(qname);
            int nsStart = pp.getNamespaceCount(pp.getDepth() - 1);
            int nsEnd = pp.getNamespaceCount(pp.getDepth());

            for (int i = nsStart; i < nsEnd; i++) {
                if (pp.getNamespacePrefix(i) != null) {
                    newElement.addNamespace(pp.getNamespacePrefix(i), pp.getNamespaceUri(i));
                }
            }

            for (int i = 0; i < pp.getAttributeCount(); i++) {
                QName qa = (pp.getAttributePrefix(i) == null) ? df.createQName(pp.getAttributeName(i))
                        : df.createQName(pp.getAttributeName(i), pp.getAttributePrefix(i),
                                pp.getAttributeNamespace(i));
                newElement.addAttribute(qa, pp.getAttributeValue(i));
            }

            if (parent != null) {
                parent.add(newElement);
            } else {
                document.add(newElement);
            }

            parent = newElement;

            break;
        }

        case XmlPullParser.END_TAG: {
            if (parent != null) {
                parent = parent.getParent();
            }

            break;
        }

        case XmlPullParser.TEXT: {
            String text = pp.getText();

            if (parent != null) {
                parent.addText(text);
            } else {
                String msg = "Cannot have text content outside of the " + "root document";
                throw new DocumentException(msg);
            }

            break;
        }

        default:
            break;
        }
    }
}