Example usage for org.dom4j.dom DOMDocument createElement

List of usage examples for org.dom4j.dom DOMDocument createElement

Introduction

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

Prototype

public org.w3c.dom.Element createElement(String name) throws DOMException 

Source Link

Usage

From source file:hello.SampleSimpleApplication.java

License:Apache License

private void addBreadcrumbBefore(DOMElement autoTileElement) {
    DOMDocument document = (DOMDocument) autoTileElement.getDocument();
    DOMElement breadcrumbEl = (DOMElement) document.createElement("div");
    //      breadcrumbEl.addAttribute("style", "font-weight: bold; left: 0px; position: absolute; top: 3px; font-size:x-small;");
    breadcrumbEl.addAttribute("style", "left: 0px; position: absolute; top: 3px; font-size:x-small;");
    Element lastChildElement = (Element) bookmarks.selectSingleNode("*[last()]");
    addBreadcrumbItem(lastChildElement, breadcrumbEl);
    DOMElement h4El = (DOMElement) autoTileElement.selectSingleNode("*");//.detach();
    autoTileElement.insertBefore(breadcrumbEl, h4El);
}

From source file:org.athento.nuxeo.rm.restlets.ConsultaCdCRestlet.java

License:Open Source License

/**
 * Manejador principal del restlet. /*from ww w . java2s  . co  m*/
 * 
 * @param req
 *            Request
 * @param res
 *            Response
 */
@Override
public void handle(Request req, Response res) {
    /* Conflicto con Checkstyle. No se pueden declarar como final los métodos de
     * beans EJB que hagan uso de dependencias inyectadas, ya que dichas
     * dependencias toman el valor null.
     * No se declara como final debido a que en ese caso 
     * la inyección de dependencias dejaría de funcionar.
     */
    String repo = (String) req.getAttributes().get("repo");
    String cdcDocId = (String) req.getAttributes().get("docid");
    if (cdcDocId == null) {
        handleError(res, "you must specify a CdC source document Id.");
    } else {
        String depth = getQueryParamValue(req, "depth", "1");

        if (repo == null || repo.equals("*")) {
            handleError(res, "you must specify a repository");
        } else {

            int profundidad = Integer.parseInt(depth);
            // String cdcPath =
            // Framework.getProperty(ArchivoConstantes.PROPIEDAD_CDC_PATH);
            DOMDocumentFactory domFactory = new DOMDocumentFactory();
            DOMDocument result = (DOMDocument) domFactory.createDocument();
            try {

                navigationContext.setCurrentServerLocation(new RepositoryLocation(repo));
                documentManager = navigationContext.getOrCreateDocumentManager();
                DocumentModel cdcRoot = documentManager.getDocument(new IdRef(cdcDocId));
                if (cdcRoot != null) {
                    Element current = result.createElement("document");

                    current.setAttribute("title", cdcRoot.getTitle());
                    current.setAttribute("type", cdcRoot.getType());
                    current.setAttribute("id", cdcRoot.getId());
                    current.setAttribute("path", cdcRoot.getPathAsString());

                    result.setRootElement((org.dom4j.Element) current);

                    addChildren(result, current, cdcRoot, profundidad);
                } else {
                    Element noEncontrado = result.createElement("cdCNoRegistrado");
                    noEncontrado.setAttribute("variable", ArchivoConstantes.PROPIEDAD_CDC_PATH);
                    noEncontrado.setAttribute("valor", cdcDocId);
                    result.setRootElement((org.dom4j.Element) noEncontrado);
                    LOG.error(
                            "No se ha configurado la ruta del CdC; por favor configure la ruta en la propiedad "
                                    + ArchivoConstantes.PROPIEDAD_CDC_PATH);
                }

                res.setEntity(result.asXML(), MediaType.TEXT_XML);
                res.getEntity().setCharacterSet(CharacterSet.UTF_8);

            }
            /**
             * Conflicto con checkstyle. Es necesario capturar la excepción
             * Exception, dado que el código nativo de Nuxeo lanza dicha
             * excepción. En caso contrario, este código no compilaría
             */
            catch (Exception e) {
                LOG.error(e);
                handleError(res, e);
            }
        }
    }

}

From source file:org.athento.nuxeo.rm.restlets.ConsultaCdCRestlet.java

License:Open Source License

/**
 * Añade un hijo al arbol.// w w w .j av a  2  s  .  com
 * 
 * @param result
 *            XML resultado
 * @param parent
 *            Elemento padre del xml
 * @param root
 *            Documento raíz.
 * @param depth
 *            profundidad
 * @return devuelve un elemento XML
 */
private Element addChildren(DOMDocument result, Element parent, DocumentModel root, int depth) {
    try {

        List<DocumentModel> hijos = documentManager.getChildren(root.getRef());

        for (DocumentModel documento : hijos) {
            String estado = documento.getCurrentLifeCycleState();
            if (!"deleted".equals(estado) && documento.isFolder()) {
                Element hijo = result.createElement("document");

                hijo.setAttribute("title", documento.getTitle());
                hijo.setAttribute("type", documento.getType());
                hijo.setAttribute("id", documento.getId());

                parent.appendChild(hijo);

                if (depth > ArchivoConstantes.NUMERO_UNO) {
                    addChildren(result, hijo, documento, depth - ArchivoConstantes.NUMERO_UNO);
                }
            }
        }
    } catch (ClientException e) {
        LOG.error("No se pudo a&ntilde;adir elementos al xml ", e);
    }
    return parent;
}

From source file:org.athento.nuxeo.rm.restlets.ExtraerCicloDeVida.java

License:Open Source License

/**
 * Manejador principal del restlet. // w w  w.  j  a  v  a  2  s .  c  o  m
 * 
 * @param req
 *            the req
 * @param res
 *            the res
 */
@Override
public void handle(Request req, Response res) {
    /* Conflicto con Checkstyle. No se pueden declarar como final los m&eacute;todos de
     * beans EJB que hagan uso de dependencias inyectadas, ya que dichas
     * dependencias toman el valor null. No se declara como final debido a que en
     * ese caso la inyecci&oacute;n de dependencias dejar&iacute;a de funcionar.
     */
    // Getting the repository and the document id of the document
    String repo = (String) req.getAttributes().get(REPO);
    String docid = (String) req.getAttributes().get(DOCID);

    DocumentModel dm = null;
    try {
        if (repo == null || repo.equals(AN_OBJECT)) {
            handleError(res, "Repositorio no especificado.");
            throw new ClientException("Repositorio no especificado.");
        }

        // Getting the document...
        navigationContext.setCurrentServerLocation(new RepositoryLocation(repo));
        documentManager = navigationContext.getOrCreateDocumentManager();
        if (docid == null || docid.equals(AN_OBJECT)) {
            handleError(res, "identificador de documento no especificado");
            throw new ClientException("Identificador de documento no" + "especificado.");
        } else {
            dm = documentManager.getDocument(new IdRef(docid));
        }

        lifeCycleService = NXCore.getLifeCycleService();
        String lifeCycleName = dm.getLifeCyclePolicy();

        LOG.debug("Ciclo de vida asociado : " + lifeCycleName);

        LifeCycle lifeCycle = lifeCycleService.getLifeCycleByName(lifeCycleName);
        Collection<LifeCycleState> states = lifeCycle.getStates();
        Collection<LifeCycleTransition> transitions = lifeCycle.getTransitions();

        DOMDocumentFactory domFactory = new DOMDocumentFactory();
        DOMDocument result = (DOMDocument) domFactory.createDocument();

        Element current = result.createElement(LIFE_CYCLE);
        current.setAttribute(NAME, lifeCycleName);
        result.setRootElement((org.dom4j.Element) current);

        Element statesElement = result.createElement(STATES);

        for (LifeCycleState state : states) {
            String stateName = state.getName();
            Element stateElement = result.createElement(STATE);
            stateElement.setAttribute(NAME, stateName);
            Element transitionsElement = result.createElement(ALLOWED_TRANSITIONS);
            Collection<String> allowedTransitions = state.getAllowedStateTransitions();
            for (String transitionName : allowedTransitions) {
                Element transitionElement = result.createElement(ALLOWED_TRANSITION);
                transitionElement.setAttribute(NAME, transitionName);
                transitionsElement.appendChild(transitionElement);
            }
            stateElement.appendChild(transitionsElement);
            statesElement.appendChild(stateElement);
        }
        current.appendChild(statesElement);

        Element transitionsListElement = result.createElement(TRANSITIONS);

        for (LifeCycleTransition transition : transitions) {
            Element transitionElement = result.createElement(TRANSITION);
            transitionElement.setAttribute(NAME, transition.getName());
            transitionsListElement.appendChild(transitionElement);
            transitionElement.setAttribute(DESTINATION_STATE, transition.getDestinationStateName());
        }

        current.appendChild(transitionsListElement);

        res.setEntity(result.asXML(), MediaType.TEXT_XML);
        res.getEntity().setCharacterSet(CharacterSet.UTF_8);

    } catch (ClientException e) {
        LOG.info("[RESTLET]Error consultando el ciclo de vida del documento.", e);
        handleError(res, e);
    }
    /**
     * Conflicto con checkstyle. Es necesario capturar la excepci&oacute;n
     * Exception, dado que el c&oacute;digo nativo de Nuxeo lanza dicha excepci&oacute;n.
     * En caso contrario, este c&oacute;digo no compilar&iacute;a
     */
    catch (Exception e) {
        LOG.error("[RESTLET] Error en la ejecuci&oacute;n del restlet ", e);
        handleError(res, e);
    }
}

From source file:org.nuxeo.ecm.platform.sync.server.restAPI.VocabularyRestlet.java

License:Open Source License

@Override
public void handle(Request req, Response res) {

    DOMDocumentFactory domfactory = new DOMDocumentFactory();
    DOMDocument result = (DOMDocument) domfactory.createDocument();

    DirectoryService directoryService;/*w  ww.  ja  v a 2  s .  c om*/
    try {
        directoryService = Framework.getService(DirectoryService.class);
        if (directoryService == null) {
            handleError(result, res, "Unable to get Directory Service");
            return;
        }
    } catch (Exception e) {
        handleError(result, res, e);
        return;
    }

    String vocName = (String) req.getAttributes().get("vocName");
    if ("".equals(vocName)) {
        handleError(result, res, "You must specify a vocabulary name");
        return;
    }

    Session dirSession;
    try {
        dirSession = directoryService.open(vocName);
        String directorySchema = directoryService.getDirectorySchema(vocName);
        Element current = result.createElement("entries");
        result.setRootElement((org.dom4j.Element) current);
        if (directorySchema.equals(VOCABULARY_TYPE_SIMPLE) || directorySchema.equals(VOCABULARY_TYPE_HIER)) {

            SchemaManager schemaManager = Framework.getLocalService(SchemaManager.class);
            Schema vocSchema = schemaManager.getSchema(directorySchema);
            Collection<Field> vocSchemaField = vocSchema.getFields();

            for (DocumentModel entry : dirSession.getEntries()) {
                Element el = result.createElement("entry");
                for (Field field : vocSchemaField) {
                    String fieldName = field.getName().getLocalName();
                    Type type = field.getType();
                    if (type instanceof StringType) {
                        el.setAttribute(fieldName, (String) entry.getProperty(directorySchema, fieldName));
                    } else if (type instanceof LongType) {
                        el.setAttribute(fieldName,
                                ((Long) (entry.getProperty(directorySchema, fieldName) != null
                                        ? entry.getProperty(directorySchema, fieldName)
                                        : 0)).toString());
                    } else if (type instanceof IntegerType) {
                        el.setAttribute(fieldName,
                                ((Integer) (entry.getProperty(directorySchema, fieldName) != null
                                        ? entry.getProperty(directorySchema, fieldName)
                                        : 0)).toString());
                    } else {
                        log.warn(
                                "Vocabulary Restlet serializer only serialize int, long or string fields type. "
                                        + fieldName + "(" + type.getName() + ") has been ignored");
                    }
                }

                current.appendChild(el);
            }
        } else {
            handleError(result, res, "Selected directory is not a vocabulary");
            return;
        }
    } catch (ClientException e) {
        handleError(result, res, e);
        return;
    }
    try {
        dirSession.close();
    } catch (ClientException e) {
        handleError(result, res, e);
        return;
    }
    res.setEntity(result.asXML(), MediaType.TEXT_XML);
}

From source file:org.nuxeo.ecm.platform.syndication.restAPI.VocabularyRestlet.java

License:Open Source License

@Override
public void handle(Request req, Response res) {

    DOMDocumentFactory domfactory = new DOMDocumentFactory();
    DOMDocument result = (DOMDocument) domfactory.createDocument();

    Locale translationLocal = Locale.getDefault();
    String lang = req.getResourceRef().getQueryAsForm().getFirstValue("lang");

    if (lang != null && !"".equals(lang)) {
        for (Locale loc : Locale.getAvailableLocales()) {
            if (loc.getLanguage().equalsIgnoreCase(lang)) {
                translationLocal = loc;/*from   w w  w.ja v  a 2 s  .  c  om*/
                continue;
            }
        }
    }

    DirectoryService directoryService;
    try {
        directoryService = Framework.getService(DirectoryService.class);
        if (directoryService == null) {
            handleError(result, res, "Unable to get Directory Service");
            return;
        }
    } catch (Exception e) {
        handleError(result, res, e);
        return;
    }

    String vocName = (String) req.getAttributes().get("vocName");
    if ("".equals(vocName)) {
        handleError(result, res, "You must specify a vocabulary name");
        return;
    }

    Session dirSession;
    try {
        dirSession = directoryService.open(vocName);
        String directorySchema = directoryService.getDirectorySchema(vocName);

        if (directorySchema.equals("vocabulary")) {
            Element current = result.createElement("entries");
            result.setRootElement((org.dom4j.Element) current);

            for (DocumentModel entry : dirSession.getEntries()) {
                Element el = result.createElement("entry");
                el.setAttribute("id", entry.getId());
                el.setAttribute("label", (String) entry.getProperty("vocabulary", "label"));
                el.setAttribute("translatedLabel",
                        getTranslation((String) entry.getProperty("vocabulary", "label"), translationLocal));
                current.appendChild(el);
            }
        } else if (directorySchema.equals("xvocabulary")) {
            Tree.Builder treeBuilder = new Tree.Builder();

            for (DocumentModel doc : dirSession.getEntries()) {
                String id = doc.getId();
                String label = (String) doc.getProperty("xvocabulary", "label");
                String translatedLabel = getTranslation(label, translationLocal);
                String parent = (String) doc.getProperty("xvocabulary", "parent");

                SimpleVocabulary voca = new SimpleVocabulary(id, label, translatedLabel, vocName);

                try {
                    treeBuilder.addElement(parent, constructHierarchicalParent(vocName, parent), voca);
                } catch (Exception e) {
                    handleError(result, res, "Problems when listing all the entries from vocabulary");
                }
            }
            Tree tree = treeBuilder.build();
            tree.buildXML(result);
        } else {
            handleError(result, res, "Selected directory is not a vocabulary");
            return;
        }
    } catch (ClientException e) {
        handleError(result, res, e);
        return;
    }

    try {
        dirSession.close();
    } catch (ClientException e) {
        handleError(result, res, e);
        return;
    }

    res.setEntity(result.asXML(), MediaType.TEXT_XML);
    res.getEntity().setCharacterSet(CharacterSet.UTF_8);
}

From source file:org.nuxeo.ecm.platform.syndication.serializer.SimpleXMLSerializer.java

License:Open Source License

@Override
public String serialize(ResultSummary summary, DocumentModelList docList, List<String> columnsDefinition,
        HttpServletRequest req) throws ClientException {
    if (docList == null) {
        return EMPTY_LIST;
    }/*from w  ww  .  jav a  2 s .c  om*/

    DOMDocumentFactory domfactory = new DOMDocumentFactory();
    DOMDocument result = (DOMDocument) domfactory.createDocument();

    Element current = result.createElement(rootNodeName);
    result.setRootElement((org.dom4j.Element) current);

    Element pagesElement = result.createElement("pages");
    pagesElement.setAttribute("pages", Integer.toString(summary.getPages()));
    pagesElement.setAttribute("pageNumber", Integer.toString(summary.getPageNumber()));
    current.appendChild(pagesElement);

    for (DocumentModel doc : docList) {
        Element el = result.createElement(docNodeName);
        el.setAttribute("id", doc.getId());

        for (String colDef : columnsDefinition) {
            ResultField res = getDocumentProperty(doc, colDef);
            el.setAttribute(res.getName(), res.getValue());
        }
        current.appendChild(el);
    }

    return result.asXML();
}

From source file:org.nuxeo.ecm.platform.syndication.vocabularies.Tree.java

License:Open Source License

public String asXML() {
    DOMDocumentFactory domfactory = new DOMDocumentFactory();
    DOMDocument document = (DOMDocument) domfactory.createDocument();

    Element current = document.createElement("entries");
    document.setRootElement((org.dom4j.Element) current);

    buildXML(rootNodes, current, document);
    return document.asXML();
}

From source file:org.nuxeo.ecm.platform.syndication.vocabularies.Tree.java

License:Open Source License

public void buildXML(DOMDocument document) {
    Element current = document.createElement("entries");
    document.setRootElement((org.dom4j.Element) current);

    buildXML(rootNodes, current, document);
}

From source file:org.nuxeo.ecm.platform.syndication.vocabularies.Tree.java

License:Open Source License

private static void buildXML(List<HierarchicalVocabulary> nodes, Element currentElement, DOMDocument document) {

    for (HierarchicalVocabulary voca : nodes) {
        Element element = document.createElement("entry");
        element.setAttribute("id", voca.getVocabulary().getId());
        element.setAttribute("label", voca.getVocabulary().getLabel());
        element.setAttribute("translatedLabel", voca.getVocabulary().getTranslatedLabel());
        if (voca.hasParent()) {
            element.setAttribute("parent", voca.getParent().getVocabulary().getId());
        }//from  w ww . j a  va2  s.co m
        if (voca.hasChildren()) {
            buildXML(voca.getChildren(), element, document);
        }
        currentElement.appendChild(element);
    }
}