Example usage for org.dom4j DocumentFactory createElement

List of usage examples for org.dom4j DocumentFactory createElement

Introduction

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

Prototype

public Element createElement(String qualifiedName, String namespaceURI) 

Source Link

Usage

From source file:com.magnet.mmx.tsung.GenTestScript.java

License:Apache License

static String generateDevRegMessageStanza() {
    DevReg reg = new DevReg();
    reg.setDevId("%%ts_user_server:get_unique_id%%"); // let tsung generate a unique id
    //reg.setDevId(devid);
    reg.setOsType(OSType.ANDROID.name());
    reg.setDisplayName("Loadtester");
    reg.setOsVersion("4.4");
    reg.setApiKey(genSettings.apiKey);//  w  w  w  . j  a  va  2  s.c  o m
    //send an IQ request with device registration
    DocumentFactory factory = new DocumentFactory();
    final Element element = factory.createElement(Constants.MMX_DEV_REG, Constants.MMX_NS_DEV);
    element.addAttribute(Constants.MMX_ATTR_COMMAND, Constants.DeviceCommand.REGISTER.name());
    element.setText(reg.toJson());
    IQ devRegIq = new IQ() {
        @Override
        public CharSequence getChildElementXML() {
            return element.asXML();
        }
    };
    devRegIq.setType(IQ.Type.SET);
    devRegIq.setFrom("%%_username%%");
    return devRegIq.toXML().toString();
}

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 w w.  j  a v  a  2s . c om
    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.dm.GDOMFormat.java

License:Open Source License

public static Element toXML(List<Concept> concepts) {
    DocumentFactory df = DocumentFactory.getInstance();
    Element gdom = df.createElement("gdom", GaleUtil.gdomns);
    Set<URI> uriSet = new HashSet<URI>();
    Set<ConceptRelation> relationSet = new HashSet<ConceptRelation>();
    for (Concept concept : concepts) {
        gdom.add(toXML(concept, df));/*from   ww  w .j ava  2 s.co  m*/
        uriSet.add(concept.getUri());
        for (ConceptRelation cr : concept.getInCR())
            relationSet.add(cr);
        for (ConceptRelation cr : concept.getOutCR())
            relationSet.add(cr);
    }
    for (ConceptRelation cr : relationSet) {
        if (uriSet.contains(cr.getInConcept().getUri()) && uriSet.contains(cr.getOutConcept().getUri()))
            gdom.add(toXML(cr, df));
    }
    return gdom;
}

From source file:nl.tue.gale.dm.GDOMFormat.java

License:Open Source License

private static Element toXML(ConceptRelation cr, DocumentFactory df) {
    Element result = df.createElement("relation", GaleUtil.gdomns).addAttribute("name", cr.getName());
    result.addElement("inconcept", GaleUtil.gdomns).addText(cr.getInConcept().getUriString());
    result.addElement("outconcept", GaleUtil.gdomns).addText(cr.getOutConcept().getUriString());
    toXMLProperties(result, cr.getProperties(), df);
    return result;
}

From source file:nl.tue.gale.dm.GDOMFormat.java

License:Open Source License

private static Element toXML(Concept concept, DocumentFactory df) {
    Element result = df.createElement("concept", GaleUtil.gdomns).addAttribute("name", concept.getUriString());
    for (Attribute attr : concept.getAttributes())
        result.add(toXML(attr, df));/*  w  w w  .j  a v a 2s .  c  om*/
    result.addElement("event", GaleUtil.gdomns).addText(concept.getEventCode());
    toXMLProperties(result, concept.getProperties(), df);
    return result;
}

From source file:nl.tue.gale.dm.GDOMFormat.java

License:Open Source License

private static Element toXML(Attribute attr, DocumentFactory df) {
    Element result = df.createElement("attribute", GaleUtil.gdomns).addAttribute("name", attr.getName())
            .addAttribute("type", attr.getType());
    result.addElement("default", GaleUtil.gdomns).addText(attr.getDefaultCode());
    result.addElement("event", GaleUtil.gdomns).addText(attr.getEventCode());
    toXMLProperties(result, attr.getProperties(), df);
    return result;
}

From source file:nl.tue.gale.dm.GDOMFormat.java

License:Open Source License

private static void toXMLProperties(Element result, Map<String, String> properties, DocumentFactory df) {
    for (Map.Entry<String, String> entry : properties.entrySet()) {
        Element property = df.createElement("property", GaleUtil.gdomns).addAttribute("name", entry.getKey())
                .addAttribute("value", entry.getValue());
        result.add(property);/*from w  ww  . java  2s . co  m*/
    }
}

From source file:org.foxbpm.bpmn.converter.BpmnXMLConverter.java

License:Apache License

/**
 * bpmnModel??documnet/*from  w  w w .  ja  v  a  2s .  com*/
 * 
 * @param model
 *            bpmn
 */
public Document convertToXML(BpmnModel model) {

    if (null == model) {
        throw new BpmnConverterException("?XML?!");
    }

    DocumentFactory factory = DocumentFactory.getInstance();
    Document doc = factory.createDocument();
    Element element = factory.createElement(
            BpmnXMLConstants.BPMN2_PREFIX + ':' + BpmnXMLConstants.ELEMENT_DEFINITIONS,
            BpmnXMLConstants.BPMN2_NAMESPACE);
    element.addNamespace(BpmnXMLConstants.XSI_PREFIX, BpmnXMLConstants.XSI_NAMESPACE);
    element.addNamespace(BpmnXMLConstants.DC_PREFIX, BpmnXMLConstants.DC_NAMESPACE);
    element.addNamespace(BpmnXMLConstants.DI_PREFIX, BpmnXMLConstants.DI_NAMESPACE);
    element.addNamespace(BpmnXMLConstants.BPMNDI_PREFIX, BpmnXMLConstants.BPMNDI_NAMESPACE);
    element.addNamespace(BpmnXMLConstants.FOXBPM_PREFIX, BpmnXMLConstants.FOXBPM_NAMESPACE);
    element.addNamespace(BpmnXMLConstants.XSD_PREFIX, BpmnXMLConstants.XSD_NAMESPACE);
    element.addNamespace(BpmnXMLConstants.EMPTY_STRING, BpmnXMLConstants.XMLNS_NAMESPACE);
    // 
    element.addAttribute(BpmnXMLConstants.TARGET_NAMESPACE_ATTRIBUTE, BpmnXMLConstants.XMLNS_NAMESPACE);
    element.addAttribute(BpmnXMLConstants.ATTRIBUTE_ID, "Definitions_1");
    doc.add(element);
    // ??
    try {
        for (Iterator<Process> iterator = model.getProcesses().iterator(); iterator.hasNext();) {
            ProcessExport.writeProcess(iterator.next(), element);
        }
        // ????
        BPMNDIExport.writeBPMNDI(model, element);
    } catch (Exception e) {
        LOGGER.error("?XML???" + model.getProcesses().get(0).getName(), e);
        if (e instanceof BpmnConverterException) {
            throw (BpmnConverterException) e;
        } else {
            throw new BpmnConverterException(
                    "?XML???" + model.getProcesses().get(0).getName(), e);
        }
    }
    return doc;
}

From source file:org.frogx.service.maven.plugin.games.GenerateFrogxResourcesMojo.java

License:Open Source License

public boolean generatePluginDescriptor() {
    // Check requirements
    if (match == null || namespace == null) {
        return false;
    }/*from w  ww .  j  a  va2  s.c o m*/

    // Create XML data
    getLog().info("Generating a game descriptor (" + frogxPluginDescriptor + ").");
    DocumentFactory documentFactory = DocumentFactory.getInstance();
    Element gameEl = documentFactory.createElement("plugin", pluginDescriptorNS);

    Element element = gameEl.addElement("type");
    element.setText("match");

    element = gameEl.addElement("match");
    element.setText(match);

    element = gameEl.addElement("namespace");
    element.setText(namespace);

    if (description != null) {
        element = gameEl.addElement("description");
        element.setText(description);
    }

    if (category != null) {
        element = gameEl.addElement("category");
        element.setText(category);
    }

    Document doc = documentFactory.createDocument(gameEl);
    doc.setXMLEncoding("UTF-8");

    // Check and create the necessary folder
    File genResourceDir = getGeneratedFrogxResourcesDirectory();
    if (!genResourceDir.exists()) {
        genResourceDir.mkdirs();
    }

    // Write the game descriptor
    try {
        writeDocument(doc, new File(getGeneratedFrogxResourcesDirectory(), frogxPluginDescriptor));
    } catch (IOException e) {
        getLog().warn("An Error occured while writing the generated " + "game descriptor. ", e);
        return false;
    }
    return true;
}

From source file:org.orbeon.oxf.xml.dom4j.Dom4jUtils.java

License:Open Source License

public static Element createElement(final String qualifiedName, final String namespaceURI) {
    final DocumentFactory factory = NonLazyUserDataDocumentFactory.getInstance();
    return factory.createElement(qualifiedName, namespaceURI);
}