Example usage for org.dom4j DocumentFactory getInstance

List of usage examples for org.dom4j DocumentFactory getInstance

Introduction

In this page you can find the example usage for org.dom4j DocumentFactory getInstance.

Prototype

public static synchronized DocumentFactory getInstance() 

Source Link

Document

Access to singleton implementation of DocumentFactory which is used if no DocumentFactory is specified when building using the standard builders.

Usage

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

License:Open Source License

@SuppressWarnings("unchecked")
static Element processLayoutConfig(Element layoutConfig) {
    if (layoutConfig.getName().equals("view")) {
        layoutConfig.setQName(//www.j  a  v  a2 s . com
                DocumentFactory.getInstance().createQName("view", "", "http://gale.tue.nl/adaptation"));
    } else if (layoutConfig.getName().equals("struct")) {
        Element table = GaleUtil.createHTMLElement("table").addAttribute("cellspacing", "0")
                .addAttribute("cellpadding", "3").addAttribute("width", "100%").addAttribute("height", "100%")
                .addAttribute("border", "0");
        boolean rows = layoutConfig.attributeValue("rows") != null;
        String attrname = (rows ? "height" : "width");
        String[] sizes = (rows ? layoutConfig.attributeValue("rows").split(";")
                : layoutConfig.attributeValue("cols").split(";"));
        Element tr = null;
        if (!rows) {
            tr = GaleUtil.createHTMLElement("tr");
            table.add(tr);
        }
        int i = 0;
        List<Element> elist = new LinkedList<Element>();
        elist.addAll(layoutConfig.elements());
        for (Element child : elist) {
            if (rows) {
                tr = GaleUtil.createHTMLElement("tr");
                table.add(tr);
            }
            Element td = GaleUtil.createHTMLElement("td").addAttribute("valign", "top")
                    .addAttribute(attrname, sizes[i]).addAttribute("style", "border-style:none");
            tr.add(td);
            child = processLayoutConfig(child);
            child.detach();
            td.add(child);
            i++;
        }
        return (Element) GaleUtil.replaceNode(layoutConfig, table);
    } else if (layoutConfig.getName().equals("content")) {
        layoutConfig.setQName(DocumentFactory.getInstance().createQName("gale-layoutprocessor-placeholder"));
    } else {
        for (Element child : (List<Element>) layoutConfig.elements())
            processLayoutConfig(child);
    }
    return layoutConfig;
}

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;/*from w ww. j  a  v a2 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);/*  w  ww. j  av  a 2  s.c  o  m*/
    if (bold) {
        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.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 va2  s.  c o m*/
        // 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.CountModule.java

License:Open Source License

public Element traverse(Element element, Resource resource) throws ProcessorException {
    try {//  w w w . j  a va 2 s.  c o m
        processor.traverseChildren(element, resource);
        GaleContext gale = GaleContext.of(resource);
        URI[] conceptList = getUriCache(gale.conceptUri(), gale);
        URI[] visitedConceptList = getVisitedUriCache(gale.conceptUri(), gale);
        boolean todo = "todo".equals(element.attributeValue("method"));
        Integer number = (todo ? conceptList.length - visitedConceptList.length : visitedConceptList.length);
        GaleUtil.replaceNode(element, DocumentFactory.getInstance().createText(number.toString()));
        return null;
    } catch (Exception e) {
        throw new IllegalArgumentException("unable to count concepts: " + e.getMessage(), e);
    }
}

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

License:Open Source License

@SuppressWarnings("unchecked")
private void traverse(Element textElement) {
    boolean flat = ("true".equals(textElement.attributeValue("flat")));
    List<Element> elements = ImmutableList.copyOf((List<Element>) textElement.elements());
    for (Element element : elements) {
        textElement.content().add(textElement.content().indexOf(element),
                DocumentFactory.getInstance().createText("(% " + GaleUtil.serializeXML(element) + " %)"));
        textElement.remove(element);/*from  w w  w  .  ja  v  a  2 s .c om*/
    }
    textElement.normalize();
    List<Node> content = ImmutableList.copyOf((List<Node>) textElement.content());
    for (Node node : content)
        if (node.getNodeType() == Node.TEXT_NODE) {
            textElement.content().addAll(textElement.content().indexOf(node), parse(node.getText(), flat));
            textElement.content().remove(node);
        }
}

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  w w w . j a v  a 2s.  com
        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;//from w  w  w .j  a  v  a2  s .  co  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;/*from  www  . j  a  v a2s.co  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.PluginModule.java

License:Open Source License

@SuppressWarnings("unchecked")
public Element traverse(Element element, Resource resource) throws ProcessorException {
    // first process the children (content of new anchor tag)
    processor.traverseChildren(element, resource);
    // create new anchor tag
    Element a = DocumentFactory.getInstance()
            .createElement(DocumentFactory.getInstance().createQName("a", "", "http://www.w3.org/1999/xhtml"));
    // backward compatibility
    List<Element> dlist = element.elements("linkdescription");
    Element parent = (dlist.size() == 0 ? element : dlist.get(0));
    // add children to new anchor tag
    a.appendContent(parent);//from  www. j  av a 2 s  . c  om
    /*
     * List<Node> nodes = new ArrayList<Node>(); for (Node node :
     * (List<Node>) parent.content()) nodes.add(node); for (Node node :
     * nodes) a.(node);
     */
    // plugin name
    String name = element.attributeValue("name");
    if (name == null)
        name = element.elementText("name");
    // add parameters
    URI reqUri = URIs.of(GaleContext.req(resource).getRequestURL().toString());
    Map<String, String> params = new HashMap<String, String>();
    params.put("plugin", name);
    for (Element child : (List<Element>) element.elements("param"))
        params.put(child.attributeValue("name"), child.attributeValue("value"));
    reqUri = GaleUtil.setURIPart(reqUri, GaleUtil.URIPart.QUERY, GaleUtil.getQueryString(params));
    // finish the new anchor tag
    a.addAttribute("href", reqUri.toString());
    a.addAttribute("class", "good");
    // replace the original tag by the new anchor tag
    GaleUtil.replaceNode(element, a);
    return null;
}