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.plugin.MCPlugin.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public void doPost(Resource resource) throws ProcessorException {
    GaleContext gale = GaleContext.of(resource);
    if ("true".equals(gale.req().getParameter("framewait")))
        return;// ww  w  .  j a  v a  2 s  . c o  m
    try {
        DocumentFactory df = DocumentFactory.getInstance();
        Element html = df.createElement("html", xhtmlns);

        MCModule.Test test = null;
        try {
            test = (MCModule.Test) gale.req().getSession().getAttribute(gale.req().getParameter("guid"));
        } catch (Exception e) {
        }
        if (test == null)
            throw new ProcessorException("unable to find test-data in session");

        Element h1 = df.createElement("h1", xhtmlns).addText(test.getTitle());
        html.add(h1);
        Element ol = df.createElement("ol", xhtmlns);
        html.add(ol);

        int qnr = 0, cnr = 0;

        // Added by Vinicius Ramos - Date: Sept 13th 2012
        Set<String> concepts_error = new TreeSet<String>();
        boolean fail = false;
        //Log the questions and answers
        String logQandA = "";
        int questions = 0;
        int answers = 0;
        for (MCModule.Question q : test.getQuestions()) {
            boolean correct = true;
            Element li = df.createElement("li", xhtmlns);
            li.add((Element) q.getQuestion().clone());
            ol.add(li);
            Element br = df.createElement("br", xhtmlns);
            li.add(br);
            //Log the questions and answers
            if (questions > 0) {
                //Separate questions by "-"
                logQandA += "-";
            }
            questions++;
            logQandA += q.getId() + ":";
            answers = 0;
            for (MCModule.Answer a : q.getAnswers()) {
                int anr = q.getAnswers().indexOf(a);
                boolean checked = checkAnswer(qnr, anr, q.getRight() == 1, gale);
                correct = correct && (checked == a.isCorrect());
                Element ea = a.toXHTML(qnr, anr, q.getRight() == 1);
                ea.addAttribute("disabled", "true");
                if (checked)
                    ea.addAttribute("checked", "true");
                li.add(ea);
                br = df.createElement("br", xhtmlns);
                li.add(br);
                if (checked && a.getExplain() != null && !"".equals(a.getExplain())) {
                    Element i = df.createElement("i", xhtmlns);
                    li.add(i);
                    i.add((Element) a.getExplain().clone());
                    br = df.createElement("br", xhtmlns);
                    li.add(br);
                }
                if (checked) {
                    logQandA += a.getId() + ",";
                    answers++;
                }
            }
            //Remove "," from answers from the last question
            if (answers > 0)
                logQandA = logQandA.substring(0, logQandA.length() - 1);
            br = df.createElement("br", xhtmlns);
            li.add(br);
            qnr++;
            cnr += (correct ? 1 : 0);

            /*
             * Implemented by Vinicius Ramos 
             * DATE: Sept 13th 2012
             * 
             * Get concepts related to the failed questions by the user
             */
            if (!correct) {
                //Store the failed question
                List<String> concepts = q.getConcepts();
                for (String concept : concepts) {
                    concepts_error.add(concept);
                    fail = true;
                }
            }
        }
        double result = (cnr * 1.0) / qnr * 100;

        CacheSession<EntityValue> session = gale.openUmSession();

        /*
         * Implemented by Vinicius Ramos 
         * DATE: Sept 13th 2012
         * 
         * Add links to the concepts related to the wrong answers
         */
        if (fail) {
            session = gale.openUmSession();
            /*Element p = df.createElement("p", xhtmlns);
            p.addText("We recommend you to read the following concepts: ");
            html.add(p);
            Element ul = df.createElement("ul", xhtmlns);
            html.add(ul);*/
            //String failedQuestions = failedQuestions.substring(0, failedQuestions.length()-1);
            //List<String> failedConcepts = new ArrayList<String>();
            for (String concept : concepts_error) {
                //List of failed concepts
                //failedConcepts.add(concept);
                /*Element li = df.createElement("li", xhtmlns);
                ul.add(li);
                Element a = df.createElement("a", adaptns);
                a.addAttribute("href", concept);
                a.addText(getConceptTitleByName(concept, gale));
                li.add(a);*/
                String execCode = test.getReal_knowledge_expr().replaceAll("%concept", concept);
                gale.cm().execute(gale.cr(), execCode, Argument.of("gale", "nl.tue.gale.ae.GaleContext", gale,
                        "session", "nl.tue.gale.common.cache.CacheSession", session));

            }
            //Store the failed concepts in UM
            if (concepts_error.size() > 0) {
                String failedConcepts = new String();
                for (String c : concepts_error) {
                    failedConcepts += c + ",";
                }
                failedConcepts = failedConcepts.substring(0, failedConcepts.length() - 1);
                String execCode = "${#failed-concepts} = \"" + failedConcepts + "\";";
                gale.cm().execute(gale.cr(), execCode, Argument.of("gale", "nl.tue.gale.ae.GaleContext", gale,
                        "session", "nl.tue.gale.common.cache.CacheSession", session));
                execCode = "#{#failed, true};";
                gale.cm().execute(gale.cr(), execCode, Argument.of("gale", "nl.tue.gale.ae.GaleContext", gale,
                        "session", "nl.tue.gale.common.cache.CacheSession", session));
            }
        }

        gale.cm().execute(gale.cr(), test.getAction(),
                Argument.of("gale", "nl.tue.gale.ae.GaleContext", gale, "session",
                        "nl.tue.gale.common.cache.CacheSession", session, "value", "java.lang.Double",
                        new Double(result)));
        session.commit();

        if (isLog()) {
            // log the result
            StringBuffer sb = new StringBuffer();
            sb.append("\"");
            sb.append(gale.userId());
            sb.append("\";\"");
            sb.append(new Date());
            sb.append("\";\"");
            sb.append(gale.conceptUri());
            sb.append("\";\"");
            // Log Questions and Answers FORMAT:  "Q1:a1,a2,...,aN-Q2:a1,a2,...,aN-...-QN:a1,a2,...,aN"  
            sb.append(logQandA);
            sb.append("\";");
            sb.append(result);
            gale.log().log("mctest", sb.toString());
        }

        if (test.isVerbose()) {
            if (test.getResult() != null)
                html.add((Element) test.getResult().clone());
            resource.put("xml", html);
            resource.put("mime", "text/xhtml");
            resource.put("original-url", "gale:/empty.xhtml");
            gale.usedStream();
        } else {
            try {
                Map<String, String[]> params = new HashMap<String, String[]>();
                params.putAll(gale.req().getParameterMap());
                params.remove("plugin");
                params.remove("guid");
                Map.Entry<String, String[]> entry;
                for (Iterator<Map.Entry<String, String[]>> iterator = params.entrySet().iterator(); iterator
                        .hasNext();) {
                    entry = iterator.next();
                    if (entry.getKey().startsWith("q_"))
                        iterator.remove();
                }
                gale.resp().sendRedirect(GaleUtil.getRequestURL(gale.req(), params));
            } catch (Exception e) {
                throw new ProcessorException("unable to redirect", e);
            }
            gale.usedResponse();
        }

    } catch (Exception e) {
        try {
            RequestDispatcher rd = gale.sc().getRequestDispatcher("/ErrorServlet");
            gale.req().getSession().setAttribute("exception",
                    new ProcessorException("unable to evaluate test", e));
            rd.forward(gale.req(), gale.resp());
            gale.usedResponse();
        } catch (Exception ee) {
            throw new ProcessorException("unexpected error while trying to display the errorpage", ee);
        }
    }
}

From source file:nl.tue.gale.ae.processor.view.AbstractView.java

License:Open Source License

protected Element createRowElement(Concept c, int width, boolean bold) {
    DocumentFactory df = DocumentFactory.getInstance();

    Element tr = GaleUtil.createHTMLElement("tr");
    Element td = GaleUtil.createHTMLElement("td").addAttribute("style", "padding-left: " + width + "px;");
    tr.add(td);
    if (bold) {//from w  w w  . j a v a 2  s . c  o m
        Element b = GaleUtil.createHTMLElement("b");
        td.add(b);
        td = b;
    }
    Element a = df.createElement(df.createQName("a", "", "http://gale.tue.nl/adaptation"))
            .addAttribute("href", c.getUriString()).addText(c.getTitle());
    td.add(a);
    return tr;
}

From source file:nl.tue.gale.ae.processor.view.NextView.java

License:Open Source License

public Element getXml(Resource resource, Object... params) {
    GaleContext gale = GaleContext.of(resource);
    String expr = GaleUtil.getParam(params, "expr");
    if (expr == null)
        expr = defaultExpr;/*from  w w  w. j av  a  2  s .c  om*/
    String label = GaleUtil.getParam(params, "label");
    String done = GaleUtil.getParam(params, "done");
    if (done == null)
        done = "end of course";

    TreeNodes nodes = new TreeNodes(gale);
    TreeNode startNode = nodes.get(gale.concept().getUriString());
    TreeNode currentNode = nextNode(startNode, nodes);
    int loop = 0;
    while (currentNode != null && !startNode.equals(currentNode) && loop < loopMax) {
        CacheSession<EntityValue> session = gale.openUmSession();
        session.setBaseUri(URIs.of(currentNode.getConcept()));
        Boolean exprResult = (Boolean) gale.eval(session, expr);
        if (exprResult)
            break;
        currentNode = nextNode(currentNode, nodes);
        loop++;
    }
    if (loop == loopMax)
        return GaleUtil.createHTMLElement("span").addText(done + " (loop)");
    Element span = GaleUtil.createHTMLElement("span");
    if (currentNode == null || startNode.equals(currentNode)) {
        span.addText(done);
        return span;
    }
    if (label != null)
        span.addText(label);
    Element a = GaleUtil.createNSElement("a", GaleUtil.adaptns);
    span.add(a);
    a.addAttribute("href", currentNode.getConcept());
    a.addText(gale.dm().get(URIs.of(currentNode.getConcept())).getTitle());
    return span;
}

From source file:nl.tue.gale.ae.processor.view.StaticTreeView.java

License:Open Source License

private void menuList(TreeNode parent, List<TreeNode> pathlist, int listindex, Element table, TreeNode rootnode,
        GaleContext gale, TreeNodes nodes) {
    if (parent.getChildren().length == 0)
        return;/* ww  w.  j  av  a2  s .  c  om*/
    for (String node : parent.getChildren()) {
        table.add(createRowElement(gale.dm().get(URIs.of(node)), listindex * 15,
                node.equals(rootnode.getConcept())));
        if (listindex < pathlist.size())
            if (node.equals((pathlist.get(listindex)).getConcept()) || node.equals(rootnode.getConcept()))
                menuList(nodes.get(node), pathlist, listindex + 1, table, rootnode, gale, nodes);
    }
}

From source file:nl.tue.gale.ae.processor.view.StaticTreeView.java

License:Open Source License

public Element getXml(Resource resource, Object... params) {
    if ("true".equals(GaleUtil.getParam(params, "css")))
        return getCssXml(resource, params);
    String smaxDepth = GaleUtil.getParam(params, "maxdepth");
    int maxDepth = 20;
    if (smaxDepth != null)
        maxDepth = Integer.parseInt(smaxDepth);

    GaleContext gale = GaleContext.of(resource);

    Element table = GaleUtil.createHTMLElement("table");
    // table.addAttribute("style",
    // "font-family:Tahoma,Arial;font-size:medium");

    TreeNodes nodes = new TreeNodes(gale);
    TreeNode rootnode = nodes.get(gale.conceptUri().toString());

    TreeNode curnode = rootnode;//from w  w w  . ja v  a2 s. c  om
    List<TreeNode> path = new LinkedList<TreeNode>();
    while (curnode != null && maxDepth > 0) {
        path.add(0, curnode);
        curnode = (curnode.getParents().length > 0 ? nodes.get(curnode.getParents()[0]) : null);
        maxDepth--;
    }

    boolean showRoot = (curnode != null);
    while (curnode != null && curnode.getParents().length > 0)
        curnode = nodes.get(curnode.getParents()[0]);
    if (showRoot) {
        table.add(createRowElement(gale.dm().get(URIs.of(curnode.getConcept())), 0,
                curnode.getConcept().equals(rootnode.getConcept())));
    }
    curnode = path.get(0);
    table.add(createRowElement(gale.dm().get(URIs.of(curnode.getConcept())), 0,
            curnode.getConcept().equals(rootnode.getConcept())));
    menuList(curnode, path, 1, table, rootnode, gale, nodes);

    return table;
}

From source file:nl.tue.gale.ae.processor.view.StaticTreeView.java

License:Open Source License

private Element getCssXml(Resource resource, Object[] params) {
    GaleContext gale = GaleContext.of(resource);
    TreeNodes nodes = new TreeNodes(gale);
    TreeNode rootnode = nodes.get(gale.conceptUri().toString());
    TreeNode curnode = rootnode;/*from  w w w.j  a va  2s.co m*/
    List<TreeNode> path = new LinkedList<TreeNode>();
    while (curnode != null) {
        path.add(0, curnode);
        curnode = (curnode.getParents().length > 0 ? nodes.get(curnode.getParents()[0]) : null);
    }

    Element result = GaleUtil.createHTMLElement("div");
    result.addAttribute("id", "static-tree-view");
    curnode = path.get(0);
    Element ul = createMenu(gale, nodes, curnode, rootnode, path);
    ul.addAttribute("id", "nav");
    result.add(ul);
    return result;
}

From source file:nl.tue.gale.ae.processor.view.StaticTreeView.java

License:Open Source License

private Element createMenu(GaleContext gale, TreeNodes nodes, TreeNode curNode, TreeNode rootNode,
        List<TreeNode> path) {
    Element result = GaleUtil.createHTMLElement("ul");
    for (String child : curNode.getChildren()) {
        Element li = createMenuItem(gale, child);
        if (rootNode.getConcept().equals(child))
            li.addAttribute("class", "current");
        if (path.contains(new TreeNode(child, null, null)) && nodes.get(child).getChildren().length > 0) {
            li.add(createMenu(gale, nodes, nodes.get(child), rootNode, path));
        }/* w ww .ja  va 2s.  c  om*/
        result.add(li);
    }
    return result;
}

From source file:nl.tue.gale.ae.processor.view.StaticTreeView.java

License:Open Source License

private Element createMenuItem(GaleContext gale, String conceptName) {
    Element result = GaleUtil.createHTMLElement("li");
    Element a = GaleUtil.createNSElement("a", GaleUtil.adaptns);
    result.add(a);
    Concept c = gale.dm().get(URIs.of(conceptName));
    a.addText(c.getTitle());/*from   www . j a  v  a2s  .  c o  m*/
    a.addAttribute("href", c.getUriString());
    return result;
}

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

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public Element traverse(Element element, Resource resource) throws ProcessorException {
    GaleContext gale = GaleContext.of(resource);
    CacheSession<EntityValue> session = gale.openUmSession();
    try {/*from  w  w  w . j  a  v a2s  . com*/
        // initialization
        processor.traverseChildren(element, resource);
        boolean useParent = !(element.getName().equals("a"));
        Element a = (useParent ? element.getParent() : element);
        String href = a.attributeValue("href");
        URI uri = URIs.of(href);
        //System.out.println(href);
        String anchorid = uri.getFragment();
        href = URIs.builder().uri(uri).fragment(null).build().toString();
        session.setBaseUri(session.resolve(href));

        // possibly add content to the link, based on previous processing
        Node n = resource.getTyped(Node.class, "nl.tue.gale.ae.processor.xmlmodule.AdaptLinkModule.content");
        if (n != null) {
            n = (Node) n.clone();
            a.add(n);
        }

        // should we adapt the class attribute or hide the link
        boolean adapt = (!"false".equals(a.attributeValue("adapt")));
        a.addAttribute("adapt", null);

        // should the link be removed or hidden
        if (adapt) {
            String removeexpr = (String) gale.cfgm().getObject("gale://gale.tue.nl/config/link#remove",
                    resource);
            if (removeexpr != null) {
                boolean remove = false;
                try {
                    remove = (Boolean) gale.eval(session, removeexpr);
                } catch (Exception e) {
                    log.debug(e, e);
                }
                if (remove) {
                    GaleUtil.replaceNode(a, null);
                    return null;
                }
            }

            String hideexpr = (String) gale.cfgm().getObject("gale://gale.tue.nl/config/link#hide", resource);
            if (hideexpr != null) {
                boolean hide = false;
                try {
                    hide = (Boolean) gale.eval(session, hideexpr);
                } catch (Exception e) {
                    log.debug(e, e);
                }
                if (hide) {
                    GaleUtil.replaceNode(a, DocumentFactory.getInstance().createText(a.getText()));
                    return null;
                }
            }
        }

        // determine and set css class
        if (adapt) {
            EntityValue ev = session.get(session.resolve("#link.class"));
            String cssclass = (ev != null ? ev.getValue().toString() : null);
            if (cssclass == null) {
                String classexpr = (String) gale.cfgm().getObject("gale://gale.tue.nl/config/link#classexpr",
                        resource);
                try {
                    cssclass = gale.eval(session, classexpr).toString();
                } catch (Exception e) {
                    log.debug(e, e);
                    cssclass = "unknown";
                }
            }
            a.addAttribute("class", cssclass);
        }

        // add possible exec code
        String exec = element.attributeValue("exec");
        String query = URIs.of(href).getQuery();
        if (exec != null) {
            String guid = GaleUtil.newGUID();
            storeInSession(gale, guid, exec);
            Map<String, String> params = GaleUtil.getQueryParameters(query);
            params.put("plugin", "exec");
            params.put("guid", guid);
            query = GaleUtil.getQueryString(params);
        }

        // add proper link to concept
        String conceptName = (href.startsWith("?") ? gale.concept().getUriString()
                : Concept.getConceptURI(session.getBaseUri()).toString());
        uri = URIs.of(gale.gsb().getConceptManager().getConceptLink(URIs.of(conceptName), gale.req(), query));

        // Added by Vinicius Ramos to log the currentView: "?view=" + gale.currentView()
        a.addAttribute("href", uri.toString() + (anchorid != null ? "#" + anchorid : "")
                + (uri.toString().contains("?") ? "" : "?view=" + gale.currentView()));
        a.setQName(DocumentFactory.getInstance().createQName(a.getName(), "", GaleUtil.xhtmlns));
        if (useParent)
            a.remove(element);

        // add possible icons
        if (adapt) {
            List<String> iconList = (List<String>) gale.cfgm()
                    .getObject("gale://gale.tue.nl/config/link#iconlist", resource);
            Element span = null;
            for (String iconExpr : iconList) {
                try {
                    String icon = (String) gale.eval(session, iconExpr);
                    if (icon == null || "".equals(icon))
                        continue;
                    boolean pre = false;
                    if (icon.startsWith("pre:")) {
                        icon = icon.substring(4);
                        pre = true;
                    }
                    URI iconUri = URIs.of(icon);
                    if (iconUri.isAbsolute()) {
                        // absolute uri
                        if (iconUri.getScheme().equals("gale")) {
                            icon = GaleUtil.getContextURL(gale.req()) + "/"
                                    + GaleUtil.getServletName(gale.req()) + "/${home}" + iconUri.getPath();
                        }
                    } else {
                        // relative uri

                    }
                    if (span == null) {
                        span = DocumentFactory.getInstance().createElement("span", GaleUtil.xhtmlns);
                        a.getParent().content().add(a.getParent().content().indexOf(a), span);
                        a.getParent().content().remove(a);
                        span.add(a);
                    }
                    Element img = DocumentFactory.getInstance().createElement("img", GaleUtil.xhtmlns);
                    img.addAttribute("src", icon);
                    img.addAttribute("align", "bottom");
                    img.addAttribute("alt", "");
                    if (pre)
                        span.content().add(0, img);
                    else
                        span.add(img);
                } catch (Exception e) {
                    log.debug(e, e);
                }
            }
        }
        return null;
    } catch (Exception e) {
        log.debug(e, e);
        return (Element) GaleUtil.replaceNode(element, GaleUtil.createErrorElement("[" + e.getMessage() + "]"));
    } finally {
        session.rollback();
    }
}

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

License:Open Source License

private Element internalParse(String text) {
    try {// w  w w. j av a2s .  c o  m
        Element span = createHTMLElement("span");
        for (Node node : Parser.CREOLE(new Tokens(new Scanner(text))))
            span.add(node);
        return span;
    } catch (Exception e) {
        throw new IllegalArgumentException("unable to parse creole '" + text + "'", e);
    }
}