Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static void updateUserMgtXML(File userMgtXML, String jndiConfigNameUserDB) throws Exception {
        Document doc = initializeXML(userMgtXML);
        NodeList configNodeList = doc.getElementsByTagName("Configuration");
        Node configNode = configNodeList.item(0); //get the 0 index, since only one available

        NodeList nodeList = configNode.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                if (node.getNodeName().equalsIgnoreCase("Property")) {
                    if (node.hasAttributes()) {
                        NamedNodeMap namedNodeMap = node.getAttributes();
                        Node attr = namedNodeMap.getNamedItem("name");
                        if (attr != null && attr.getNodeValue().equalsIgnoreCase("dataSource")) {
                            node.setTextContent(jndiConfigNameUserDB);
                        }
                    }
                }
            }
        }
        finalizeXML(userMgtXML, doc, 4);
    }

    private static Document initializeXML(File xmlFile) throws Exception {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);
        doc.getDocumentElement().normalize();
        return doc;
    }

    private static void finalizeXML(File xmlFile, Document doc, int intendAmount) throws Exception {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(xmlFile);
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "" + intendAmount);
        transformer.setOutputProperty("indent", "yes");
        transformer.transform(source, result);
    }
}