Example usage for org.w3c.dom Element setAttributeNode

List of usage examples for org.w3c.dom Element setAttributeNode

Introduction

In this page you can find the example usage for org.w3c.dom Element setAttributeNode.

Prototype

public Attr setAttributeNode(Attr newAttr) throws DOMException;

Source Link

Document

Adds a new attribute node.

Usage

From source file:org.mrgeo.resources.tms.TileMapServiceResource.java

protected static Document rootResourceXml(final String url) throws ParserConfigurationException {
    /*/*from  w  w  w  .jav a 2 s  .c  o m*/
     * <?xml version="1.0" encoding="UTF-8" ?> <Services> <TileMapService
     * title="MrGeo Tile Map Service" version="1.0.0"
     * href="http://localhost:8080/mrgeo-services/api/tms/1.0.0" /> </Services>
     */

    final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    final Document doc = docBuilder.newDocument();
    final Element rootElement = doc.createElement("Services");
    doc.appendChild(rootElement);
    final Element tms = doc.createElement("TileMapService");
    rootElement.appendChild(tms);
    final Attr title = doc.createAttribute("title");
    title.setValue("MrGeo Tile Map Service");
    tms.setAttributeNode(title);
    final Attr v = doc.createAttribute("version");
    v.setValue(VERSION);
    tms.setAttributeNode(v);
    final Attr href = doc.createAttribute("href");
    href.setValue(normalizeUrl(url) + "/" + VERSION);
    tms.setAttributeNode(href);

    return doc;
}

From source file:org.ojbc.util.xml.XmlUtils.java

/**
 * Add an attribute to the specified element
 * @param parent the element to which we add the attribute
 * @param ns the namespace of the attribute
 * @param attributeName the name of the attribute
 * @param value the value of the attribute
 * @return the attribute//from w  ww .  ja  va  2 s . c  o  m
 */
public static final Attr addAttribute(Element parent, String ns, String attributeName, String value) {
    Document doc = parent.getOwnerDocument();
    Attr ret = doc.createAttributeNS(ns, attributeName);
    ret.setTextContent(value);
    ret.setPrefix(OJBC_NAMESPACE_CONTEXT.getPrefix(ns));
    parent.setAttributeNode(ret);
    return ret;
}

From source file:org.osaf.cosmo.xml.DomReader.java

private static Element readElement(Document d, XMLStreamReader reader) throws XMLStreamException {
    Element e = null;

    String local = reader.getLocalName();
    String ns = reader.getNamespaceURI();
    if (ns != null) {
        String prefix = reader.getPrefix();
        String qualified = prefix != null ? prefix + ":" + local : local;
        e = d.createElementNS(ns, qualified);
    } else {/*from   ww  w . j  av  a 2 s .  c om*/
        e = d.createElement(local);
    }

    //if (log.isDebugEnabled())
    //log.debug("Reading element " + e.getTagName());

    for (int i = 0; i < reader.getAttributeCount(); i++) {
        Attr a = readAttribute(i, d, reader);
        if (a.getNamespaceURI() != null)
            e.setAttributeNodeNS(a);
        else
            e.setAttributeNode(a);
    }

    return e;
}

From source file:org.sakaiproject.tool.rutgers.LinkToolEntityProducer.java

/**
 * {@inheritDoc}/*from  w ww .  j a  va 2  s  . com*/
 */
public String archive(String siteId, Document doc, Stack stack, String archivePath, List attachments) {
    //prepare the buffer for the results log
    StringBuilder results = new StringBuilder();

    try {
        Site site = SiteService.getSite(siteId);
        // start with an element with our very own (service) name         
        Element element = doc.createElement(serviceName());
        element.setAttribute(VERSION_ATTR, ARCHIVE_VERSION);
        ((Element) stack.peek()).appendChild(element);
        stack.push(element);

        Element linktool = doc.createElement(LINKTOOL);
        Collection<ToolConfiguration> tools = site.getTools(myToolIds());
        if (tools != null && !tools.isEmpty()) {
            for (ToolConfiguration config : tools) {
                element = doc.createElement(LINKTOOL);

                Attr attr = doc.createAttribute("toolid");
                attr.setValue(config.getToolId());
                element.setAttributeNode(attr);

                attr = doc.createAttribute("name");
                attr.setValue(config.getContainingPage().getTitle());
                element.setAttributeNode(attr);

                Properties props = config.getConfig();
                if (props == null)
                    continue;

                String url = props.getProperty("url", null);
                if (url == null && props != null) {
                    String urlProp = props.getProperty("urlProp", null);
                    if (urlProp != null) {
                        url = ServerConfigurationService.getString(urlProp);
                    }
                }

                attr = doc.createAttribute("url");
                attr.setValue(url);
                element.setAttributeNode(attr);

                String height = "600";
                String heights = props.getProperty("height", "600");
                if (heights != null) {
                    heights = heights.trim();
                    if (heights.endsWith("px"))
                        heights = heights.substring(0, heights.length() - 2).trim();
                    height = heights;
                }

                attr = doc.createAttribute("height");
                attr.setValue(height);
                element.setAttributeNode(attr);

                linktool.appendChild(element);
            }

            results.append("archiving " + getLabel() + ": (" + tools.size()
                    + ") linktool instances archived successfully.\n");

        } else {
            results.append("archiving " + getLabel() + ": no linktools.\n");
        }

        ((Element) stack.peek()).appendChild(linktool);
        stack.push(linktool);

        stack.pop();
    } catch (Exception any) {
        logger.warn("archive: exception archiving service: " + serviceName());
    }

    stack.pop();

    return results.toString();
}

From source file:org.sakaiproject.webservices.SakaiScript.java

/**
 * Return XML document listing all pages and tools in those pages for a given site.
 * The session id must be of a valid, active user in that site, or a super user, or it will throw an exception.
 * If a page is hidden in a site, the page and all tools in that page will be skipped from the returned document, as they are in the portal.
 * Super user's can request any site to retrieve the full list.
 *
 * @param sessionid the session id of a user in a site, or a super user
 * @param siteid    the site to retrieve the information for
 * @return xml or an empty list <site/>. The return XML format is below:
 * <site id="9ec48d9e-b690-4090-a300-10a44ed7656e">
 * <pages>//from   w w w.  ja va 2s  .  c o  m
 * <page id="ec1b0ab8-90e8-4d4d-bf64-1e586035f08f">
 * <page-title>Home</page-title>
 * <tools>
 * <tool id="dafd2a4d-8d3f-4f4c-8e12-171968b259cd">
 * <tool-id>sakai.iframe.site</tool-id>
 * <tool-title>Site Information Display</tool-title>
 * </tool>
 * ...
 * </tools>
 * </page>
 * <page>
 * ...
 * </page>
 * ...
 * </pages>
 * </site>
 * @throws RuntimeException if not a super user and the user attached to the session is not in the site, if site does not exist
 */
@WebMethod
@Path("/getPagesAndToolsForSiteForCurrentUser")
@Produces("text/plain")
@GET
public String getPagesAndToolsForSiteForCurrentUser(
        @WebParam(name = "sessionid", partName = "sessionid") @QueryParam("sessionid") String sessionid,
        @WebParam(name = "siteid", partName = "siteid") @QueryParam("siteid") String siteid) {
    Session session = establishSession(sessionid);

    //check if site exists
    Site site;
    try {
        site = siteService.getSite(siteid);
    } catch (Exception e) {
        LOG.warn("WS getPagesAndToolsForSiteForCurrentUser(): Error looking up site: " + siteid + ":"
                + e.getClass().getName() + " : " + e.getMessage());
        throw new RuntimeException("WS getPagesAndToolsForSiteForCurrentUser(): Error looking up site: "
                + siteid + ":" + e.getClass().getName() + " : " + e.getMessage());
    }

    String userId = session.getUserId();

    //check if super user
    boolean isSuperUser = false;
    if (securityService.isSuperUser(userId)) {
        isSuperUser = true;
    }

    //if not super user, check user is a member of the site, and get their Role
    Role role;
    if (!isSuperUser) {
        Member member = site.getMember(userId);
        if (member == null || !member.isActive()) {
            LOG.warn("WS getPagesAndToolsForSiteForCurrentUser(): User: " + userId
                    + " does not exist in site : " + siteid);
            throw new RuntimeException("WS getPagesAndToolsForSiteForCurrentUser(): User: " + userId
                    + " does not exist in site : " + siteid);
        }
        role = member.getRole();
    }

    //get list of pages in the site, if none, return empty list
    List<SitePage> pages = site.getPages();
    if (pages.isEmpty()) {
        return "<site id=\"" + site.getId() + "\"/>";
    }

    //site node
    Document dom = Xml.createDocument();
    Element siteNode = dom.createElement("site");
    Attr siteIdAttr = dom.createAttribute("id");
    siteIdAttr.setNodeValue(site.getId());
    siteNode.setAttributeNode(siteIdAttr);

    //pages node
    Element pagesNode = dom.createElement("pages");

    for (SitePage page : pages) {

        //page node
        Element pageNode = dom.createElement("page");
        Attr pageIdAttr = dom.createAttribute("id");
        pageIdAttr.setNodeValue(page.getId());
        pageNode.setAttributeNode(pageIdAttr);

        //pageTitle
        Element pageTitleNode = dom.createElement("page-title");
        pageTitleNode.appendChild(dom.createTextNode(page.getTitle()));

        //get tools in page
        List<ToolConfiguration> tools = page.getTools();

        Element toolsNode = dom.createElement("tools");

        boolean includePage = true;
        for (ToolConfiguration toolConfig : tools) {
            //if we not a superAdmin, check the page properties
            //if any tool on this page is hidden, skip the rest of the tools and exclude this page from the output
            //this makes the behaviour consistent with the portal

            //if not superUser, process  tool function requirements
            if (!isSuperUser) {

                //skip processing tool if we've skipped tools previously on this page
                if (!includePage) {
                    continue;
                }

                //skip this tool if not visible, ultimately hiding the whole page
                if (!toolManager.isVisible(site, toolConfig)) {
                    includePage = false;
                    break;
                }
            }

            //if we got this far, add the details about the tool to the document
            Element toolNode = dom.createElement("tool");

            //tool uuid
            Attr toolIdAttr = dom.createAttribute("id");
            toolIdAttr.setNodeValue(toolConfig.getId());
            toolNode.setAttributeNode(toolIdAttr);

            //registration (eg sakai.profile2)
            Element toolIdNode = dom.createElement("tool-id");
            toolIdNode.appendChild(dom.createTextNode(toolConfig.getToolId()));
            toolNode.appendChild(toolIdNode);

            Element toolTitleNode = dom.createElement("tool-title");
            toolTitleNode.appendChild(dom.createTextNode(toolConfig.getTitle()));
            toolNode.appendChild(toolTitleNode);

            toolsNode.appendChild(toolNode);

        }

        //if the page is not hidden, add the elements
        if (includePage) {
            pageNode.appendChild(pageTitleNode);
            pageNode.appendChild(toolsNode);
            pagesNode.appendChild(pageNode);
        }
    }

    //add the main nodes
    siteNode.appendChild(pagesNode);
    dom.appendChild(siteNode);

    return Xml.writeDocumentToString(dom);
}

From source file:org.talend.designer.maven.utils.PomUtil.java

/**
 * //  w  ww .j  a  va 2  s  .c o  m
 * Create pom without refresh eclipse resources
 * 
 * @param artifact
 * @return
 */
public static String generatePom2(MavenArtifact artifact) {
    try {
        Project project = ProjectManager.getInstance().getCurrentProject();
        IProject fsProject = ResourceUtils.getProject(project);
        SecureRandom random = new SecureRandom();
        IPath tempPath = fsProject.getLocation().append("temp").append("pom" + Math.abs(random.nextLong()));
        File tmpFolder = new File(tempPath.toPortableString());
        tmpFolder.mkdirs();
        String pomFile = tempPath.append(TalendMavenConstants.POM_FILE_NAME).toPortableString();
        Model pomModel = new Model();
        pomModel.setModelVersion(TalendMavenConstants.POM_VERSION);
        pomModel.setModelEncoding(TalendMavenConstants.DEFAULT_ENCODING);
        pomModel.setGroupId(artifact.getGroupId());
        pomModel.setArtifactId(artifact.getArtifactId());
        pomModel.setVersion(artifact.getVersion());
        String artifactType = artifact.getType();
        if (artifactType == null || "".equals(artifactType)) {
            artifactType = TalendMavenConstants.PACKAGING_JAR;
        }
        pomModel.setPackaging(artifactType);

        ByteArrayOutputStream buf = new ByteArrayOutputStream();

        MavenPlugin.getMaven().writeModel(pomModel, buf);

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(false);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        TransformerFactory tfactory = TransformerFactory.newInstance();

        Document document = documentBuilder.parse(new ByteArrayInputStream(buf.toByteArray()));
        Element documentElement = document.getDocumentElement();

        NamedNodeMap attributes = documentElement.getAttributes();

        if (attributes == null || attributes.getNamedItem("xmlns") == null) { //$NON-NLS-1$
            Attr attr = document.createAttribute("xmlns"); //$NON-NLS-1$
            attr.setTextContent("http://maven.apache.org/POM/4.0.0"); //$NON-NLS-1$
            documentElement.setAttributeNode(attr);
        }

        if (attributes == null || attributes.getNamedItem("xmlns:xsi") == null) { //$NON-NLS-1$
            Attr attr = document.createAttribute("xmlns:xsi"); //$NON-NLS-1$
            attr.setTextContent("http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$
            documentElement.setAttributeNode(attr);
        }

        if (attributes == null || attributes.getNamedItem("xsi:schemaLocation") == null) { //$NON-NLS-1$
            Attr attr = document.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", //$NON-NLS-1$
                    "xsi:schemaLocation"); //$NON-NLS-1$
            attr.setTextContent(
                    "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"); //$NON-NLS-1$
            documentElement.setAttributeNode(attr);
        }
        Transformer transformer = tfactory.newTransformer();
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(new File(pomFile));
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(source, result);

        return pomFile;
    } catch (PersistenceException e) {
        ExceptionHandler.process(e);
    } catch (CoreException e) {
        ExceptionHandler.process(e);
    } catch (ParserConfigurationException e) {
        ExceptionHandler.process(e);
    } catch (SAXException e) {
        ExceptionHandler.process(e);
    } catch (IOException e) {
        ExceptionHandler.process(e);
    } catch (TransformerConfigurationException e) {
        ExceptionHandler.process(e);
    } catch (TransformerException e) {
        ExceptionHandler.process(e);
    }
    return null;
}

From source file:org.unitedinternet.cosmo.util.DomReader.java

private static Element readElement(Document d, XMLStreamReader reader) throws XMLStreamException {
    Element e = null;

    String local = reader.getLocalName();
    String ns = reader.getNamespaceURI();
    if (ns != null && !ns.equals("")) {
        String prefix = reader.getPrefix();
        String qualified = prefix != null && !prefix.isEmpty() ? prefix + ":" + local : local;
        e = d.createElementNS(ns, qualified);
    } else {/*from  w  w  w  .j a va 2s. co  m*/
        e = d.createElement(local);
    }

    //if (log.isDebugEnabled())
    //log.debug("Reading element " + e.getTagName());

    for (int i = 0; i < reader.getAttributeCount(); i++) {
        Attr a = readAttribute(i, d, reader);
        if (a.getNamespaceURI() != null) {
            e.setAttributeNodeNS(a);
        } else {
            e.setAttributeNode(a);
        }
    }

    return e;
}

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
 *///from www .j  a va2 s .c om
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 ww .j a  va2s . 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 {//from  w w  w. ja va  2 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);
    }
}