Example usage for org.jdom2 Document setRootElement

List of usage examples for org.jdom2 Document setRootElement

Introduction

In this page you can find the example usage for org.jdom2 Document setRootElement.

Prototype

public Document setRootElement(Element rootElement) 

Source Link

Document

This sets the root Element for the Document.

Usage

From source file:org.educautecisystems.core.Sistema.java

License:Open Source License

private static void generarChatConf(File archivoConfChatXML) {
    Document document = new Document();

    Namespace baseNamespace = Namespace.getNamespace("chat", "http://free.chat.com/");
    Element root = new Element("config", baseNamespace);

    /* Datos servidor */
    Element eServidor = new Element("server", baseNamespace);
    eServidor.addContent(new Element("ip").setText(ip_defecto));
    eServidor.addContent(new Element("port").setText(port_defecto));
    root.addContent(eServidor);/*from  w  ww. ja  va  2s .  c  om*/

    /* Datos sesin */
    Element eSession = new Element("session", baseNamespace);
    eSession.addContent(new Element("nickname").setText(nickname_defecto));
    eSession.addContent(new Element("real_name").setText(realName_defecto));
    root.addContent(eSession);

    /* Guardar archivo */
    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    document.setRootElement(root);

    try {
        outputter.output(document, new FileOutputStream(archivoConfChatXML));
    } catch (IOException ioe) {
        System.err.println("No se puedo crear archivo de configuracin.");
    }

    /* Iniciar informacin */
    chatServerConf = new ChatServerConf(ip_defecto, port_defecto);
    chatSessionConf = new ChatSessionConf(nickname_defecto, realName_defecto);
}

From source file:org.educautecisystems.core.Sistema.java

License:Open Source License

public static void guardarChatConf() {
    File archivoConfChatXML = new File(pathChatConf);

    /* Borrar archivo, si existe. */
    if (archivoConfChatXML.exists()) {
        archivoConfChatXML.delete();//from www  .j a va2s. co m
    }

    Document document = new Document();

    Namespace baseNamespace = Namespace.getNamespace("chat", "http://free.chat.com/");
    Element root = new Element("config", baseNamespace);

    /* Datos servidor */
    Element eServidor = new Element("server", baseNamespace);
    eServidor.addContent(new Element("ip").setText(chatServerConf.getIp()));
    eServidor.addContent(new Element("port").setText(chatServerConf.getPort()));
    root.addContent(eServidor);

    /* Datos sesin */
    Element eSession = new Element("session", baseNamespace);
    eSession.addContent(new Element("nickname").setText(chatSessionConf.getNickname()));
    eSession.addContent(new Element("real_name").setText(chatSessionConf.getRealName()));
    root.addContent(eSession);

    /* Guardar archivo */
    XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
    document.setRootElement(root);

    try {
        outputter.output(document, new FileOutputStream(archivoConfChatXML));
    } catch (IOException ioe) {
        System.err.println("No se puedo crear archivo de configuracin.");
    }
}

From source file:org.geoserver.backuprestore.tasklet.AbstractCatalogBackupRestoreTasklet.java

License:Open Source License

/**
 * This method dumps the current Backup index: - List of Workspaces - List of Stores - List of
 * Layers//from   w w w .ja  va  2  s. co m
 *
 * @param sourceFolder
 * @throws IOException
 */
protected void dumpBackupIndex(Resource sourceFolder) throws IOException {
    Element root = new Element("Index");
    Document doc = new Document();

    for (WorkspaceInfo ws : getCatalog().getWorkspaces()) {
        if (!filteredResource(ws, false)) {
            Element workspace = new Element("Workspace");
            workspace.addContent(new Element("Name").addContent(ws.getName()));
            root.addContent(workspace);

            for (DataStoreInfo ds : getCatalog().getStoresByWorkspace(ws.getName(), DataStoreInfo.class)) {
                if (!filteredResource(ds, ws, true, StoreInfo.class)) {
                    Element store = new Element("Store");
                    store.setAttribute("type", "DataStoreInfo");
                    store.addContent(new Element("Name").addContent(ds.getName()));
                    workspace.addContent(store);

                    for (FeatureTypeInfo ft : getCatalog().getFeatureTypesByDataStore(ds)) {
                        if (!filteredResource(ft, ws, true, ResourceInfo.class)) {
                            for (LayerInfo ly : getCatalog().getLayers(ft)) {
                                if (!filteredResource(ly, ws, true, LayerInfo.class)) {
                                    Element layer = new Element("Layer");
                                    layer.setAttribute("type", "VECTOR");
                                    layer.addContent(new Element("Name").addContent(ly.getName()));
                                    store.addContent(layer);
                                }
                            }
                        }
                    }
                }
            }

            for (CoverageStoreInfo cs : getCatalog().getStoresByWorkspace(ws.getName(),
                    CoverageStoreInfo.class)) {
                if (!filteredResource(cs, ws, true, StoreInfo.class)) {
                    Element store = new Element("Store");
                    store.setAttribute("type", "CoverageStoreInfo");
                    store.addContent(new Element("Name").addContent(cs.getName()));
                    workspace.addContent(store);

                    for (CoverageInfo ci : getCatalog().getCoveragesByCoverageStore(cs)) {
                        if (!filteredResource(ci, ws, true, ResourceInfo.class)) {
                            for (LayerInfo ly : getCatalog().getLayers(ci)) {
                                if (!filteredResource(ly, ws, true, LayerInfo.class)) {
                                    Element layer = new Element("Layer");
                                    layer.setAttribute("type", "RASTER");
                                    layer.addContent(new Element("Name").addContent(ly.getName()));
                                    store.addContent(layer);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    if (filterIsValid()) {
        Element filter = new Element("Filters");
        if (getFilters().length > 0 && getFilters()[0] != null) {
            Element wsFilter = new Element("Filter");
            wsFilter.setAttribute("type", "WorkspaceInfo");
            wsFilter.addContent(new Element("ECQL").addContent(ECQL.toCQL(getFilters()[0])));
            filter.addContent(wsFilter);
        }

        if (getFilters().length > 1 && getFilters()[1] != null) {
            Element siFilter = new Element("Filter");
            siFilter.setAttribute("type", "StoreInfo");
            siFilter.addContent(new Element("ECQL").addContent(ECQL.toCQL(getFilters()[1])));
            filter.addContent(siFilter);
        }

        if (getFilters().length > 2 && getFilters()[2] != null) {
            Element liFilter = new Element("Filter");
            liFilter.setAttribute("type", "LayerInfo");
            liFilter.addContent(new Element("ECQL").addContent(ECQL.toCQL(getFilters()[2])));
            filter.addContent(liFilter);
        }

        root.addContent(filter);
    }

    doc.setRootElement(root);

    XMLOutputter outter = new XMLOutputter();
    outter.setFormat(Format.getPrettyFormat());
    outter.output(doc, new FileWriter(sourceFolder.get(BR_INDEX_XML).file()));
}

From source file:org.goobi.production.export.ExportXmlLog.java

License:Open Source License

/**
 * This method exports the production metadata for al list of processes as a single file to a given stream.
 * //from  w  w  w.  j a v  a 2  s  .  c o  m
 * @param processList
 * @param outputStream
 * @param xslt
 */

public void startExport(List<Process> processList, OutputStream outputStream, String xslt) {
    Document answer = new Document();
    Element root = new Element("processes");
    answer.setRootElement(root);
    Namespace xmlns = Namespace.getNamespace("http://www.goobi.io/logfile");

    Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
    root.addNamespaceDeclaration(xsi);
    root.setNamespace(xmlns);
    Attribute attSchema = new Attribute("schemaLocation", "http://www.goobi.io/logfile" + " XML-logfile.xsd",
            xsi);
    root.setAttribute(attSchema);
    for (Process p : processList) {
        Document doc = createDocument(p, false);
        Element processRoot = doc.getRootElement();
        processRoot.detach();
        root.addContent(processRoot);
    }

    XMLOutputter outp = new XMLOutputter();
    outp.setFormat(Format.getPrettyFormat());

    try {

        outp.output(answer, outputStream);
    } catch (IOException e) {

    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                outputStream = null;
            }
        }
    }

}

From source file:org.jumpmind.metl.core.runtime.component.XmlFormatter.java

License:Open Source License

private void fillStackWithStaticParentElements(Stack<DocElement> parentStack, DocElement firstDocElement,
        Document generatedXml) {

    Element elementToPutOnStack = null;
    Map<Element, Namespace> namespaces = null;

    // if the generatedXml doc is empty then start a new one and use it for
    // search/*from   w  w w.  j a v  a  2  s .c  o m*/
    if (!generatedXml.hasRootElement()) {
        Element newRootElement = templateDoc.getRootElement().clone();
        generatedXml.setRootElement(newRootElement);
        namespaces = removeNamespaces(generatedXml);
        XPathExpression<Element> expression = XPathFactory.instance().compile(firstDocElement.xpath,
                Filters.element());
        List<Element> matches = expression.evaluate(generatedXml.getRootElement());
        if (matches.size() != 0) {
            elementToPutOnStack = matches.get(0).getParentElement();
        } else {
            elementToPutOnStack = generatedXml.getRootElement();
        }
        elementToPutOnStack.removeContent();
        removeAllAttributes(elementToPutOnStack);
        parentStack.push(new DocElement(firstDocElement.level - 1, elementToPutOnStack, null, null));
        restoreNamespaces(generatedXml, namespaces);
    } else {
        // we already have a genertedXml going, but need other static
        // elements from the template
        namespaces = removeNamespaces(templateDoc);
        XPathExpression<Element> expression = XPathFactory.instance().compile(firstDocElement.xpath,
                Filters.element());
        List<Element> matches = expression.evaluate(templateDoc.getRootElement());
        // TODO: do something here for when the attribute is more than one
        // level away from the entity
        if (matches.size() != 0) {
            elementToPutOnStack = matches.get(0).getParentElement().clone();
        } else {
            // throw some exception here
        }
        elementToPutOnStack.removeContent();
        removeAllAttributes(elementToPutOnStack);
        parentStack.push(new DocElement(firstDocElement.level - 1, elementToPutOnStack, null, null));
        restoreNamespaces(templateDoc, namespaces);
    }
}

From source file:org.kitodo.docket.ExportXmlLog.java

License:Open Source License

/**
 * This method exports the production metadata for al list of processes as a
 * single file to a given stream.//  w  w w .  j ava2s .  c o  m
 *
 * @param docketDataList
 *            a list of Docket data
 * @param outputStream
 *            The output stream, to write the docket to.
 */

void startMultipleExport(Iterable<DocketData> docketDataList, OutputStream outputStream) {
    Document answer = new Document();
    Element root = new Element("processes");
    answer.setRootElement(root);
    Namespace xmlns = Namespace.getNamespace(NAMESPACE);

    Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
    root.addNamespaceDeclaration(xsi);
    root.setNamespace(xmlns);
    Attribute attSchema = new Attribute("schemaLocation", NAMESPACE + " XML-logfile.xsd", xsi);
    root.setAttribute(attSchema);
    for (DocketData docketData : docketDataList) {
        Document doc = createDocument(docketData, false);
        Element processRoot = doc.getRootElement();
        processRoot.detach();
        root.addContent(processRoot);
    }

    XMLOutputter outp = new XMLOutputter(Format.getPrettyFormat());

    try {
        outp.output(answer, outputStream);
    } catch (IOException e) {
        logger.error("Generating XML Output failed.", e);
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                logger.error("Closing the output stream failed.", e);
            }
        }
    }

}

From source file:org.mule.tools.apikit.output.MuleConfigGenerator.java

License:Open Source License

private Document getDocument(API api) throws IOException, JDOMException {
    SAXBuilder saxBuilder = new SAXBuilder(XMLReaders.NONVALIDATING);
    Document doc;
    File xmlFile = api.getXmlFile(rootDirectory);
    if (!xmlFile.exists() || xmlFile.length() == 0) {
        xmlFile.getParentFile().mkdirs();
        doc = new Document();
        doc.setRootElement(new MuleScope().generate());
    } else {/*w w  w  .j a  v a  2  s. c  om*/
        InputStream xmlInputStream = new FileInputStream(xmlFile);
        doc = saxBuilder.build(xmlInputStream);
    }
    return doc;
}

From source file:org.mycore.restapi.v1.MCRRestAPIClassifications.java

License:Open Source License

/**
 *
 * @param info - a Jersey Context Object for URI
 *     Possible values are: json | xml (required)
 *///from   w  ww .j  a va 2  s.  c o m
@GET
@Path("/")
@Produces({ MediaType.TEXT_XML + ";charset=UTF-8", MediaType.APPLICATION_JSON + ";charset=UTF-8" })
public Response listClassifications(@Context UriInfo info,
        @QueryParam("format") @DefaultValue("json") String format) {
    if (FORMAT_XML.equals(format)) {
        StringWriter sw = new StringWriter();

        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        Document docOut = new Document();
        Element eRoot = new Element("mycoreclassifications");
        docOut.setRootElement(eRoot);

        for (MCRCategory cat : DAO.getRootCategories()) {
            eRoot.addContent(
                    new Element("mycoreclass").setAttribute("ID", cat.getId().getRootID()).setAttribute("href",
                            info.getAbsolutePathBuilder().path(cat.getId().getRootID()).build().toString()));
        }
        try {
            xout.output(docOut, sw);
            return Response.ok(sw.toString()).type("application/xml; charset=UTF-8").build();
        } catch (IOException e) {
            //ToDo
        }
    }

    if (FORMAT_JSON.equals(format)) {
        StringWriter sw = new StringWriter();
        try {
            JsonWriter writer = new JsonWriter(sw);
            writer.setIndent("    ");
            writer.beginObject();
            writer.name("mycoreclass");
            writer.beginArray();
            for (MCRCategory cat : DAO.getRootCategories()) {
                writer.beginObject();
                writer.name("ID").value(cat.getId().getRootID());
                writer.name("href")
                        .value(info.getAbsolutePathBuilder().path(cat.getId().getRootID()).build().toString());
                writer.endObject();
            }
            writer.endArray();
            writer.endObject();

            writer.close();

            return Response.ok(sw.toString()).type("application/json; charset=UTF-8").build();
        } catch (IOException e) {
            //toDo
        }
    }
    return Response.status(Status.BAD_REQUEST).build();
}

From source file:org.onosproject.provider.netconf.flow.impl.XmlBuilder.java

License:Apache License

public String buildAclRequestXml(AccessList accessList) {
    Document doc = new Document();
    Namespace namespaceRpc = Namespace.getNamespace("urn:ietf:params:xml:ns:netconf:base:1.0");
    Namespace accessNamespaceRpc = Namespace.getNamespace("urn:ietf:params:xml:ns:yang:ietf-acl");
    doc.setRootElement(new Element("rpc", namespaceRpc).setAttribute("message-id", "101"));

    /**//  www .jav a 2  s .  co m
     * Access list elements of given ACL model.
     */
    Element access = new Element("access-list", accessNamespaceRpc);
    access.addContent(new Element("acl-name", accessNamespaceRpc).setText(accessList.getAclName()));
    // access.addContent(accessEntries);

    if (!accessList.getAccessListEntries().isEmpty() && accessList.getAccessListEntries() != null) {
        for (int accessEntryIntVlu = 0; accessEntryIntVlu < accessList.getAccessListEntries()
                .size(); accessEntryIntVlu++) {
            access.addContent(getAccessEntries(accessEntryIntVlu, accessList, accessNamespaceRpc));
        }
    }

    /**
     * edit-config operation for given ACL model.
     */
    Element editConfig = new Element("edit-config", namespaceRpc);
    editConfig.addContent(new Element("target", namespaceRpc).addContent(new Element("running", namespaceRpc)));
    editConfig
            .addContent(new Element("config", Namespace.getNamespace("urn:ietf:params:xml:ns:netconf:base:1.0"))
                    .addContent(access));

    doc.getRootElement().addContent(editConfig);
    XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
    String outputString = xmlOutputter.outputString(doc);

    return outputString;
}

From source file:org.opengroup.archimate.xmlexchange.XMLModelExporter.java

License:Open Source License

/**
 * @param doc/*from   w  ww.  ja va  2  s  .c o  m*/
 * @return The Root JDOM Element
 */
Element createRootElement(Document doc) {
    Element rootElement = new Element(ELEMENT_MODEL, OPEN_GROUP_NAMESPACE);
    doc.setRootElement(rootElement);

    rootElement.addNamespaceDeclaration(JDOMUtils.XSI_Namespace);
    // rootElement.addNamespaceDeclaration(OPEN_GROUP_NAMESPACE_EMBEDDED); // Don't include this

    // DC Namespace
    if (hasMetadata()) {
        rootElement.addNamespaceDeclaration(DC_NAMESPACE);
    }

    /* 
     * Add Schema Location Attribute which is constructed from Target Namespaces and file names of Schemas
     */
    StringBuffer schemaLocationURI = new StringBuffer();

    // Open Group Schema Location
    schemaLocationURI.append(rootElement.getNamespace().getURI());
    schemaLocationURI.append(" "); //$NON-NLS-1$
    schemaLocationURI.append(OPEN_GROUP_SCHEMA_LOCATION);

    // DC Schema Location
    if (hasMetadata()) {
        schemaLocationURI.append(" "); //$NON-NLS-1$
        schemaLocationURI.append(DC_NAMESPACE.getURI());
        schemaLocationURI.append(" "); //$NON-NLS-1$
        schemaLocationURI.append(DC_SCHEMA_LOCATION);
    }

    rootElement.setAttribute(JDOMUtils.XSI_SchemaLocation, schemaLocationURI.toString(),
            JDOMUtils.XSI_Namespace);

    return rootElement;
}