Example usage for org.dom4j.dom DOMDocument asXML

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

Introduction

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

Prototype

public String asXML() 

Source Link

Usage

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

License:Open Source License

/**
 * Retrieve the arguments of the restlet and returns a XML with the result.
 * /*from  www  .ja va 2s  .c  om*/
 *  
 * @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é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.
     */
    // Getting the repository and the document id of the document
    String repo = (String) req.getAttributes().get("repo");
    String docid = (String) req.getAttributes().get("docid");
    String transition = (String) req.getAttributes().get("transition");

    DocumentModel dm = null;
    try {
        if (repo == null || repo.equals("*")) {
            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("*")) {
            handleError(res, "dentificador de documento no especificado");
            throw new ClientException("Identificador de documento no" + "especificado.");
        } else {
            dm = documentManager.getDocument(new IdRef(docid));
        }
        if (!dm.followTransition(transition)) {
            handleError(res, "Transicion incorrecta");
            throw new ClientException("Transicion incorrecta.");
        }
        documentManager.save();
        String finalState = dm.getCurrentLifeCycleState();
        // build the XML response document holding the ref
        DOMDocumentFactory domfactory = new DOMDocumentFactory();
        DOMDocument resultDocument = (DOMDocument) domfactory.createDocument();
        Element docCreatedElement = resultDocument.addElement("documentNewState");
        docCreatedElement.addAttribute("newState", finalState);
        res.setEntity(resultDocument.asXML(), MediaType.TEXT_XML);

    } catch (ClientException e) {
        LOG.info("[RESTLET]Error en cambiando el estado del documento.", e);
        handleError(res, e);
        return;
    }

}

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

License:Open Source License

/**
 * Manejador principal del restlet. /*from  ww  w  .  j  a va 2  s .  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.ExtraerCicloDeVida.java

License:Open Source License

/**
 * Manejador principal del restlet. //from w  w w. ja va  2s.  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é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.
     */
    // 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.athento.nuxeo.rm.restlets.HistoricoDocumentoRestlet.java

License:Open Source License

/**
 * Manejador principal del restlet. //from   w  w w. j a  va2s .c  o 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&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("*")) {
            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("*")) {
            handleError(res, "dentificador de documento no especificado");
            throw new ClientException("Identificador de documento no" + "especificado.");
        } else {
            dm = documentManager.getDocument(new IdRef(docid));
        }

        documentManager.save();
        List<LogEntry> docHistory = this.computeLogEntries(dm);
        // build the XML response document holding the ref
        DOMDocumentFactory domfactory = new DOMDocumentFactory();
        DOMDocument resultDocument = (DOMDocument) domfactory.createDocument();
        Element docCreatedElement = resultDocument.addElement("LogEntries");
        for (LogEntry logEntry : docHistory) {
            Element logEnt = docCreatedElement.addElement("LogEntry");
            logEnt.addAttribute("category", logEntry.getCategory());
            logEnt.addAttribute("action", logEntry.getEventId());
            logEnt.addAttribute("date", logEntry.getEventDate().toString());
            logEnt.addAttribute("user", logEntry.getPrincipalName());
            String comment = "";
            if (logEntry.getComment() != null) {
                comment = logEntry.getComment().toString();
            }
            logEnt.addAttribute("comment", comment);

        }
        res.setEntity(resultDocument.asXML(), MediaType.TEXT_XML);

    } catch (ClientException e) {
        LOG.info("[RESTLET]Error en cambiando el estado del documento.", e);
        handleError(res, e);
        return;
    }

}

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;/*from  www . jav a  2s . 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;//ww w .  j  av  a2s. c  o m
                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;
    }//w  ww.j a  v  a 2 s . co m

    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.ui.web.restAPI.BaseNuxeoRestlet.java

License:Open Source License

private static void handleError(DOMDocument result, Response res, String message, String classMessage) {
    Element error = result.createElement("error");
    result.setRootElement((org.dom4j.Element) error);
    error.setAttribute("message", message);
    if (classMessage != null) {
        error.setAttribute("class", classMessage);
    }// w w  w . j a  va2s  . co  m
    result.setRootElement((org.dom4j.Element) error);

    Representation rep = new StringRepresentation(result.asXML(), MediaType.APPLICATION_XML);
    rep.setCharacterSet(CharacterSet.UTF_8);
    res.setEntity(rep);
}

From source file:org.nuxeo.ecm.platform.ui.web.restAPI.BrowseRestlet.java

License:Open Source License

@Override
protected void doHandleStatelessRequest(Request req, Response res) {
    String repo = (String) req.getAttributes().get("repo");
    String docid = (String) req.getAttributes().get("docid");

    DOMDocumentFactory domFactory = new DOMDocumentFactory();

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

    if (repo == null || repo.equals("*")) {
        try {/*from  ww  w . j  ava 2 s  .c  om*/
            RepositoryManager repmanager = Framework.getService(RepositoryManager.class);
            Collection<Repository> repos = repmanager.getRepositories();

            Element serversNode = result.createElement("avalaibleServers");
            result.setRootElement((org.dom4j.Element) serversNode);

            for (Repository availableRepo : repos) {
                Element server = result.createElement("server");
                server.setAttribute("title", availableRepo.getName());
                server.setAttribute("url", getRelURL(availableRepo.getName(), "*"));
                serversNode.appendChild(server);
            }
            res.setEntity(result.asXML(), MediaType.TEXT_XML);
            res.getEntity().setCharacterSet(CharacterSet.UTF_8);
            return;
        } catch (Exception e) {
            handleError(result, res, e);
            return;
        }
    } else {
        DocumentModel dm;

        boolean init = initRepository(res, repo);
        boolean isRoot = false;
        try {
            if (init) {
                if (docid == null || docid.equals("*")) {
                    dm = session.getRootDocument();
                    isRoot = true;
                } else {
                    dm = session.getDocument(new IdRef(docid));
                }
            } else {
                handleError(res, "Unable to init repository");
                return;
            }
        } catch (ClientException e) {
            handleError(res, e);
            return;
        }

        Element current = result.createElement("document");
        try {
            current.setAttribute("title", dm.getTitle());
        } catch (Exception e) {
            handleError(res, e);
        }
        current.setAttribute("type", dm.getType());
        current.setAttribute("id", dm.getId());
        current.setAttribute("name", dm.getName());
        if (isRoot) {
            current.setAttribute("url", getRelURL(repo, ""));
        } else {
            current.setAttribute("url", getRelURL(repo, dm.getRef().toString()));
        }
        result.setRootElement((org.dom4j.Element) current);

        if (dm.isFolder()) {
            // Element childrenElem = result.createElement("children");
            // root.appendChild(childrenElem);

            DocumentModelList children;
            try {
                children = session.getChildren(dm.getRef());
            } catch (ClientException e) {
                handleError(result, res, e);
                return;
            }

            for (DocumentModel child : children) {
                Element el = result.createElement("document");
                try {
                    el.setAttribute("title", child.getTitle());
                } catch (DOMException e) {
                    handleError(res, e);
                } catch (ClientException e) {
                    handleError(res, e);
                }
                el.setAttribute("type", child.getType());
                el.setAttribute("id", child.getId());
                el.setAttribute("name", child.getName());
                el.setAttribute("url", getRelURL(repo, child.getRef().toString()));
                current.appendChild(el);
            }
        }

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