Example usage for org.jdom2 Document Document

List of usage examples for org.jdom2 Document Document

Introduction

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

Prototype

public Document() 

Source Link

Document

Creates a new empty document.

Usage

From source file:neon.ui.graphics.svg.SVGLoader.java

License:Open Source License

public static JVShape loadShape(String shape) {
    StringReader stringReader = new StringReader(shape);
    SAXBuilder builder = new SAXBuilder();
    // doc al initialiseren, in geval builder.build faalt
    Document doc = new Document();
    try {//from w  w w  .j  av  a 2 s. com
        doc = builder.build(stringReader);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Element root = doc.getRootElement();
    root.detach();
    return loadShape(root);
}

From source file:net.visualillusionsent.tellplugin.xml.XMLSaveHandler.java

License:Open Source License

public XMLSaveHandler(String fileName) {
    try {//www. j a  va  2 s .co  m
        file = new File(dataDir, fileName + ".xml");
        if (!file.exists()) {
            dataDir.mkdirs();
            file.createNewFile();

            /* Create our Document */
            document = new Document();
            /* initialize the root element */
            document.setRootElement(new Element(fileName));
            /* write doc to file */
            RandomAccessFile f = new RandomAccessFile(getFile().getPath(), "rw");
            f.getChannel().lock();
            f.setLength(0);
            f.write(getXmlSerializer().outputString(getDocument()).getBytes(Charset.forName("UTF-8")));
            f.close();
        } else {
            FileInputStream in = new FileInputStream(file);
            document = fileBuilder.build(in);
            in.close();
        }
    } catch (JDOMException e) {
        VIBotX.log.error("Error initializing XML Document.", e);
    } catch (IOException e) {
        VIBotX.log.error("Error initializing XML Document.", e);
    }
}

From source file:object2xml.JDOMXMLWriter.java

public void writeFileUsingJDOM(List<Pessoa> pessoaList, String fileName) throws IOException {
    Document doc = new Document();
    doc.setRootElement(new Element("Pessoas", ""));
    for (Pessoa p : pessoaList) {
        System.out.println(p);/*www . j  ava  2  s  .co m*/
        Element pessoa = new Element("Pessoa");
        pessoa.setAttribute("id", "" + p.getIdentidade());
        pessoa.addContent(new Element("nome").setText(p.getNome()));
        pessoa.addContent(new Element("idade").setText("" + p.getIdade()));
        pessoa.addContent(new Element("peso").setText("" + p.getPeso()));
        Element celulares = new Element("Celulares");
        for (Celular c : p.getCelulares()) {
            Element celular = new Element("Celular");
            celular.setAttribute("id", "" + c.getIdCel());
            celular.addContent(new Element("numero").setText("" + c.getNumero()));
            celular.addContent(new Element("operadora").setText("" + c.getOperadora()));
            celulares.addContent(celular);
        }

        pessoa.addContent(celulares);
        doc.getRootElement().addContent(pessoa);
    }
    //JDOM document is ready now, lets write it to file now
    XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
    //output xml to console for debugging
    //xmlOutputter.output(doc, System.out);
    xmlOutputter.output(doc, new FileOutputStream(fileName));
}

From source file:odml.core.Writer.java

License:Open Source License

/**
 * Creates the Dom document from the section.
 *
 * @param rootSection {@link Section}: the section to start the dom creation.
 * @param asTerminology {@link boolean}: flag to indicate whether Template is used or not
 *
 *//* www.  java 2s .c om*/
private void createDom(Section rootSection, boolean asTerminology) {
    doc = new Document();
    ProcessingInstruction instruction;
    ProcessingInstruction alternativeInstruction;
    if (asTerminology) {
        alternativeInstruction = new ProcessingInstruction("xml-stylesheet",
                "type=\"text/xsl\" href=\"odml.xsl\"");
        instruction = new ProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"odmlTerms.xsl\"");
    } else {
        alternativeInstruction = new ProcessingInstruction("xml-stylesheet",
                "type=\"text/xsl\" href=\"odmlTerms.xsl\"");
        instruction = new ProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"odml.xsl\"");
    }
    doc.addContent(instruction);
    doc.addContent(alternativeInstruction);
    Element rootElement = new Element("odML");
    rootElement.setAttribute("version", "1");
    doc.setRootElement(rootElement);

    Section dummyRoot;
    if (rootSection.propertyCount() != 0) {
        dummyRoot = new Section();
        dummyRoot.add(rootSection);
        dummyRoot.setDocumentAuthor(rootSection.getDocumentAuthor());
        dummyRoot.setDocumentDate(rootSection.getDocumentDate());
        dummyRoot.setDocumentVersion(rootSection.getDocumentVersion());
        dummyRoot.setRepository(rootSection.getRepository());
    } else {
        dummyRoot = rootSection;
    }
    String author = dummyRoot.getDocumentAuthor();
    if (author != null) {
        Element authorElement = new Element("author");
        authorElement.setText(author);
        rootElement.addContent(authorElement);
    }
    String version = dummyRoot.getDocumentVersion();
    if (version != null) {
        Element versionElement = new Element("version");
        versionElement.setText(version);
        rootElement.addContent(versionElement);
    }
    String dateString;
    Date date = dummyRoot.getDocumentDate();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    if (date != null) {
        dateString = sdf.format(date);
    } else {
        date = new Date(Calendar.getInstance().getTimeInMillis());
        dateString = sdf.format(date);
    }
    Element dateElement = new Element("date");
    dateElement.setText(dateString);
    rootElement.addContent(dateElement);
    URL repository = dummyRoot.getRepository();
    if (repository != null) {
        Element repElement = new Element("repository");
        repElement.setText(repository.toString());
        rootElement.addContent(repElement);
    }
    for (int i = 0; i < dummyRoot.sectionCount(); i++) {
        appendSection(rootElement, dummyRoot.getSection(i), asTerminology);
    }
}

From source file:org.artifactory.webapp.wicket.page.home.settings.ivy.IvySettingsPanel.java

License:Open Source License

@Override
public String generateSettings() {
    Document document = new Document();
    Element rootNode = new Element("ivy-settings");

    Element settingsElement = new Element("settings");
    settingsElement.setAttribute("defaultResolver", "main");
    rootNode.addContent(settingsElement);

    if (!authorizationService.isAnonymous() || !authorizationService.isAnonAccessEnabled()) {
        rootNode.addContent(/*  ww  w. ja v  a 2s.c  om*/
                new Comment("Authentication required for publishing (deployment). 'Artifactory Realm' is "
                        + "the realm used by Artifactory so don't change it."));

        Element credentialsElement = new Element("credentials");
        try {
            credentialsElement.setAttribute("host", new URL(servletContextUrl).getHost());
        } catch (MalformedURLException e) {
            String errorMessage = "An error occurred while decoding the servlet context URL for the credentials host attribute: ";
            error(errorMessage + e.getMessage());
            log.error(errorMessage, e);
        }
        credentialsElement.setAttribute("realm", "Artifactory Realm");

        FilteredResourcesWebAddon filteredResourcesWebAddon = addonsManager
                .addonByType(FilteredResourcesWebAddon.class);

        credentialsElement.setAttribute("username",
                filteredResourcesWebAddon.getGeneratedSettingsUsernameTemplate());

        credentialsElement.setAttribute("passwd", "@PASS_ATTR_PLACEHOLDER@");

        rootNode.addContent(credentialsElement);
    }

    Element resolversElement = new Element("resolvers");

    Element chainElement = new Element("chain");
    chainElement.setAttribute("name", "main");

    String resolverName = resolverPanel.getResolverName();
    resolverName = StringUtils.isNotBlank(resolverName) ? resolverName : "public";

    if (resolverPanel.useIbiblioResolver()) {

        Element ibiblioElement = new Element("ibiblio");
        ibiblioElement.setAttribute("name", resolverName);
        ibiblioElement.setAttribute("m2compatible", Boolean.TRUE.toString());
        ibiblioElement.setAttribute("root", resolverPanel.getFullRepositoryUrl());
        chainElement.addContent(ibiblioElement);
    } else {

        Element urlElement = new Element("url");
        urlElement.setAttribute("name", resolverName);

        urlElement.setAttribute("m2compatible", Boolean.toString(resolverPanel.isM2Compatible()));

        Element artifactPatternElement = new Element("artifact");
        artifactPatternElement.setAttribute("pattern", resolverPanel.getFullArtifactPattern());
        urlElement.addContent(artifactPatternElement);

        Element ivyPatternElement = new Element("ivy");
        ivyPatternElement.setAttribute("pattern", resolverPanel.getFullDescriptorPattern());
        urlElement.addContent(ivyPatternElement);

        chainElement.addContent(urlElement);
    }

    resolversElement.addContent(chainElement);

    rootNode.addContent(resolversElement);

    document.setRootElement(rootNode);

    String result = new XMLOutputter(Format.getPrettyFormat()).outputString(document);
    // after the xml is generated replace the password placeholder with the template placeholder (otherwise jdom
    // escapes this string)
    FilteredResourcesWebAddon filteredResourcesWebAddon = addonsManager
            .addonByType(FilteredResourcesWebAddon.class);
    return result.replace("@PASS_ATTR_PLACEHOLDER@",
            filteredResourcesWebAddon.getGeneratedSettingsUserCredentialsTemplate(false));
}

From source file:org.educautecisystems.core.chat.elements.UserChat.java

License:Open Source License

public static String generateXMLFromList(ArrayList<UserChat> users) {
    Document xmlDocument = new Document();

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

    for (UserChat user : users) {
        Element userXml = new Element("user", baseNamespace);

        userXml.addContent(new Element("id").setText("" + user.getId()));
        userXml.addContent(new Element("real_name").setText(user.getRealName()));
        userXml.addContent(new Element("nickname").setText(user.getNickName()));

        root.addContent(userXml);/*w  w w  .  j  a v  a 2 s .c  o  m*/
    }

    xmlDocument.setRootElement(root);
    XMLOutputter xmlOutputter = new XMLOutputter();

    return xmlOutputter.outputString(xmlDocument);
}

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

License:Open Source License

public static void guardarConfPrincipal() {
    File archivoConfPrincipal = new File(pathGeneralConf);

    if (archivoConfPrincipal.exists()) {
        archivoConfPrincipal.delete();/*  www.j  a  v a 2 s . c om*/
    }

    Document documento = new Document();

    Namespace baseNamespace = Namespace.getNamespace("eus", "http://educautecisystems.org/");
    Element root = new Element("config", baseNamespace);
    documento.setRootElement(root);

    Element eBaseDeDatos = new Element("database", baseNamespace);
    eBaseDeDatos.addContent(new Element("host").setText(confBaseDeDatos.getHost()));
    eBaseDeDatos.addContent(new Element("port").setText(confBaseDeDatos.getPort()));
    eBaseDeDatos.addContent(new Element("user").setText(confBaseDeDatos.getUser()));
    eBaseDeDatos.addContent(new Element("password").setText(confBaseDeDatos.getPassword()));
    eBaseDeDatos.addContent(new Element("esquema").setText(confBaseDeDatos.getEsquema()));
    root.addContent(eBaseDeDatos);

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

    try {
        FileOutputStream fis = new FileOutputStream(archivoConfPrincipal);
        outputter.output(documento, fis);
        fis.close();
    } catch (IOException ioe) {
        System.err.println("No se pudo escribor configuracin principal.");
    }
}

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);/*  w  ww. j  ava2  s . c  o m*/

    /* 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();//  w  w  w . j a va 2  s  .c o 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//w w w . j  a  v  a 2 s  .  c  o  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()));
}