Example usage for org.dom4j.dom DOMDocumentFactory createDocument

List of usage examples for org.dom4j.dom DOMDocumentFactory createDocument

Introduction

In this page you can find the example usage for org.dom4j.dom DOMDocumentFactory createDocument.

Prototype

public Document createDocument() 

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 w  w w.j av  a 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");
    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  w  w  w.  ja  v a 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 2 s  .  co 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  av  a2 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&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  ww  w  .j  a  v a 2 s. com*/
    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.BaseQueryModelRestlet.java

License:Open Source License

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

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

    QueryModelService qmService = getQueryModelService(result, res);
    if (qmService == null) {
        return;/*  w w  w  .  ja v a  2s  . c  o  m*/
    }

    String qmName = getQueryModelName(req);

    QueryModelDescriptor qmd = qmService.getQueryModelDescriptor(qmName);
    if (qmd == null) {
        handleError(result, res, "can not find QueryModel " + qmName);
        return;
    }

    CoreSession session = getCoreSession(req, res, null);
    try {
        PagedDocumentsProvider provider = getPageDocumentsProvider(session, qmd, req);

        // get Page number
        Form form = req.getResourceRef().getQueryAsForm();
        String pageS = form.getFirstValue(PAGE_PARAM);
        int page = 0;
        if (pageS != null) {
            try {
                page = Integer.parseInt(pageS);
            } catch (NumberFormatException e) {
                page = 0;
            }
        }
        if (page >= provider.getNumberOfPages()) {
            handleError(result, res, "No Page " + page + " available");
            return;
        }

        // get format
        String format = form.getFirstValue("format");
        if (format == null) {
            format = getDefaultFormat();
        }

        // get Columns definition
        String columnsDefinition = form.getFirstValue("columns");
        if (columnsDefinition == null) {
            columnsDefinition = defaultColumns;
        }

        // get format
        String lang = form.getFirstValue("lang");

        // fetch result
        DocumentModelList dmList = provider.getPage(page);

        ResultSummary summary = new ResultSummary();

        summary.setTitle("Result for search " + qmName);
        summary.setDescription("Result for search " + qmName);
        summary.setAuthor(getUserPrincipal(req).getName());
        summary.setModificationDate(new Date());
        summary.setLink(getRestletFullUrl(req));
        summary.setPages(provider.getNumberOfPages());
        summary.setPageNumber(page);

        if (lang != null) {
            String[] cols = columnsDefinition.split(DocumentModelListSerializer.colDefinitonDelimiter);
            List<String> labels = new ArrayList<String>();
            for (String col : cols) {
                labels.add("label." + col);
            }
            // format result
            SerializerHelper.formatResult(summary, dmList, res, format, columnsDefinition, getHttpRequest(req),
                    labels, lang);
        } else {
            // format result
            SerializerHelper.formatResult(summary, dmList, res, format, columnsDefinition, getHttpRequest(req));
        }
    } catch (Exception e) {
        handleError(res, e);
    } finally {
        try {
            Repository.close(session);
        } catch (Exception e) {
            log.error("Repository close failed", e);
        }
    }
}

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

License:Open Source License

@Override
protected boolean initRepository(Response res, String repoId) {

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

    RepositoryManager rm;//from  w  w w .j a v  a2s .com
    try {
        rm = Framework.getService(RepositoryManager.class);
    } catch (Exception e1) {
        handleError(result, res, e1);
        return false;
    }

    Repository repo = null;
    if (repoId == null) {
        repo = rm.getDefaultRepository();
    } else {
        repo = rm.getRepository(repoId);
    }

    if (repo == null) {
        handleError(res, "Unable to get " + repoId + " repository");
        return false;
    }

    try {
        session = repo.open();
    } catch (Exception e1) {
        handleError(result, res, e1);
        return false;
    }
    if (session == null) {
        handleError(result, res, "Unable to open " + repoId + " repository");
        return false;
    }
    return true;
}

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  .j  a  v  a  2s  .  co  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;
    }/*from   www.jav  a 2s.  c  o 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();
}