Example usage for org.dom4j.dom DOMDocument addElement

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

Introduction

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

Prototype

public Element addElement(String name) 

Source Link

Usage

From source file:com.devoteam.srit.xmlloader.genscript.genscriptCmd.java

License:Open Source License

/**
 * @param args the command line arguments
 *///from  w w  w .ja v  a2  s .co  m
public static void main(String[] args) {

    // Initialisation de MTS core
    ExceptionHandlerSingleton.setInstance(new TextExceptionHandler());
    SingletonFSInterface.setInstance(new LocalFSInterface());
    TextListenerProviderRegistry.instance().register(new FileTextListenerProvider());
    // set the storage location to FILE for logging
    PropertiesEnhanced properties = new PropertiesEnhanced();
    properties.addPropertiesEnhancedComplete("logs.STORAGE_LOCATION", "FILE");
    Config.overrideProperties("tester.properties", properties);

    // S'il n'y a pas d'arguments, on affiche la syntaxe  utiliser
    if (args.length < 3) {
        System.out.println("ERROR => At least two arguments are required : filtre and capture file");
        System.out.println("Usage : genscript <protocol>:<host>:<port> <capturefile> <generatedfile>");
        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.CORE,
                "ERROR => At least two arguments are required : filtre and capture file");
        System.exit(-1);
    }
    // Si le nombre d'argument est bon, on lance la convertion
    System.out.println("-------- GENSCRIPT -------------------------------------------------------");
    System.out.println("START => capture file: " + args[args.length - 2]);
    GlobalLogger.instance().getApplicationLogger().info(TextEvent.Topic.CORE,
            "START => capture file: " + args[args.length - 2]);

    List<FiltreGenerator> listeFiltre = new ArrayList<FiltreGenerator>();
    List<Probe> listeProbe = new ArrayList<Probe>();

    String src = "";
    URI srcURI = null;
    String out = "";
    URI outURI = null;
    String nomPcap = "";

    // Pour chaque lment pass en paramtre
    for (int i = 0; i < args.length; i++) {

        // Si l'argument est un filtre
        if (args[i].matches("[a-zA-Z0-9]+:[a-zA-Z0-9.]+:[0-9]+")) {
            String[] filtre = args[i].split(":");
            listeFiltre.add(new FiltreGenerator(filtre[0], filtre[1], Integer.parseInt(filtre[2])));
        }
    }

    // Cration des URI  partir des paramtres
    // URI du fichier pcap source
    src = args[args.length - 2];
    srcURI = new File(src).toURI();

    // URI du fichier de test  gnrer
    out = args[args.length - 1];
    outURI = new File(out).toURI();

    // On rcupre le nom du fichier pcap
    String[] nomPcapPath = args[args.length - 2].split("/");
    nomPcap = nomPcapPath[nomPcapPath.length - 1].replaceAll("[.]([0-9A-Za-z])+", "");

    // Creation du generateur de script
    ScriptGenerator generator = new ScriptGenerator(outURI);
    generator.setTestcaseName(nomPcap);

    try {
        // Chaque filtre est enregistr dans le gnrateur de script de test
        for (FiltreGenerator fg : listeFiltre) {
            generator.addFiltre(fg);
        }

        // Generation des fichiers de test
        //generator.generateTestFile();
        generator.generateTest();

        // Pour chaque filtre on crer l'objet Probe
        for (FiltreGenerator fg : listeFiltre) {
            System.out.println("CAPTURE filter: => " + fg);
            GlobalLogger.instance().getApplicationLogger().info(TextEvent.Topic.CORE,
                    "CAPTURE filter: => " + fg);
            // Cration de la stack du protocole que l'on souhaite filtrer
            Stack stack = StackFactory.getStack(fg.getProtocole());
            DOMDocument docProbe = new DOMDocument();
            Element root = docProbe.addElement("root");
            root.addAttribute("filename", src);
            // String captureFilter = "host " + fg.getHostName() + " and port " + fg.getHostPort().toString();
            String captureFilter = "host " + fg.getHostName() + " and (port " + fg.getHostPort().toString()
                    + " or not (ip[6:2] & 0x1FFF = 0)) and ip";
            root.addAttribute("captureFilter", captureFilter);

            // Cration de l'objet Probe
            Probe probe = new Probe(stack, root);
            listeProbe.add(probe);

            // On configure le probe pour la gnration de script
            probe.genScript(generator);

            stack.createProbe(probe, fg.getProtocole());
        }

        // Attente de la fin de la capture  partir du fichier
        while (!listeProbe.get(0).getProbeJpcapThread().getStopPossible()) {
        }

        generator.closeTest();

        System.out.println("END => test file: " + args[args.length - 1] + "(See application.log)");
        GlobalLogger.instance().getApplicationLogger().info(TextEvent.Topic.CORE,
                "END => test file: " + args[args.length - 1] + "(See application.log)");

        // On ferme proprement le programme                                      
        System.exit(0);
    } catch (Exception e) {
        System.out.println("EXCEPTION => " + e);
        e.printStackTrace();
        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.CORE, e, "EXCEPTION => ");
        System.exit(-10);
    }
}

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 a  v  a2  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.HistoricoDocumentoRestlet.java

License:Open Source License

/**
 * Manejador principal del restlet. /*from www  .  jav  a2s .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.ui.web.restAPI.CreateDocumentRestlet.java

License:Open Source License

@Override
public void handle(Request req, Response res) {
    String repo = (String) req.getAttributes().get("repo");
    if (repo == null || repo.equals("*")) {
        handleError(res, "you must specify a repository");
        return;//from  w ww.j a  v  a  2s. c o  m
    }

    DocumentModel parentDm;
    PathSegmentService pss;
    try {
        navigationContext.setCurrentServerLocation(new RepositoryLocation(repo));
        documentManager = navigationContext.getOrCreateDocumentManager();
        String parentDocRef = (String) req.getAttributes().get("parentdocid");
        if (parentDocRef != null) {
            parentDm = documentManager.getDocument(new IdRef(parentDocRef));
        } else {
            handleError(res, "you must specify a valid document IdRef for the parent document");
            return;
        }
        pss = Framework.getService(PathSegmentService.class);
    } catch (Exception e) {
        handleError(res, e);
        return;
    }

    String docTypeName = getQueryParamValue(req, DOC_TYPE, DEFAULT_DOCTYPE);
    String titleField = "dublincore:title";
    String title = getQueryParamValue(req, titleField, "New " + docTypeName);

    try {
        DocumentModel newDm = documentManager.createDocumentModel(docTypeName);
        Form queryParameters = req.getResourceRef().getQueryAsForm();
        for (String paramName : queryParameters.getNames()) {
            if (!DOC_TYPE.equals(paramName)) {
                // treat all non doctype parameters as string fields
                newDm.setPropertyValue(paramName, getQueryParamValue(req, paramName, null));
                // TODO: handle multi-valued parameters as StringList fields
            }
            // override the title for consistency
            newDm.setPropertyValue(titleField, title);
        }
        // create the document in the repository
        newDm.setPathInfo(parentDm.getPathAsString(), pss.generatePathSegment(newDm));
        newDm = documentManager.createDocument(newDm);
        documentManager.save();

        // build the XML response document holding the ref
        DOMDocumentFactory domFactory = new DOMDocumentFactory();
        DOMDocument resultDocument = (DOMDocument) domFactory.createDocument();
        Element docElement = resultDocument.addElement(documentTag);
        docElement.addElement(docRepositoryTag).setText(newDm.getRepositoryName());
        docElement.addElement(docRefTag).setText(newDm.getRef().toString());
        docElement.addElement(docTitleTag).setText(newDm.getTitle());
        docElement.addElement(docPathTag).setText(newDm.getPathAsString());
        Representation rep = new StringRepresentation(resultDocument.asXML(), MediaType.APPLICATION_XML);
        rep.setCharacterSet(CharacterSet.UTF_8);
        res.setEntity(rep);
    } catch (ClientException e) {
        handleError(res, e);
    }
}

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

License:Open Source License

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

    DocumentModelList containers = null;
    String docType = getQueryParamValue(req, DOC_TYPE, DEFAULT_DOCTYPE);
    try {/*from  w  w  w .j  a  v  a2 s .c  o m*/
        FileManager fileManager = Framework.getService(FileManager.class);
        containers = fileManager.getCreationContainers(getUserPrincipal(req), docType);
    } catch (Exception e) {
        handleError(res, e);
    }

    // build the XML response document holding the containers info
    DOMDocumentFactory domFactory = new DOMDocumentFactory();
    DOMDocument resultDocument = (DOMDocument) domFactory.createDocument();
    Element containersElement = resultDocument.addElement("containers");
    for (DocumentModel parent : containers) {
        Element docElement = containersElement.addElement(documentTag);
        docElement.addElement(docRepositoryTag).setText(parent.getRepositoryName());
        docElement.addElement(docRefTag).setText(parent.getRef().toString());
        try {
            docElement.addElement(docTitleTag).setText(parent.getTitle());
        } catch (ClientException e) {
            log.error("not setting doc title tag: " + e);
        }
        docElement.addElement(docPathTag).setText(parent.getPathAsString());
    }
    res.setEntity(resultDocument.asXML(), MediaType.TEXT_XML);
    res.getEntity().setCharacterSet(CharacterSet.UTF_8);
}

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

License:Open Source License

@Override
protected void doHandleStatelessRequest(Request req, Response res) {

    String repoId = (String) req.getAttributes().get("repo");
    String docId = (String) req.getAttributes().get("docid");

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

    if (docId != null) {
        // init repo and document
        boolean initOk = initRepositoryAndTargetDocument(res, repoId, docId);
        if (!initOk) {
            return;
        }/* ww w . j av a2 s .com*/
    } else {
        // init repo
        boolean initOk = initRepository(res, repoId);
        if (!initOk) {
            return;
        }

        // init document
        String path = getQueryParamValue(req, "path", null);
        if (path == null) {
            return;
        }
        targetDocRef = new PathRef(path);
        try {
            targetDocument = session.getDocument(targetDocRef);
        } catch (ClientException e) {
            handleError(result, res, "Unable to get document " + path);
            return;
        }
        docId = targetDocument.getId();
    }

    try {
        if (!session.canRemoveDocument(targetDocRef)) {
            handleError(res, "This document can't be removed");
            return;
        }

        session.removeDocument(targetDocRef);
        session.save();

        // build the XML response document holding the ref
        Element docElement = result.addElement(documentTag);
        docElement.addElement(docRefTag).setText("Document " + docId + " deleted");
        res.setEntity(result.asXML(), MediaType.TEXT_XML);
        res.getEntity().setCharacterSet(CharacterSet.UTF_8);
    } catch (ClientException e) {
        log.error(e.getMessage(), e);
        handleError(res, e);
    }
}

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

License:Open Source License

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

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

    try {/*from w  ww .jav  a  2 s  .  c om*/
        DirectoryService service = Framework.getLocalService(DirectoryService.class);
        List<Directory> directories = new LinkedList<Directory>();
        Form form = req.getResourceRef().getQueryAsForm();

        if (form.getNames().contains(DIRECTORY_NAME_QUERY_PARAM)) {
            // only invalidate the caches of the requested directories
            String[] directoryNames = form.getValues(DIRECTORY_NAME_QUERY_PARAM).split(",");
            for (String directoryName : directoryNames) {
                Directory directory = service.getDirectory(directoryName);
                if (directory == null) {
                    log.error("no such directory: " + directoryName);
                } else {
                    directories.add(directory);
                }
            }
        } else {
            // invalidate all directory caches
            directories = service.getDirectories();
        }

        Element invalidatedCachesElement = result.addElement("invalidatedCaches");
        for (Directory directory : directories) {
            directory.getCache().invalidateAll();
            invalidatedCachesElement.addElement("directory").addText(directory.getName());
        }

    } catch (Exception e) {
        handleError(res, e);
        return;
    }
    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.OpenSearchRestlet.java

License:Open Source License

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

    CoreSession session;//from  w w  w. ja  va  2  s  .  c  o  m
    try {
        Repository repository = Framework.getService(RepositoryManager.class).getDefaultRepository();
        if (repository == null) {
            throw new ClientException("Cannot get default repository");
        }
        Map<String, Serializable> context = new HashMap<String, Serializable>();
        context.put("principal", getSerializablePrincipal(req));
        session = repository.open(context);
    } catch (Exception e) {
        handleError(res, e);
        return;
    }
    try {
        // read the search term passed as the 'q' request parameter
        String keywords = getQueryParamValue(req, "q", " ");

        // perform the search on the fulltext index and wrap the results as
        // a DocumentModelList with the 10 first matching results ordered by
        // modification time
        String query = String.format(QUERY, keywords);
        DocumentModelList documents = session.query(query, null, MAX, 0, true);

        // build the RSS 2.0 response document holding the results
        DOMDocumentFactory domFactory = new DOMDocumentFactory();
        DOMDocument resultDocument = (DOMDocument) domFactory.createDocument();

        // rss root tag
        Element rssElement = resultDocument.addElement(RSS_TAG);
        rssElement.addAttribute("version", "2.0");
        rssElement.addNamespace(OPENSEARCH_NS.getPrefix(), OPENSEARCH_NS.getURI());
        rssElement.addNamespace(ATOM_NS.getPrefix(), ATOM_NS.getURI());

        // channel with OpenSearch metadata
        Element channelElement = rssElement.addElement(CHANNEL_TAG);

        channelElement.addElement(TITLE_TAG).setText("Nuxeo EP OpenSearch channel for " + keywords);
        channelElement.addElement("link").setText(BaseURL.getBaseURL(getHttpRequest(req))
                + "restAPI/opensearch?q=" + URLEncoder.encode(keywords, "UTF-8"));
        channelElement.addElement(new QName("totalResults", OPENSEARCH_NS))
                .setText(Long.toString(documents.totalSize()));
        channelElement.addElement(new QName("startIndex", OPENSEARCH_NS)).setText("0");
        channelElement.addElement(new QName("itemsPerPage", OPENSEARCH_NS))
                .setText(Integer.toString(documents.size()));

        Element queryElement = channelElement.addElement(new QName("Query", OPENSEARCH_NS));
        queryElement.addAttribute("role", "request");
        queryElement.addAttribute("searchTerms", keywords);
        queryElement.addAttribute("startPage", Integer.toString(1));

        // document items
        String baseUrl = BaseURL.getBaseURL(getHttpRequest(req));

        for (DocumentModel doc : documents) {
            Element itemElement = channelElement.addElement(ITEM_TAG);
            Element titleElement = itemElement.addElement(TITLE_TAG);
            String title = doc.getTitle();
            if (title != null) {
                titleElement.setText(title);
            }
            Element descriptionElement = itemElement.addElement(DESCRIPTION_TAG);
            String description = doc.getProperty("dublincore:description").getValue(String.class);
            if (description != null) {
                descriptionElement.setText(description);
            }
            Element linkElement = itemElement.addElement("link");
            linkElement.setText(baseUrl + DocumentModelFunctions.documentUrl(doc));
        }

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

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

License:Open Source License

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

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

    // init repo and document
    boolean initOk = initRepositoryAndTargetDocument(res, repoId, docId);
    if (!initOk) {
        return;//  ww  w.  j a va  2 s  .c  om
    }

    try {
        Form queryParameters = req.getResourceRef().getQueryAsForm();
        for (String paramName : queryParameters.getNames()) {
            if (!DOC_TYPE.equals(paramName)) {
                // treat all non doctype parameters as string fields
                targetDocument.setPropertyValue(paramName, getQueryParamValue(req, paramName, null));
            }
        }
        session.saveDocument(targetDocument);
        session.save();

        // build the XML response document holding the ref
        Element docElement = result.addElement(documentTag);
        docElement.addElement(docRefTag).setText("Document " + docId + " has been updated");
        res.setEntity(result.asXML(), MediaType.TEXT_XML);
        res.getEntity().setCharacterSet(CharacterSet.UTF_8);
    } catch (ClientException e) {
        log.error(e.getMessage(), e);
        handleError(res, e);
    }
}

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

License:Open Source License

@Override
public void handle(Request req, Response res) {
    String repo = (String) req.getAttributes().get("repo");
    String docid = (String) req.getAttributes().get("docid");
    String fileName = (String) req.getAttributes().get("filename");

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

    DocumentModel targetContainer;/*from   w w w.  j a v a  2s .  c om*/
    try {
        navigationContext.setCurrentServerLocation(new RepositoryLocation(repo));
        documentManager = navigationContext.getOrCreateDocumentManager();
        targetContainer = documentManager.getDocument(new IdRef(docid));
    } catch (Exception e) {
        handleError(res, e);
        return;
    }

    if (targetContainer != null) {
        List<Blob> blobs = null;
        try {
            blobs = FileUploadHelper.parseRequest(req);
        } catch (Exception e) {
            handleError(res, e);
            return;
        }

        if (blobs == null) {
            // mono import
            String outcome;
            try {
                Blob inputBlob = StreamingBlob.createFromStream(req.getEntity().getStream()).persist();
                inputBlob.setFilename(fileName);
                outcome = FileManageActions.addBinaryFileFromPlugin(inputBlob, fileName, targetContainer);
            } catch (Exception e) {
                outcome = "ERROR : " + e.getMessage();
            }
            result.addElement("upload").setText(outcome);
        } else {
            // multiple file upload
            Element uploads = result.addElement("uploads");
            for (Blob blob : blobs) {
                String outcome;
                try {
                    outcome = FileManageActions.addBinaryFileFromPlugin(blob, blob.getFilename(),
                            targetContainer);
                } catch (Exception e) {
                    log.error("error importing " + blob.getFilename() + ": " + e.getMessage(), e);
                    outcome = "ERROR : " + e.getMessage();
                }
                uploads.addElement("upload").setText(outcome);
            }
        }
    }
    Representation rep = new StringRepresentation(result.asXML(), MediaType.APPLICATION_XML);
    rep.setCharacterSet(CharacterSet.UTF_8);
    res.setEntity(rep);
}