Example usage for org.dom4j.dom DOMDocumentFactory DOMDocumentFactory

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

Introduction

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

Prototype

DOMDocumentFactory

Source Link

Usage

From source file:hello.SampleSimpleApplication.java

License:Apache License

@Override
public void run(String... args) {
    System.out.println(this.helloWorldService.getHelloMessage());
    System.out.println(year);//from   w  ww . ja  v  a  2  s  . c o m
    workDir = workDir();
    dirJsonName = workDir + "OUT1json/";
    dirLargeHtmlName = workDir + "OUT1html/";
    dirJsonStart = Paths.get(dirJsonName);

    domReader.setDocumentFactory(new DOMDocumentFactory());
    startMillis = new DateTime();
    System.out.println("The time is now " + dateFormat.format(startMillis.toDate()));
    logger.debug(dirJsonStart.toString());
    filesCount = countFiles2(dirJsonStart.toFile());
    logger.debug("Files count " + filesCount + ". The time is now " + dateFormat.format(new Date()));
    logger.debug(dirJsonName);
    try {
        makeLargeHTML();
        //makePdfFromHTML();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:hello.W2j.java

License:Apache License

@Override
public void run(String... args) {
    System.out.println(this.helloWorldService.getHelloMessage());
    System.out.println(year);//from   w  w  w .  ja va 2 s.c  o m
    workDir = workDir();
    dirJsonName = workDir + "OUT1json/";
    dirLargeHtmlName = workDir + "OUT1html/";
    dirPdfName = workDir + "OUT1pdf/";
    pathStart = Paths.get(dirLargeHtmlName);
    outputDir = workDir;
    startMillis = new DateTime();
    System.out.println("--------------------");
    System.out.println(year);
    System.out.println("--------------------");

    domReader.setDocumentFactory(new DOMDocumentFactory());

    //      readAuto(ford1, "c-max_2003.75_06.2003", "ford");
    //      if(true) return;

    //      createAutoIndexDocument();

    Document document = getDomFromStream(domain);
    logger.debug(outputDir);
    File openOutputFolder = openCreateFolder(outputDir);

    logger.debug("" + openOutputFolder);
    List<Element> selectNodes = document
            .selectNodes("/html/body/div/table//a[contains(@href,'workshop-manuals')]");
    for (Element manufacturerAncorElement : selectNodes) {
        //         addOl1li(element);
        String href = manufacturerAncorElement.attributeValue("href");
        if (href.equals(domain))
            continue;
        String[] split = href.split("/");
        String manufacturer = split[split.length - 1];
        logger.debug(href + " :: " + manufacturer);
        //         if(new File(outputDir+"/"+manufacturer).exists())
        //            continue;
        File dm = openCreateFolder(outputDir + "/" + manufacturer);
        Document document2 = getDomFromStream(href);
        if (document2 != null) {
            readManufacturer(manufacturerAncorElement, href, manufacturer, document2);
        }
        //         cnt1++;
    }
    String msg = "url " + domain + " :: overall " + selectNodes.size() + "/" + cntVehicles;
}

From source file:net.unicon.academus.apps.briefcase.migrate.BriefcaseMigrator.java

License:Open Source License

public static void main(String[] args) {

    System.out.println("Starting Briefcase portlet migration of data from Academus 1.5 " + " to Academus 1.6");

    if (args.length == 2) {
        try {//w ww . jav  a  2 s . co  m
            DataSource ds = new SimpleDataSource();

            SAXReader reader = new SAXReader();

            // replace the old urls with the new classpaths
            System.out.println("Updating the resource urls.");
            updateUrl(ds);
            updateSharedResourceUrls(ds);

            // replace the OWNER access type.
            System.out.println("Updating the accessTypes.");
            updateAccessType(ds);

            // set the uni_sequence table for the RdbmsAccessBroker Counter
            // and the FSA_Kernel_Sequencer
            updateSequencers(ds);

            // read the old config file
            // and correct the classpaths for all the access brokers.  
            Document oldDoc = reader.read(args[0]);

            DOMDocumentFactory dFac = new DOMDocumentFactory();

            // Get all access brokers
            List brokers = oldDoc.selectNodes("//access-broker");
            Element broker = null;

            // Change access brokers to point to alchemist instead of academus
            for (int i = 0; i < brokers.size(); i++) {
                broker = (Element) brokers.get(i);
                String implValue = broker.attributeValue("impl").replaceFirst("academus", "alchemist");
                broker.addAttribute("impl", implValue);
            }

            // Get the Access Broker under the personal Drive, and make sure it's a JIT broker
            Element targetsJitAccessBroker = (Element) ((Element) oldDoc.selectNodes(
                    "/briefcase/drive[@handle='personal']/access-broker[@impl='net.unicon.alchemist.access.jit.JitAccessBroker']")
                    .get(0)).detach();

            // Only enter this code if the personal drive section was successful selected
            if (targetsJitAccessBroker != null) {

                // Create new permissions element, mirroring targets element
                Element permissionsJitAccessBroker = (Element) targetsJitAccessBroker.clone();

                // Change handles
                targetsJitAccessBroker.addAttribute("handle", "personal-resourses-t");
                permissionsJitAccessBroker.addAttribute("handle", "personal-resourses-p");

                // Create new permissions access-broker
                Element permAccessBroker = dFac.createElement(new QName("access-broker"), 2);
                permAccessBroker.addAttribute("handle", "personal-jit");
                permAccessBroker.addAttribute("impl", PermissionsAccessBroker.class.getName());

                // Create new access element and add it to permAccessBroker
                Element permAccess = dFac.createElement(new QName("access"), 1);
                permAccess.addAttribute("impl", BriefcaseAccessType.class.getName());
                permAccessBroker.add(permAccess);

                // Create targets and permissions elements and add to the new permissions access-broker
                Element targets = permAccessBroker.addElement("targets");
                targets.add(targetsJitAccessBroker);

                Element permissions = permAccessBroker.addElement("permissions");
                permissions.add(permissionsJitAccessBroker);

                // Add new permissions access broker to the drive
                Element curDrive = (Element) oldDoc.selectNodes("/briefcase/drive[@handle='personal']").get(0);
                curDrive.add(permAccessBroker);

                //
                // Change targets internals
                //

                List targetsAccess = targets.selectNodes("access-broker/jit-rule/behavior/access");
                for (int i = 0; i < targetsAccess.size(); i++) {

                    // Add impl attribute with value of fully-qualified class name
                    ((Element) targetsAccess.get(i)).addAttribute("impl", DummyAccessType.class.getName());

                    // Get all child type elements and remove them
                    List types = ((Element) targetsAccess.get(i)).elements();
                    for (int j = 0; j < types.size(); j++) {
                        ((Element) types.get(j)).detach();
                    }

                    // Add a single dummy element
                    Element eType = dFac.createElement(new QName("type"), 2);
                    eType.addAttribute("value", "GRANT");
                    eType.addAttribute("handle", "DUMMY");

                    ((Element) targetsAccess.get(i)).add(eType);

                }

                // Add internal access broker's access element
                Element targetsIAccessBroker = (Element) (targets.selectNodes("access-broker/access-broker")
                        .get(0));
                Element targetsIAccess = dFac.createElement(new QName("access"), 1);
                targetsIAccess.addAttribute("impl", DummyAccessType.class.getName());
                targetsIAccessBroker.add(targetsIAccess);

                //
                // Change permissions internals
                //

                List permissionsAccess = permissions.selectNodes("access-broker/jit-rule/behavior/access");
                for (int i = 0; i < permissionsAccess.size(); i++) {
                    // Add impl attribute with value of fully-qualified class name
                    ((Element) permissionsAccess.get(i)).addAttribute("impl",
                            BriefcaseAccessType.class.getName());

                    // Get all child type elements and replace them
                    List types = ((Element) permissionsAccess.get(i)).elements();
                    for (int j = 0; j < types.size(); j++) {
                        Attribute value = ((Element) types.get(j)).attribute("value");
                        String text = value.getValue();
                        value.setValue("GRANT");

                        if (text.equals("0")) {
                            BriefcaseAccessType[] aTypes = BriefcaseAccessType.getInstances();
                            ((Element) types.get(j)).addAttribute("handle", aTypes[0].getName());

                            for (int k = 1; k < aTypes.length; k++) {
                                Element eType = dFac.createElement(new QName("type"), 2);
                                eType.addAttribute("value", "GRANT");
                                eType.addAttribute("handle", aTypes[k].getName());
                                ((Element) permissionsAccess.get(i)).add(eType);
                            }
                        } else {
                            ((Element) types.get(j)).addAttribute("handle",
                                    BriefcaseAccessType.getAccessType(Integer.parseInt(text)).getName());
                        }
                    }

                }

                // Change other elements in the permissions section
                List permissionsBehavior = permissions.selectNodes("access-broker/jit-rule/behavior");
                for (int i = 0; i < permissionsBehavior.size(); i++) {
                    Element trigger = (Element) ((Element) permissionsBehavior.get(i)).elements("trigger")
                            .get(0);
                    Element target = (Element) ((Element) permissionsBehavior.get(i)).elements("target").get(0);
                    Element creator = (Element) ((Element) permissionsBehavior.get(i)).elements("creator")
                            .get(0);

                    // Insert trigger text into target
                    target.addAttribute("type", "GROUP");
                    target.addText(trigger.getText());

                    // Remove current creator element
                    creator.detach();

                    // Add new current creator element
                    Element eCreator = dFac.createElement(new QName("creator"), 1);
                    eCreator.addAttribute("impl", DummyCreator.class.getName());
                    ((Element) permissionsBehavior.get(i)).add(eCreator);
                }

                // Change internal access broker's name
                Element permissionsIAccessBroker = (Element) (permissions
                        .selectNodes("access-broker/access-broker").get(0));
                permissionsIAccessBroker.addAttribute("handle", "personal-resources-p-i");

                // Add internal access broker's access element
                Element permissionsIAccess = dFac.createElement(new QName("access"), 1);
                permissionsIAccess.addAttribute("impl", BriefcaseAccessType.class.getName());
                permissionsIAccessBroker.add(permissionsIAccess);

            }

            List access = oldDoc.selectNodes("/briefcase/drive[@handle!='personal']//access");
            for (int i = 0; i < access.size(); i++) {

                // Add impl attribute with value of fully-qualified class name
                ((Element) access.get(i)).addAttribute("impl", BriefcaseAccessType.class.getName());

                List types = ((Element) access.get(i)).elements();
                for (int j = 0; j < types.size(); j++) {
                    Attribute value = ((Element) types.get(j)).attribute("value");
                    String text = value.getValue();
                    value.setValue("GRANT");

                    if (text.equals("0")) {
                        BriefcaseAccessType[] aTypes = BriefcaseAccessType.getInstances();
                        ((Element) types.get(j)).addAttribute("handle", aTypes[0].getName());

                        for (int k = 1; k < aTypes.length; k++) {
                            Element eType = dFac.createElement(new QName("type"), 2);
                            eType.addAttribute("value", "GRANT");
                            eType.addAttribute("handle", aTypes[k].getName());
                            ((Element) access.get(i)).add(eType);
                        }
                    } else {
                        ((Element) types.get(j)).addAttribute("handle",
                                BriefcaseAccessType.getAccessType(Integer.parseInt(text)).getName());
                    }
                }
            }

            // add impl attribute to specify the UserDirectory impl to user-attribute element
            List userAttr = oldDoc.selectNodes("//user-attribute");
            for (int i = 0; i < userAttr.size(); i++) {
                ((Element) userAttr.get(i)).addAttribute("impl",
                        "net.unicon.academus.apps.briefcase.UserAttributeDirectory");
            }

            //replace the resource factory urls  
            List entries = oldDoc
                    .selectNodes("/briefcase/drive[@handle!='personal']//access-broker/entry[@target!='']");
            for (int i = 0; i < entries.size(); i++) {
                ((Element) entries.get(i)).addAttribute("target", ((Element) entries.get(i))
                        .attributeValue("target").replaceAll("academus.resource.factory", "demetrius.fac"));
            }

            // add access element to specify the AccessType to the RdbmsAccessBroker
            brokers = oldDoc.selectNodes("/briefcase/drive[@handle!='personal']//access-broker[@impl='"
                    + RdbmsAccessBroker.class.getName() + "']");

            for (int i = 0; i < brokers.size(); i++) {
                broker = (Element) brokers.get(i);
                Element eType = dFac.createElement(new QName("access"), 1);
                eType.addAttribute("impl", BriefcaseAccessType.class.getName());
                broker.add(eType);
            }

            // add the civis address book information.
            Element drive = (Element) oldDoc.selectSingleNode("briefcase");
            drive.addComment("Civis implementation to be used to resolve usernames and group paths"
                    + " to academus users and groups. This should not require"
                    + " modification, as it utilized the Academus framework for gathering this"
                    + " information.");

            Element civis = dFac.createElement("civis");
            civis.addAttribute("id", "addressBook");
            civis.addAttribute("impl", "net.unicon.civis.fac.academus.AcademusCivisFactory");

            Element restrictor = dFac.createElement("restrictor");
            restrictor.addAttribute("impl", "net.unicon.civis.grouprestrictor.AcademusGroupRestrictor");
            civis.add(restrictor);

            drive.add(civis);

            File f = new File(args[1]);
            PrintWriter pw = new PrintWriter(new FileOutputStream(f));
            pw.write(oldDoc.asXML());
            pw.flush();
            pw.close();

            System.out.println(
                    "Done. Enjoy !! \n Remember to the use the migrated config file with the 1.6 deploy.");

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        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  . jav  a  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&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");
    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. //w  w w. ja v  a2  s  .  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.
     */
    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&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(e);
                handleError(res, e);
            }
        }
    }

}

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.com
 * 
 * @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.athento.nuxeo.rm.restlets.HistoricoDocumentoRestlet.java

License:Open Source License

/**
 * Manejador principal del restlet. //w w w .j  av  a 2  s . 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. j  ava 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.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;/*from   w w  w. java 2 s  .  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;// w  w  w  . ja v a 2  s.  c o m
    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;
}