Example usage for org.w3c.dom Node setTextContent

List of usage examples for org.w3c.dom Node setTextContent

Introduction

In this page you can find the example usage for org.w3c.dom Node setTextContent.

Prototype

public void setTextContent(String textContent) throws DOMException;

Source Link

Document

This attribute returns the text content of this node and its descendants.

Usage

From source file:com.github.alexfalappa.nbspringboot.projects.initializr.InitializrProjectWizardIterator.java

private void pomDevTools(Document doc) {
    // modify pom.xml content and add cfg dependency snippet
    NodeList nl = doc.getElementsByTagName("dependency");
    if (nl != null && nl.getLength() > 0) {
        for (int i = 0; i < nl.getLength(); i++) {
            Element el = (Element) nl.item(i);
            NodeList grpId = el.getElementsByTagName("groupId");
            NodeList artId = el.getElementsByTagName("artifactId");
            if (grpId.getLength() > 0 && artId.getLength() > 0
                    && "org.springframework.boot".equals(grpId.item(0).getTextContent())
                    && "spring-boot-devtools".equals(artId.item(0).getTextContent())) {
                Node opt = doc.createElement("optional");
                opt.setTextContent("true");
                el.appendChild(opt);//from ww  w.  j  a  v a2  s. co  m
            }
        }
    }
}

From source file:net.roboconf.target.azure.internal.AzureIaasHandler.java

private void replaceValueOfTagInXMLFile(String filePath, String tagName, String replacingValue)
        throws ParserConfigurationException, SAXException, IOException {

    File fXmlFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);

    //optional, but recommended
    //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    doc.getDocumentElement().normalize();

    NodeList nList = doc.getElementsByTagName(tagName);
    Node nNode = nList.item(0);
    nNode.setTextContent(replacingValue);

    // write the modified content into xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer;/*ww w  . j  av  a  2  s  .c  o  m*/
    try {
        transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filePath));
        transformer.transform(source, result);

    } catch (TransformerException e) {
        this.logger.severe(e.getMessage());
    }
}

From source file:it.pronetics.madstore.crawler.publisher.impl.AtomPublisherImpl.java

private void setUpdatedDateTimeIfNecessary(Element entry) {
    NodeList updatedNodes = entry.getElementsByTagName(AtomConstants.ATOM_ENTRY_UPDATED);
    Node updatedNode = updatedNodes.item(0);
    if (updatedNode != null) {
        String entryUpdatedDateTime = updatedNode.getTextContent();
        if (entryUpdatedDateTime == null || entryUpdatedDateTime.equals("")) {
            LOG.warn("The entry has no updated date, using current time ...");
            updatedNode.setTextContent(ISODateTimeFormat.dateTime().print(System.currentTimeMillis()));
        }//from w  ww .ja  v  a  2  s.  c o m
    } else {
        LOG.warn("The entry has no updated date, using current time ...");
        updatedNode = entry.getOwnerDocument().createElementNS(AtomConstants.ATOM_NS,
                AtomConstants.ATOM_ENTRY_UPDATED);
        updatedNode.setTextContent(ISODateTimeFormat.dateTime().print(System.currentTimeMillis()));
        entry.appendChild(updatedNode);
    }
}

From source file:de.bitzeche.video.transcoding.zencoder.ZencoderClient.java

private Document createDocumentForException(String message) {
    try {//w ww. ja v a  2  s .com
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document errorDocument = documentBuilder.newDocument();
        Element root = errorDocument.createElement("error");
        errorDocument.appendChild(root);
        Node input = errorDocument.createElement("reason");
        input.setTextContent(message);
        root.appendChild(input);
        return errorDocument;
    } catch (ParserConfigurationException e) {
        LOGGER.error("Exception creating document for exception '" + message + "'", e);
        return null;
    }
}

From source file:com.cloud.hypervisor.kvm.resource.wrapper.LibvirtMigrateCommandWrapper.java

private String replaceStorage(String xmlDesc, Map<String, MigrateCommand.MigrateDiskInfo> migrateStorage)
        throws IOException, ParserConfigurationException, SAXException, TransformerException {
    InputStream in = IOUtils.toInputStream(xmlDesc);

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(in);

    // Get the root element
    Node domainNode = doc.getFirstChild();

    NodeList domainChildNodes = domainNode.getChildNodes();

    for (int i = 0; i < domainChildNodes.getLength(); i++) {
        Node domainChildNode = domainChildNodes.item(i);

        if ("devices".equals(domainChildNode.getNodeName())) {
            NodeList devicesChildNodes = domainChildNode.getChildNodes();

            for (int x = 0; x < devicesChildNodes.getLength(); x++) {
                Node deviceChildNode = devicesChildNodes.item(x);

                if ("disk".equals(deviceChildNode.getNodeName())) {
                    Node diskNode = deviceChildNode;

                    String sourceFileDevText = getSourceFileDevText(diskNode);

                    String path = getPathFromSourceFileDevText(migrateStorage.keySet(), sourceFileDevText);

                    if (path != null) {
                        MigrateCommand.MigrateDiskInfo migrateDiskInfo = migrateStorage.remove(path);

                        NamedNodeMap diskNodeAttributes = diskNode.getAttributes();
                        Node diskNodeAttribute = diskNodeAttributes.getNamedItem("type");

                        diskNodeAttribute.setTextContent(migrateDiskInfo.getDiskType().toString());

                        NodeList diskChildNodes = diskNode.getChildNodes();

                        for (int z = 0; z < diskChildNodes.getLength(); z++) {
                            Node diskChildNode = diskChildNodes.item(z);

                            if ("driver".equals(diskChildNode.getNodeName())) {
                                Node driverNode = diskChildNode;

                                NamedNodeMap driverNodeAttributes = driverNode.getAttributes();
                                Node driverNodeAttribute = driverNodeAttributes.getNamedItem("type");

                                driverNodeAttribute.setTextContent(migrateDiskInfo.getDriverType().toString());
                            } else if ("source".equals(diskChildNode.getNodeName())) {
                                diskNode.removeChild(diskChildNode);

                                Element newChildSourceNode = doc.createElement("source");

                                newChildSourceNode.setAttribute(migrateDiskInfo.getSource().toString(),
                                        migrateDiskInfo.getSourceText());

                                diskNode.appendChild(newChildSourceNode);
                            } else if ("auth".equals(diskChildNode.getNodeName())) {
                                diskNode.removeChild(diskChildNode);
                            } else if ("iotune".equals(diskChildNode.getNodeName())) {
                                diskNode.removeChild(diskChildNode);
                            }/*from  w  w  w  .j  a v a2 s .  c om*/
                        }
                    }
                }
            }
        }
    }

    if (!migrateStorage.isEmpty()) {
        throw new CloudRuntimeException(
                "Disk info was passed into LibvirtMigrateCommandWrapper.replaceStorage that was not used.");
    }

    return getXml(doc);
}

From source file:eu.impact_project.iif.tw.gen.DeploymentCreator.java

/**
 * Insert data types//from   w  w w. j a va 2s. c o m
 * @throws GeneratorException 
 */
public void createPom() throws GeneratorException {
    File wsdlTemplate = new File(this.pomAbsPath);
    if (!wsdlTemplate.canRead()) {
        throw new GeneratorException("Unable to read pom.xml template file: " + this.pomAbsPath);
    }
    try {

        DocumentBuilderFactory docBuildFact = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuildFact.newDocumentBuilder();
        doc = docBuilder.parse(this.pomAbsPath);
        NodeList profilesNodes = doc.getElementsByTagName("profiles");
        Node firstProfilesNode = profilesNodes.item(0);
        List<Deployref> dks = service.getDeployto().getDeployref();

        NodeList executionsNode = doc.getElementsByTagName("executions");
        Node thirdExecutionsNode = executionsNode.item(2);

        for (Deployref dk : dks) {
            boolean isDefaultDeployment = dk.isDefault();
            Deployment d = (Deployment) dk.getRef();

            String host = d.getHost();
            String id = d.getId();

            //<profile>
            //    <id>deployment1</id>
            //    <properties>
            //        <tomcat.manager.url>http://localhost:8080/manager</tomcat.manager.url>
            //        <tomcat.user>tomcat</tomcat.user>
            //        <tomcat.password>TxF781!P</tomcat.password>
            //        <war.suffix>deployment1</war.suffix>
            //    </properties>
            //</profile>
            //<profile>
            //    <id>deployment2</id>
            //    <properties>
            //        <tomcat.manager.url>http://localhost:8080/manager</tomcat.manager.url>
            //        <tomcat.user>tomcat</tomcat.user>
            //        <tomcat.password>TxF781!P</tomcat.password>
            //        <war.suffix>deployment2</war.suffix>
            //    </properties>
            //</profile>
            Element profileElm = doc.createElement("profile");

            if (isDefaultDeployment) {
                Element activationElm = doc.createElement("activation");
                Element activeByDefaultElm = doc.createElement("activeByDefault");
                activeByDefaultElm.setTextContent("true");
                activationElm.appendChild(activeByDefaultElm);
                profileElm.appendChild(activationElm);
            }

            firstProfilesNode.appendChild(profileElm);
            Element idElm = doc.createElement("id");
            idElm.setTextContent(d.getId());
            profileElm.appendChild(idElm);
            Element propertiesElm = doc.createElement("properties");
            profileElm.appendChild(propertiesElm);

            List<Port> ports = d.getPorts().getPort();
            String port = "8080";
            String type = "http";
            for (Port p : ports) {
                if (p.getType().equals("http")) {
                    port = String.valueOf(p.getValue());
                    type = p.getType();
                }
            }

            Element tomcatManagerUrlElm = doc.createElement("tomcat.manager.url");
            String managerPath = d.getManager().getPath();
            managerPath = (managerPath != null && !managerPath.isEmpty()) ? managerPath : "manager";
            tomcatManagerUrlElm.setTextContent(type + "://" + d.getHost() + ":" + port + "/" + managerPath);

            propertiesElm.appendChild(tomcatManagerUrlElm);
            Element tomcatUserPropElm = doc.createElement("tomcat.user");
            Manager manager = d.getManager();
            tomcatUserPropElm.setTextContent(manager.getUser());
            propertiesElm.appendChild(tomcatUserPropElm);
            Element tomcatPasswordPropElm = doc.createElement("tomcat.password");
            tomcatPasswordPropElm.setTextContent(manager.getPassword());
            propertiesElm.appendChild(tomcatPasswordPropElm);
            Element warSuffixElm = doc.createElement("war.suffix");
            warSuffixElm.setTextContent(d.getId());
            propertiesElm.appendChild(warSuffixElm);

            //<execution>
            //    <id>package-deployment1</id>
            //    <phase>package</phase>
            //    <configuration>
            //        <classifier>deployment1</classifier>
            //        <webappDirectory>${project.build.directory}/${project.build.finalName}_deployment1</webappDirectory>
            //        <webResources>
            //            <resource>
            //                <directory>src/env/deployment1</directory>
            //            </resource>
            //        </webResources>
            //    </configuration>
            //    <goals>
            //        <goal>war</goal>
            //    </goals>
            //</execution>

            Element executionElm = doc.createElement("execution");
            Element id2Elm = doc.createElement("id");
            id2Elm.setTextContent("package-" + d.getId());
            executionElm.appendChild(id2Elm);
            Element phaseElm = doc.createElement("phase");
            phaseElm.setTextContent("package");
            executionElm.appendChild(phaseElm);
            Element configurationElm = doc.createElement("configuration");
            executionElm.appendChild(configurationElm);
            Element classifierElm = doc.createElement("classifier");
            classifierElm.setTextContent(d.getId());
            configurationElm.appendChild(classifierElm);
            Element webappDirectoryElm = doc.createElement("webappDirectory");
            webappDirectoryElm
                    .setTextContent("${project.build.directory}/${project.build.finalName}_" + d.getId());
            configurationElm.appendChild(webappDirectoryElm);
            Element webResourcesElm = doc.createElement("webResources");
            Element resourceElm = doc.createElement("resource");
            Element directoryElm = doc.createElement("directory");
            directoryElm.setTextContent("src/env/" + d.getId());
            resourceElm.appendChild(directoryElm);
            webResourcesElm.appendChild(resourceElm);
            configurationElm.appendChild(webResourcesElm);
            Element goalsElm = doc.createElement("goals");
            executionElm.appendChild(goalsElm);
            Element goalElm = doc.createElement("goal");
            goalElm.setTextContent("war");
            goalsElm.appendChild(goalElm);
            thirdExecutionsNode.appendChild(executionElm);

            if (isDefaultDeployment) {
                NodeList directories = doc.getElementsByTagName("directory");
                Node directoryNode = directories.item(0);
                directoryNode.setTextContent("src/env/" + d.getId());
            }

            // Create different environment dependent configuration files.
            // Deployment environment dependent files will be stored in
            // src/env and will then be activated by choosing the corresponding
            // profile during the corresponding maven phase.
            // E.g. mvn tomcat:redeploy -P deployment1
            // will replace the deployment dependent files by the ones
            // available under src/env/deployment1.
            String generatedDir = st.getGenerateDir();
            String projMidfix = st.getProjectMidfix();
            String projDir = st.getProjectDirectory();
            String servDir = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId(), "WEB-INF/services",
                    projMidfix, "META-INF");
            FileUtils.forceMkdir(new File(servDir));

            String sxmlFile = FileUtil.makePath(generatedDir, projDir, "src/main/webapp/WEB-INF/services",
                    st.getProjectMidfix(), "META-INF") + "services.xml";

            GenericCode deplDepServXmlCode = new GenericCode(sxmlFile);

            //<parameter name="cliCommand1">${clicmd}</parameter>
            //<parameter name="processingUnit">${tomcat_public_procunitid}</parameter>
            //<parameter name="publicHttpAccessDir">${tomcat_public_http_access_dir}</parameter>
            //<parameter name="publicHttpAccessUrl">${tomcat_public_http_access_url}</parameter>
            //<parameter name="serviceUrlFilter">${service_url_filter}</parameter>
            List<Operation> operations = service.getOperations().getOperation();
            for (Operation operation : operations) {
                String command = operation.getCommand();
                String toolsbasedir = d.getToolsbasedir();
                if (toolsbasedir != null && !toolsbasedir.equals("")) {
                    command = toolsbasedir + command;
                }
                deplDepServXmlCode.put("cli_cmd_" + String.valueOf(operation.getOid()), command);
            }

            deplDepServXmlCode.put("tomcat_public_procunitid", d.getIdentifier());
            Dataexchange de = d.getDataexchange();

            String accessDir = FileUtil.makePath(de.getAccessdir());
            String accessUrl = de.getAccessurl();

            deplDepServXmlCode.put("tomcat_public_http_access_dir", accessDir);
            deplDepServXmlCode.put("tomcat_public_http_access_url", accessUrl);
            // TODO: filter
            //deplDepServXmlCode.put("service_url_filter", );
            deplDepServXmlCode.evaluate();

            deplDepServXmlCode.create(servDir + "services.xml");
            logger.debug("Writing: " + servDir + "services.xml");
            if (isDefaultDeployment) {
                defaultDeplServicesFile = servDir + "services.xml";
                defaultServicesFile = sxmlFile;
            }

            // source
            String htmlIndexSourcePath = FileUtil.makePath(generatedDir, projDir, "src/main", "webapp")
                    + "index.html";
            // substitution
            GenericCode htmlSourceIndexCode = new GenericCode(htmlIndexSourcePath);
            htmlSourceIndexCode.put("service_description", service.getDescription());
            htmlSourceIndexCode.put("tomcat_public_host", d.getHost());
            htmlSourceIndexCode.put("tomcat_public_http_port", port);
            // target
            String htmlIndexDir = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId());
            FileUtils.forceMkdir(new File(htmlIndexDir));
            String htmlIndexTargetPath = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId())
                    + "index.html";
            htmlSourceIndexCode.create(htmlIndexTargetPath);
            if (isDefaultDeployment) {
                this.defaultDeplHtmlFile = htmlIndexTargetPath;
                this.defaultHtmlFile = htmlIndexSourcePath;
            }

            // source
            String wsdlSourcePath = FileUtil.makePath(generatedDir, projDir, "src/main", "webapp")
                    + st.getProjectMidfix() + ".wsdl";
            // substitution
            GenericCode wsdlSourceCode = new GenericCode(wsdlSourcePath);
            wsdlSourceCode.put("tomcat_public_host", d.getHost());
            wsdlSourceCode.put("tomcat_public_http_port", port);
            // target
            String wsdlDir = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId());
            FileUtils.forceMkdir(new File(wsdlDir));
            String wsdlTargetPath = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId())
                    + st.getProjectMidfix() + ".wsdl";
            wsdlSourceCode.create(wsdlTargetPath);
            if (isDefaultDeployment) {
                this.defaultDeplWsdlFile = wsdlTargetPath;
                this.defaultWsdlFile = wsdlSourcePath;
            }
        }
        if (defaultDeplServicesFile != null && !defaultDeplServicesFile.isEmpty()) {
            FileUtils.copyFile(new File(defaultDeplServicesFile), new File(defaultServicesFile));
            FileUtils.copyFile(new File(this.defaultDeplHtmlFile), new File(this.defaultHtmlFile));
            FileUtils.copyFile(new File(this.defaultDeplWsdlFile), new File(this.defaultWsdlFile));
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        DOMSource source = new DOMSource(doc);
        FileOutputStream fos = new FileOutputStream(this.pomAbsPath);
        StreamResult result = new StreamResult(fos);
        transformer.transform(source, result);
        fos.close();
    } catch (Exception ex) {
        logger.error("An exception occurred: " + ex.getMessage());
    }
}

From source file:jp.ikedam.jenkins.plugins.viewcopy_builder.SetRegexOperation.java

/**
 * @param doc//from  w w w . j a  va2 s  .  c om
 * @param env
 * @param logger
 * @return
 * @see jp.ikedam.jenkins.plugins.viewcopy_builder.ViewcopyOperation#perform(org.w3c.dom.Document, hudson.EnvVars, java.io.PrintStream)
 */
@Override
public Document perform(Document doc, EnvVars env, PrintStream logger) {
    if (StringUtils.isEmpty(getRegex())) {
        logger.println("Regular expression is not specified.");
        return null;
    }

    String expandedRegex = StringUtils.trim(env.expand(getRegex()));
    if (StringUtils.isEmpty(expandedRegex)) {
        logger.println("Regular expression got to empty.");
        return null;
    }

    try {
        Pattern.compile(expandedRegex);
    } catch (PatternSyntaxException e) {
        e.printStackTrace(logger);
        return null;
    }

    Node regexNode;
    try {
        regexNode = getNode(doc, "/*/includeRegex");
    } catch (XPathExpressionException e) {
        e.printStackTrace(logger);
        return null;
    }

    if (regexNode == null) {
        // includeRegex is not exist.
        // create new one.
        regexNode = doc.createElement("includeRegex");
        doc.getDocumentElement().appendChild(regexNode);
    }

    regexNode.setTextContent(expandedRegex);
    logger.println(String.format("Set includeRegex to %s", expandedRegex));

    return doc;
}

From source file:cz.muni.fi.mir.mathmlunificator.utils.DOMBuilderTest.java

@Test
public void testCloneNodeToNewDoc() {

    try {/*w w  w.ja va  2  s.c  om*/

        String xmlString = "<math xmlns:uni=\"http://mir.fi.muni.cz/mathml-unification/\"\n"
                + "    uni:unification-level=\"2\" uni:unification-max-level=\"4\" xmlns=\"http://www.w3.org/1998/Math/MathML\">\n"
                + "    <msup>\n" + "        <mi>a</mi>\n" + "        <mi>b</mi>\n" + "    </msup>\n"
                + "    <mo>+</mo>\n" + "    <mfrac>\n" + "        <mi>c</mi>\n" + "        <mi>d</mi>\n"
                + "    </mfrac>\n" + "</math>";
        Document originalDoc = DOMBuilder.buildDoc(xmlString);
        Document doc = DOMBuilder.buildDoc(xmlString);

        // deep == true
        NodeList deepNodeList = doc.getElementsByTagNameNS("http://www.w3.org/1998/Math/MathML", "mo");
        assertEquals(deepNodeList.getLength(), 1);
        Node deepNode = deepNodeList.item(0);
        Node newDeepNode = DOMBuilder.cloneNodeToNewDoc(deepNode, true);
        System.out.println("testCloneNodeToNewDoc  deep output:\n"
                + XMLOut.xmlStringSerializer(newDeepNode.getOwnerDocument()));
        testXML("Deep clonning failed",
                DOMBuilder.buildDoc("<mo xmlns=\"http://www.w3.org/1998/Math/MathML\">+</mo>"),
                newDeepNode.getOwnerDocument());
        newDeepNode.setTextContent("deep different content");
        System.out.println("testCloneNodeToNewDoc  input document DOM after non-deep processing:\n"
                + XMLOut.xmlStringSerializer(doc));
        testXML("Original document DOM changed after processing", originalDoc, doc);

        // deep == false
        NodeList noDeepNodeList = doc.getElementsByTagNameNS("http://www.w3.org/1998/Math/MathML", "mfrac");
        assertEquals(noDeepNodeList.getLength(), 1);
        Node noDeepNode = noDeepNodeList.item(0);
        Node newNoDeepNode = DOMBuilder.cloneNodeToNewDoc(noDeepNode, false);
        System.out.println("testCloneNodeToNewDoc  non-deep output:\n"
                + XMLOut.xmlStringSerializer(newNoDeepNode.getOwnerDocument()));
        testXML("Non-deep clonning failed",
                DOMBuilder.buildDoc("<mfrac xmlns=\"http://www.w3.org/1998/Math/MathML\"/>"),
                newNoDeepNode.getOwnerDocument());
        newNoDeepNode.setTextContent("non-deep different content");
        System.out.println("testCloneNodeToNewDoc  input document DOM after non-deep processing:\n"
                + XMLOut.xmlStringSerializer(doc));
        testXML("Original document DOM changed after processing", originalDoc, doc);

    } catch (ParserConfigurationException | SAXException | IOException ex) {
        fail(ex.getMessage());
    }

}

From source file:jp.ikedam.jenkins.plugins.viewcopy_builder.SetDescriptionOperation.java

/**
 * @param doc// w w w  . j a v a 2s .c  om
 * @param env
 * @param logger
 * @return
 * @see jp.ikedam.jenkins.plugins.viewcopy_builder.ViewcopyOperation#perform(org.w3c.dom.Document, hudson.EnvVars, java.io.PrintStream)
 */
@Override
public Document perform(Document doc, EnvVars env, PrintStream logger) {
    Node descNode;
    try {
        descNode = getNode(doc, "/*/description");
    } catch (XPathExpressionException e) {
        e.printStackTrace(logger);
        return null;
    }

    if (descNode == null) {
        // includeRegex is not exist.
        // create new one.
        descNode = doc.createElement("description");
        doc.getDocumentElement().appendChild(descNode);
    }

    String description = (getDescription() != null) ? StringUtils.trim(env.expand(getDescription())) : "";

    descNode.setTextContent(description);
    logger.println(String.format("Set description to:\n%s", description));

    return doc;
}

From source file:isl.FIMS.servlet.imports.ImportXML.java

private Document createAdminPart(String fileId, String type, Document doc, String username) {
    //create admin element
    String query = "name(//admin/parent::*)";
    DBFile dbf = new DBFile(this.DBURI, this.systemDbCollection + type, type + ".xml", this.DBuser,
            this.DBpassword);
    String parentOfAdmin = dbf.queryString(query)[0];
    Element parentElement = (Element) doc.getElementsByTagName(parentOfAdmin).item(0);
    Element admin = doc.createElement("admin");
    parentElement.appendChild(admin);/* w w  w  .  ja v  a2 s . co  m*/

    //create id element
    String id = fileId.split(type)[1];
    Element idE = doc.createElement("id");
    idE.appendChild(doc.createTextNode(id));
    admin.appendChild(idE);

    //create uri_id element
    String uri_name = "";
    try {
        uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0];
    } catch (DMSException ex) {
        ex.printStackTrace();
    }
    String uriValue = this.URI_Reference_Path + uri_name + "/" + id;
    String uriPath = UtilsXPaths.getPathUriField(type);
    Element uriId = doc.createElement("uri_id");
    uriId.appendChild(doc.createTextNode(uriValue));
    admin.appendChild(uriId);
    if (!uriPath.equals("")) {
        try {
            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList nodes = (NodeList) xPath.evaluate(uriPath, doc.getDocumentElement(),
                    XPathConstants.NODESET);
            Node oldChild = nodes.item(0);
            if (oldChild != null) {
                oldChild.setTextContent(uriValue);
            }
        } catch (XPathExpressionException ex) {
            ex.printStackTrace();
        }
    }

    //create lang element
    Element lang = doc.createElement("lang");
    lang.appendChild(doc.createTextNode(this.lang));
    admin.appendChild(lang);

    //create organization element
    Element organization = doc.createElement("organization");
    organization.appendChild(doc.createTextNode(this.getUserGroup(username)));
    admin.appendChild(organization);

    //create creator element
    Element creator = doc.createElement("creator");
    creator.appendChild(doc.createTextNode(username));
    admin.appendChild(creator);

    //create creator element
    Element saved = doc.createElement("saved");
    saved.appendChild(doc.createTextNode("yes"));
    admin.appendChild(saved);

    //create locked element
    Element locked = doc.createElement("locked");
    locked.appendChild(doc.createTextNode("no"));
    admin.appendChild(locked);
    Element status = doc.createElement("status");
    if (GetEntityCategory.getEntityCategory(type).equals("primary")) {
        status.appendChild(doc.createTextNode("unpublished"));
    }
    admin.appendChild(status);

    //create version elemnt
    Element versions = doc.createElement("versions");

    //create versionidr elememt
    Element versionId = doc.createElement("versionId");
    versionId.appendChild(doc.createTextNode("1"));
    versions.appendChild(versionId);

    //create versionUser elememt
    Element versionUser = doc.createElement("versionUser");
    versionUser.appendChild(doc.createTextNode(username));
    versions.appendChild(versionUser);

    //create versionDate elememt
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = new Date();
    Element versionDate = doc.createElement("versionDate");
    versionDate.appendChild(doc.createTextNode(dateFormat.format(date)));
    versions.appendChild(versionDate);

    admin.appendChild(versions);
    //create read element
    Element read = doc.createElement("read");
    read.appendChild(doc.createTextNode(username));
    admin.appendChild(read);

    //create write element
    Element write = doc.createElement("write");
    write.appendChild(doc.createTextNode(username));
    admin.appendChild(write);

    //create status element
    //create imported element
    Element imported = doc.createElement("imported");
    imported.appendChild(doc.createTextNode(username));
    admin.appendChild(imported);

    return doc;
}