Example usage for org.w3c.dom Attr setValue

List of usage examples for org.w3c.dom Attr setValue

Introduction

In this page you can find the example usage for org.w3c.dom Attr setValue.

Prototype

public void setValue(String value) throws DOMException;

Source Link

Document

On retrieval, the value of the attribute is returned as a string.

Usage

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

/**
 * Adds a property//from   ww w . ja va2  s . c om
 *
 * @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 {//from  w w  w .  j av a 2s.  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
 * /*from ww w. j av  a 2 s .c  o 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:pl.net.ptak.PrqPrePackageMojo.java

/**
 * @param fileSizeAttr/*from  w  w w .j a  va2  s. c  om*/
 * @param dependencyFile
 */
private void setNewSizeForFile(Attr fileSizeAttr, File dependencyFile) {
    fileSizeAttr.setValue(String.format("0,%d", dependencyFile.length()));
}

From source file:pl.net.ptak.PrqPrePackageMojo.java

/**
 * @param dependencyFile/*from  w  ww  . j  a  v  a  2 s  .  c om*/
 * @param dependencyFileAttr
 */
private void setNewMd5ChecksumForFile(Attr dependencyFileAttr, File dependencyFile)
        throws MojoFailureException {
    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(dependencyFile);
        String md5 = DigestUtils.md5Hex(fileInputStream);
        dependencyFileAttr.setValue(md5.toUpperCase());
    } catch (FileNotFoundException e) {
        String message = String.format("File %s not found", dependencyFile);
        String shortMessage = "File not found";
        getLog().debug(message, e);
        throw new MojoFailureException(e, shortMessage, message);
    } catch (IOException e) {
        String message = String.format("Failed to calculate checksum for file %s", dependencyFile);
        String shortMessage = "Failed to calculate checksum";
        getLog().debug(message, e);
        throw new MojoFailureException(e, shortMessage, message);
    } finally {
        try {
            fileInputStream.close();
        } catch (IOException e) {
            String message = String.format("Failed to close filestream for file %s", dependencyFile);
            String shortMessage = "Failed to close filestream";
            getLog().debug(message, e);
            throw new MojoFailureException(e, shortMessage, message);
        }
    }
}

From source file:pl.net.ptak.PrqPrePackageMojo.java

private String calculateAndSetNewRelativePath(File dependencyFile, File relativePathRoot,
        Attr dependencyFileAttr) throws IOException {

    String relativeOutputPath = dependencyFile.getCanonicalPath()
            .substring(relativePathRoot.getCanonicalPath().length());
    String newRelativePath = relativePackageSubFolderPrefix + relativeOutputPath;

    dependencyFileAttr.setValue(newRelativePath);

    getLog().debug(String.format("New relative path for %s was set to %s", dependencyFile.getCanonicalPath(),
            newRelativePath));/*from w w w  .j  a v a  2s . c o m*/

    return relativeOutputPath;
}

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

/**
 * create bag-info.xml file at transfer destination
 *///  w  w w  . ja  va2 s.c om
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  w w  w.  j  a  v  a  2 s  . 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";
}