Example usage for org.w3c.dom Document createAttribute

List of usage examples for org.w3c.dom Document createAttribute

Introduction

In this page you can find the example usage for org.w3c.dom Document createAttribute.

Prototype

public Attr createAttribute(String name) throws DOMException;

Source Link

Document

Creates an Attr of the given name.

Usage

From source file:org.wso2.appserver.test.integration.TestListener.java

/**
 * Registers an Apache Tomcat Valve in the server.xml of the Application Server Catalina config base.
 *
 * @param className the fully qualified class name of the Valve implementation
 * @throws ParserConfigurationException if a DocumentBuilder cannot be created
 * @throws SAXException                 if any parse errors occur
 * @throws IOException                  if an I/O error occurs
 * @throws XPathExpressionException     if the XPath expression cannot be evaluated
 * @throws TransformerException         if an error occurs during the transformation
 *//*  www  .j av  a2 s  .  c o m*/
private static void addValveToServerXML(String className) throws ParserConfigurationException, SAXException,
        IOException, XPathExpressionException, TransformerException {
    Path serverXML = Paths.get(System.getProperty(TestConstants.APPSERVER_HOME), "conf", "server.xml");
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new InputSource(serverXML.toString()));
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList valves = (NodeList) xpath.evaluate("/Server/Service/Engine/Host/Valve", document,
            XPathConstants.NODESET);

    Element valve = document.createElement("Valve");
    Attr attrClassName = document.createAttribute("className");
    attrClassName.setValue(className);
    valve.setAttributeNode(attrClassName);
    valves.item(0).getParentNode().appendChild(valve);

    Transformer xFormer = TransformerFactory.newInstance().newTransformer();
    xFormer.transform(new DOMSource(document), new StreamResult(serverXML.toFile().getAbsolutePath()));
}

From source file:org.wso2.carbon.identity.user.store.configuration.UserStoreConfigAdminService.java

/**
 * Adds a property//from w  w w  . j a v a2 s  .  co  m
 *
 * @param name:   Name of property
 * @param value:  Value
 * @param doc:    Document
 * @param parent: Parent element of the property to be added as a child
 */
private void addProperty(String name, String value, Document doc, Element parent, boolean encrypted) {
    Element property = doc.createElement("Property");
    Attr attr;
    if (encrypted) {
        attr = doc.createAttribute("encrypted");
        attr.setValue("true");
        property.setAttributeNode(attr);
    }

    attr = doc.createAttribute("name");
    attr.setValue(name);
    property.setAttributeNode(attr);

    property.setTextContent(value);
    parent.appendChild(property);
}

From source file:org.wso2.carbon.identity.user.store.configuration.UserStoreConfigAdminService.java

private void writeUserMgtXMLFile(File userStoreConfigFile, UserStoreDTO userStoreDTO,
        boolean editSecondaryUserStore) throws IdentityUserStoreMgtException {
    StreamResult result = new StreamResult(userStoreConfigFile);
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();

    try {//  ww  w. jav a2  s  .  c  o  m
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();

        //create UserStoreManager element
        Element userStoreElement = doc
                .createElement(UserCoreConstants.RealmConfig.LOCAL_NAME_USER_STORE_MANAGER);
        doc.appendChild(userStoreElement);

        Attr attrClass = doc.createAttribute("class");
        attrClass.setValue(userStoreDTO.getClassName());
        userStoreElement.setAttributeNode(attrClass);

        addProperties(userStoreDTO.getClassName(), userStoreDTO.getProperties(), doc, userStoreElement,
                editSecondaryUserStore);
        addProperty(UserStoreConfigConstants.DOMAIN_NAME, userStoreDTO.getDomainId(), doc, userStoreElement,
                false);
        addProperty(DESCRIPTION, userStoreDTO.getDescription(), doc, userStoreElement, false);
        DOMSource source = new DOMSource(doc);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "6");
        transformer.transform(source, result);
    } catch (ParserConfigurationException e) {
        String errMsg = " Error occurred due to serious parser configuration exception of "
                + userStoreConfigFile;
        throw new IdentityUserStoreMgtException(errMsg, e);
    } catch (TransformerException e) {
        String errMsg = " Error occurred during the transformation process of " + userStoreConfigFile;
        throw new IdentityUserStoreMgtException(errMsg, e);
    }
}

From source file:org.wso2.developerstudio.eclipse.artifact.bpel.ui.wizard.BPELSecurityWizard.java

/**
 * Creates the service.xml file if it is not available
 * // w  w  w. ja v a2 s .  co m
 * @param serviceXML
 * @return
 * @throws ParserConfigurationException
 * @throws TransformerException
 */
private void createServiceXML(File serviceXML) throws ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root element
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement(SERVICE_GROUP_TAG);
    doc.appendChild(rootElement);

    List<String> serviceList = securityPage.getServicesFromWSDLs();
    for (String service : serviceList) {
        Element serviceElement = doc.createElement(SERVICE_NODE);
        rootElement.appendChild(serviceElement);

        Attr attr = doc.createAttribute(NAME_ATTRIBUTE);
        attr.setValue(service);
        serviceElement.setAttributeNode(attr);

    }

    // write the content into xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(serviceXML);
    transformer.transform(source, result);
}

From source file:uk.sipperfly.ui.BackgroundWorker.java

/**
 * create bag-info.xml file at transfer destination
 *///w w w  .ja  v  a2 s  .c o m
public void createXML(String payload, String date, String size) {
    try {
        char[] charArray = { '<', '>', '&', '"', '\\', '!', '#', '$', '%', '\'', '(', ')', '*', '.', ':', '+',
                ',', '/', ';', '=', '?', '@', '[', ']', '^', '`', '{', '|', '}', '~' };
        //      List<char[]> asList = Arrays.asList(charArray);
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("transfer_metadata");
        doc.appendChild(rootElement);

        Attr attr1 = doc.createAttribute("xmlns:xsi");
        attr1.setValue("http://www.w3.org/2001/XMLSchema-instance");
        rootElement.setAttributeNode(attr1);

        Element payLoad = doc.createElement("Payload-Oxum");
        payLoad.appendChild(doc.createTextNode(payload));
        rootElement.appendChild(payLoad);

        Element baggingDate = doc.createElement("Bagging-Date");
        baggingDate.appendChild(doc.createTextNode(date));
        rootElement.appendChild(baggingDate);

        Element bagsize = doc.createElement("Bag-Size");
        bagsize.appendChild(doc.createTextNode(size));
        rootElement.appendChild(bagsize);

        BagInfoRepo bagInfoRepo = new BagInfoRepo();
        List<BagInfo> bagInfo = bagInfoRepo.getOneOrCreateOne();

        for (BagInfo b : bagInfo) {
            StringBuilder stringBuilder = new StringBuilder();
            char[] txt = Normalizer.normalize(b.getLabel(), Normalizer.Form.NFD).toCharArray();
            for (int i = 0; i < b.getLabel().length(); i++) {
                int check = 0;
                for (int j = 0; j < charArray.length; j++) {
                    if (txt[i] == charArray[j]) {
                        check = 1;

                    }
                }
                if (check == 0) {
                    stringBuilder.append(txt[i]);
                }
            }
            Element firstname = doc.createElement(stringBuilder.toString().replace(" ", "-"));
            firstname.appendChild(doc.createTextNode(b.getValue().trim()));
            rootElement.appendChild(firstname);

        }
        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(
                new File(this.target.toString() + File.separator + "bag-info.xml"));
        transformer.transform(source, result);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(BackgroundWorker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TransformerConfigurationException ex) {
        Logger.getLogger(BackgroundWorker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (TransformerException ex) {
        Logger.getLogger(BackgroundWorker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DOMException ex) {
        Logger.getLogger(BackgroundWorker.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:uk.sipperfly.utils.CommonUtil.java

/**
 * Create xml file to export//from   ww  w.  ja  v a2s .  c om
 *
 * @param recipient
 * @param ftp
 * @param config
 * @param bagInfo
 * @param path
 */
public String createXMLExport(List<Recipients> recipient, FTP ftp, Configurations config, List<BagInfo> bagInfo,
        String path, Boolean template) {
    try {
        char[] charArray = { '<', '>', '&', '"', '\\', '!', '#', '$', '%', '\'', '(', ')', '*', '+', ',', '/',
                ':', ';', '=', '?', '@', '[', ']', '^', '`', '{', '|', '}', '~' };
        String name = "Exactly_Configuration_" + System.currentTimeMillis() + ".xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element temElement = doc.createElement("Exactly");
        doc.appendChild(temElement);
        //////bag info
        Element bagElement = doc.createElement("Metadata");
        temElement.appendChild(bagElement);

        for (BagInfo b : bagInfo) {
            StringBuilder stringBuilder = new StringBuilder();
            char[] txt = Normalizer.normalize(b.getLabel(), Normalizer.Form.NFD).toCharArray();
            for (int i = 0; i < b.getLabel().length(); i++) {
                int check = 0;
                for (int j = 0; j < charArray.length; j++) {
                    if (txt[i] == charArray[j]) {
                        check = 1;

                    }
                }
                if (check == 0) {
                    stringBuilder.append(txt[i]);
                }
            }
            Element firstname = doc.createElement(stringBuilder.toString().replace(" ", "-"));
            firstname.appendChild(doc.createTextNode(b.getValue()));
            Attr attr = doc.createAttribute("label");
            attr.setValue(Normalizer.normalize(b.getLabel(), Normalizer.Form.NFD).toString());
            firstname.setAttributeNode(attr);
            bagElement.appendChild(firstname);
        }
        //////emails
        Element recipientElement = doc.createElement("Recipients");
        temElement.appendChild(recipientElement);

        for (Recipients r : recipient) {
            if (r.getEmail() != null) {
                Element mail = doc.createElement("Email");
                mail.appendChild(doc.createTextNode(r.getEmail()));
                recipientElement.appendChild(mail);
            }
        }
        //////////ftp
        Element ftpElement = doc.createElement("FTP");
        temElement.appendChild(ftpElement);

        Element server = doc.createElement("Host");
        if (ftp.getHostName() != null) {
            server.appendChild(doc.createTextNode(ftp.getHostName()));
        } else {
            server.appendChild(doc.createTextNode(""));
        }
        ftpElement.appendChild(server);

        Element user = doc.createElement("Username");
        if (ftp.getUsername() != null) {
            user.appendChild(doc.createTextNode(ftp.getUsername()));
        } else {
            user.appendChild(doc.createTextNode(""));
        }
        ftpElement.appendChild(user);

        Element password1 = doc.createElement("Password");

        if (ftp.getPassword() == null || ftp.getPassword() == "") {
            password1.appendChild(doc.createTextNode(""));
        } else {
            password1.appendChild(doc.createTextNode(EncryptDecryptUtil.encrypt(ftp.getPassword())));
        }
        ftpElement.appendChild(password1);

        Element port = doc.createElement("Port");
        port.appendChild(doc.createTextNode(String.valueOf(ftp.getPort())));
        ftpElement.appendChild(port);

        Element protocol = doc.createElement("Mode");
        protocol.appendChild(doc.createTextNode(ftp.getMode()));
        ftpElement.appendChild(protocol);

        Element email = doc.createElement("Destination");
        if (ftp.getDestination() != null) {
            email.appendChild(doc.createTextNode(ftp.getDestination()));
        } else {
            email.appendChild(doc.createTextNode(""));
        }
        ftpElement.appendChild(email);
        //////configurations
        Element configElement = doc.createElement("configurations");
        temElement.appendChild(configElement);

        Element server1 = doc.createElement("Server-Name");
        if (config.getServerName() != null) {
            server1.appendChild(doc.createTextNode(config.getServerName()));
        } else {
            server1.appendChild(doc.createTextNode(""));
        }
        configElement.appendChild(server1);

        Element user1 = doc.createElement("Username");
        if (config.getUsername() != null) {
            user1.appendChild(doc.createTextNode(config.getUsername()));
        } else {
            user1.appendChild(doc.createTextNode(""));
        }
        configElement.appendChild(user1);

        Element password = doc.createElement("Password");

        if (config.getPassword() == null || config.getPassword() == "") {
            password.appendChild(doc.createTextNode(""));
        } else {
            password.appendChild(doc.createTextNode(EncryptDecryptUtil.encrypt(config.getPassword())));
        }
        configElement.appendChild(password);

        Element port1 = doc.createElement("Port");
        port1.appendChild(doc.createTextNode(config.getServerPort()));
        configElement.appendChild(port1);

        Element protocol1 = doc.createElement("Protocol");
        protocol1.appendChild(doc.createTextNode(config.getServerProtocol()));
        configElement.appendChild(protocol1);

        Element email1 = doc.createElement("Email-Notification");
        if (config.getEmailNotifications()) {
            email1.appendChild(doc.createTextNode("true"));
        } else {
            email1.appendChild(doc.createTextNode("false"));
        }

        configElement.appendChild(email1);
        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        if (template) {
            StringWriter writer = new StringWriter();
            transformer.transform(source, new StreamResult(writer));
            String output = writer.getBuffer().toString();
            return output;
        } else {
            StreamResult result = new StreamResult(new File(path + File.separator + name));
            transformer.transform(source, result);
        }
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(CommonUtil.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(CommonUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "XML exported";
}