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.mrgeo.resources.tms.TileMapServiceResource.java

protected static Document rootResourceXml(final String url) throws ParserConfigurationException {
    /*//from   w  w  w. j a  va2  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.openbravo.erpCommon.modules.ImportModule.java

/**
 * Adds a single classpath entry to the xml file
 *//*from   www .  j  a  v a2s.co m*/
private void addClassPathEntry(Document doc, String dir) throws Exception {
    log4j.info("adding entry for directory" + dir);
    final Node root = doc.getFirstChild();
    final Node classpath = doc.createElement("classpathentry");
    final NamedNodeMap cpAttributes = classpath.getAttributes();

    Attr attr = doc.createAttribute("kind");
    attr.setValue("src");
    cpAttributes.setNamedItem(attr);

    attr = doc.createAttribute("path");
    attr.setValue(dir);
    cpAttributes.setNamedItem(attr);

    root.appendChild(classpath);

}

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

private static Attr readAttribute(int i, Document d, XMLStreamReader reader) throws XMLStreamException {
    Attr a = null;/*www  .  ja  v a 2 s.  c  o m*/

    String local = reader.getAttributeLocalName(i);
    String ns = reader.getAttributeNamespace(i);
    if (ns != null) {
        String prefix = reader.getAttributePrefix(i);
        String qualified = prefix != null ? prefix + ":" + local : local;
        a = d.createAttributeNS(ns, qualified);
    } else {
        a = d.createAttribute(reader.getAttributeLocalName(i));
    }

    //if (log.isDebugEnabled())
    //log.debug("Reading attribute " + a.getName());

    a.setValue(reader.getAttributeValue(i));

    return a;
}

From source file:org.panlab.tgw.restclient.RepoAdapter.java

static String addSchemaDefinition(String response) {
    try {//  w  w  w.j  ava2s  .co  m
        ByteArrayInputStream bais = new ByteArrayInputStream(response.getBytes());
        DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = fact.newDocumentBuilder();
        Document doc = builder.parse(bais);

        Attr attr = doc.createAttribute("xmlns");
        attr.setValue("http://xml.netbeans.org/schema/repo.xsd");
        //attr.setValue("http://www.w3.org/2001/XMLSchema");
        doc.getDocumentElement().setAttributeNode(attr);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Result result = new StreamResult(baos);
        // Write the DOM document to the file
        doc.setXmlStandalone(false);
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        Source source = new DOMSource(doc);
        xformer.transform(source, result);

        response = new String(baos.toByteArray());
        return response;
    } catch (Exception error) {
        return null;
    }
}

From source file:org.regenstrief.util.XMLUtil.java

/**
 * Imports a Node into a Document without creating new prefixes like Document.importNode
 * /*  w w w  . j  a v a 2 s.c  om*/
 * @param doc the Document
 * @param toImport the Node to import
 * @return the imported Node
 **/
public final static Node importNode(final Document doc, final Node toImport) {
    Node imported;
    NodeList list;
    NamedNodeMap map;
    int i, size;

    if (toImport instanceof Element) {
        //imported = doc.createElement(((Element) toImport).getTagName()); // Ever want this?
        // This should copy toImport's prefix; I don't think that's what we want, but we don't have a namespace context for doc
        imported = doc.createElementNS(toImport.getNamespaceURI(), toImport.getNodeName());
        for (map = toImport.getAttributes(), size = size(map), i = 0; i < size; i++) {
            final Node n = map.item(i);
            if (n != null) {
                ((Element) imported).setAttributeNode((Attr) importNode(doc, n));
            }
        }
    } else if (toImport instanceof Attr) {
        final String uri = toImport.getNamespaceURI();
        if (Util.isEmpty(uri)) {
            imported = doc.createAttribute(
                    "xmlns".equals(getPrefix(toImport)) ? toImport.getNodeName() : getLocalName(toImport));
        } else {
            imported = doc.createAttributeNS(uri, toImport.getNodeName());
        }
        //imported.setNodeValue(toImport.getNodeValue()); // The value will be copied when we import children below
    } else {
        imported = doc.importNode(toImport, false);
    }
    for (list = toImport.getChildNodes(), size = size(list), i = 0; i < size; i++) {
        final Node n = list.item(i);
        if (n != null) {
            imported.appendChild(importNode(doc, n));
        }
    }

    return imported;
}

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

/**
 * {@inheritDoc}/*from ww  w . java2 s  .c o  m*/
 */
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>/*www  . ja  v  a  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.silverpeas.SilverpeasSettings.xml.transform.XPathTransformer.java

/**
 * Create a new node (element or attribute) to be inserted into the target node as a child or
 * attribute.//from   ww w. j a  v a  2  s .co m
 * @param doc DOM document
 * @param target the target ode
 * @param value the value for creating the new node.
 */
public void createNewNode(Document doc, Node target, Value value) {
    if (value.getLocation().startsWith("@")) {
        Attr newAttribute = doc.createAttribute(value.getLocation().substring(1));
        newAttribute.setValue(value.getValue());
        target.getAttributes().setNamedItem(newAttribute);
    } else {
        Element newElement = doc.createElement(value.getLocation());
        newElement.setTextContent(value.getValue());
        target.appendChild(newElement);
    }
}

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

/**
 * /*from   www .j a  v  a2 s  .co 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 Attr readAttribute(int i, Document d, XMLStreamReader reader) throws XMLStreamException {
    Attr a = null;//from   ww  w  . j  a v  a 2 s  .  c  om

    String local = reader.getAttributeLocalName(i);
    String ns = reader.getAttributeNamespace(i);
    if (ns != null && !ns.equals("")) {
        String prefix = reader.getAttributePrefix(i);
        String qualified = prefix != null ? prefix + ":" + local : local;
        a = d.createAttributeNS(ns, qualified);
    } else {
        a = d.createAttribute(reader.getAttributeLocalName(i));
    }

    //if (log.isDebugEnabled())
    //log.debug("Reading attribute " + a.getName());

    a.setValue(reader.getAttributeValue(i));

    return a;
}