Example usage for org.w3c.dom Element setAttribute

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

Introduction

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

Prototype

public void setAttribute(String name, String value) throws DOMException;

Source Link

Document

Adds a new attribute.

Usage

From source file:it.unibas.spicy.persistence.xml.operators.ExportXSD.java

private void checkOccurs(INode node, Element elementTag) {
    if (node.isRoot()) {
        return;/* w w w.  j  av a 2s.c  o m*/
    }

    if (node.isRequired()) {
        elementTag.setAttribute("minOccurs", "1");
    } else if (!node.isRequired()) {
        elementTag.setAttribute("minOccurs", "0");
    }
    if (node.isNotNull()) {
        elementTag.setAttribute("nillable", "false");
    } else {
        elementTag.setAttribute("nillable", "true");
    }
}

From source file:mil.dod.th.ose.junit4xmltestrunner.ant.XMLJUnitResultFormatter.java

/**
 * The whole test suite started.//from  w w  w.j a v a2s  .co m
 */
public void startTestSuite(final String name) // NOCHECKSTYLE: no documentation, file modified from 3rd party
{
    m_Doc = getDocumentBuilder().newDocument();
    m_RootElement = m_Doc.createElement(TESTSUITE);
    m_RootElement.setAttribute(ATTR_NAME, name);

    //add the timestamp
    final String timestamp = DateUtils.format(new Date(), DateUtils.ISO8601_DATETIME_PATTERN);
    m_RootElement.setAttribute(TIMESTAMP, timestamp);
    //and the hostname.
    m_RootElement.setAttribute(HOSTNAME, getHostname());

    // Output properties
    final Element propsElement = m_Doc.createElement(PROPERTIES);
    m_RootElement.appendChild(propsElement);
    final Properties props = System.getProperties();
    if (props != null) {
        final Enumeration<?> e = props.propertyNames();
        while (e.hasMoreElements()) {
            final String propName = (String) e.nextElement();
            final Element propElement = m_Doc.createElement(PROPERTY);
            propElement.setAttribute(ATTR_NAME, propName);
            propElement.setAttribute(ATTR_VALUE, props.getProperty(propName));
            propsElement.appendChild(propElement);
        }
    }

    m_OldStdOut = System.out;
    System.setOut(new PrintStream(m_TeeOutStream));
    m_OldStdErr = System.err;
    System.setErr(new PrintStream(m_TeeErrStream));
}

From source file:net.sourceforge.eclipsetrader.ats.Repository.java

void saveStrategy(Strategy obj, Document document, Element root) {
    Element element = document.createElement("strategy");
    element.setAttribute("id", String.valueOf(obj.getId()));
    if (obj.getPluginId() != null)
        element.setAttribute("pluginId", obj.getPluginId());
    element.setAttribute("autostart", obj.isAutoStart() ? "true" : "false");
    root.appendChild(element);//w  ww .j a  va  2  s  .co m

    if (obj.getName() != null) {
        Element node = document.createElement("name");
        node.appendChild(document.createTextNode(obj.getName()));
        element.appendChild(node);
    }

    if (obj.getMarketManager() != null) {
        Element node = document.createElement("marketManager");
        saveComponent(obj.getMarketManager(), document, node);
        element.appendChild(node);
    }
    if (obj.getEntry() != null) {
        Element node = document.createElement("entry");
        saveComponent(obj.getEntry(), document, node);
        element.appendChild(node);
    }
    if (obj.getExit() != null) {
        Element node = document.createElement("exit");
        saveComponent(obj.getExit(), document, node);
        element.appendChild(node);
    }
    if (obj.getMoneyManager() != null) {
        Element node = document.createElement("moneyManager");
        saveComponent(obj.getMoneyManager(), document, node);
        element.appendChild(node);
    }

    for (Iterator iter = obj.getSecurities().iterator(); iter.hasNext();) {
        Element node = document.createElement("security");
        node.setAttribute("id", String.valueOf(((Security) iter.next()).getId()));
        element.appendChild(node);
    }

    for (Iterator paramIter = obj.getParams().keySet().iterator(); paramIter.hasNext();) {
        String key = (String) paramIter.next();
        Element node = document.createElement("param");
        node.setAttribute("key", key);
        node.setAttribute("value", (String) obj.getParams().get(key));
        element.appendChild(node);
    }
}

From source file:net.ion.radon.impl.let.webdav.FCKConnectorRestlet.java

protected void handleGet(final Request request, final Response response) {
    final Form parameters = request.getResourceRef().getQueryAsForm();
    final String commandStr = parameters.getValues("Command");
    final String typeStr = parameters.getValues("Type");
    final VFSPath currentFolderStr;
    try {// w  w w . ja va2  s.co  m
        currentFolderStr = VFSUtils.parseVFSPath(parameters.getValues("CurrentFolder"));
    } catch (VFSUtils.VFSPathParseException e) {
        return;
    }

    final Document document = newDocument();

    final Node root = createCommonXML(document, commandStr, typeStr, parameters.getValues("CurrentFolder"),
            parameters.getValues("CurrentFolder"));

    if (commandStr.equalsIgnoreCase("GetFolders")) {
        getFolders(currentFolderStr.toString(), root, document);
    } else if (commandStr.equalsIgnoreCase("GetFoldersAndFiles")) {
        getFolders(currentFolderStr.toString(), root, document);
        getFiles(currentFolderStr.toString(), root, document);
    } else if (commandStr.equalsIgnoreCase("CreateFolder")) {
        final String newFolderStr = parameters.getValues("NewFolderName");
        String retValue = "110";
        if (vfs.exists(currentFolderStr.child(new VFSPathToken(newFolderStr)))) {
            retValue = "101";
        } else {
            try {
                vfs.makeCollection(currentFolderStr.child(new VFSPathToken(newFolderStr)));
                retValue = "0";
            } catch (final Exception e) {
                retValue = "102";
            }
        }
        final Element myEl = document.createElement("Error");
        myEl.setAttribute("number", retValue);
        root.appendChild(myEl);
    }

    response.setStatus(Status.SUCCESS_OK);
    Form headers = (Form) response.getAttributes().get("org.restlet.http.headers");
    if (headers == null) {
        headers = new Form();
        response.getAttributes().put("org.restlet.http.headers", headers);
    }
    headers.add("Content-type", "text/xml; charset=UTF-8");
    headers.add("Cache-control", "no-cache");

    response.setEntity(new DomRepresentation(MediaType.TEXT_XML, document));
}

From source file:org.opentraces.metatracker.net.OpenTracesClient.java

/**
 * perform TWorx multi-service request.//from  w w w. ja v a  2s .c om
 */
synchronized public List<Element> service(List<Element> requests, boolean stopOnError) throws ClientException {
    // We don't need a valid session as one of the requests
    // may be a login or create-session request.

    // Create multi-req request with individual requests as children
    Element request = createRequest(SERVICE_MULTI_REQ);
    request.setAttribute(ATTR_STOPONERROR, stopOnError + "");

    for (Element req : requests) {
        request.appendChild(req);
    }

    // Execute request
    Element response = doRequest(request);

    // Check for session timeout
    response = redoRequestOnSessionTimeout(request, response);

    // Throw exception on negative response
    throwOnNrsp(response);

    // Filter child responses for session-based responses
    NodeList responseList = response.getChildNodes();
    List<Element> responses = new ArrayList(responseList.getLength());

    for (int i = 0; i < responseList.getLength(); i++) {
        handleResponse(requests.get(i), (Element) responseList.item(i));
        responses.add((Element) responseList.item(i));
    }

    // Positive multi-req response: return child responses
    return responses;
}

From source file:de.fhg.iais.asc.xslt.binaries.DownloadAndScale.java

private void addBinaryNodeWithPath(List<Node> result, Node inputNode, Object variant, String subPath,
        String mimeType) {/*from   w w  w.  ja v  a 2  s  .c om*/
    final Element binaryElement = this.targetDoc.createElement("binary");
    copyAttributes(inputNode, binaryElement, ATTRNAMES_COPY_TO_RESULT);

    if (variant instanceof URI) {
        binaryElement.setAttribute(ATTRNAME_PATH, variant.toString());
    } else {
        String resultPath = this.parameters.get(PARAMNAME_RESULT_PATH);
        if (StringUtils.isNotEmpty(resultPath)) {
            binaryElement.setAttribute(PARAMNAME_RESULT_PATH, resultPath);
        }

        binaryElement.setAttribute(ATTRNAME_LOCAL_PATHNAME, (String) variant);

        if (mimeType.startsWith("video/") || mimeType.startsWith("audio/")) { //  Todo Test anpassen
            binaryElement.setAttribute(ATTRNAME_CATEGORY, "full");
        }

        if (!mimeType.equals("video/vimeo")) {
            String prefix = FilenameUtils.removeExtension((String) variant)
                    .replace(FilenameUtils.removeExtension(subPath), "");
            binaryElement.setAttribute(ATTRNAME_PATH,
                    prefix + binaryElement.getAttribute(ATTRNAME_POSITION) + getExtension((String) variant));

            if (mimeType.startsWith("image/") || mimeType.equals("application/pdf")) { //  ToDo Test anpassen

                binaryElement.setAttribute(ATTRNAME_CATEGORY, prefix.replace("/", ""));
            }

        } else {
            binaryElement.setAttribute(ATTRNAME_PATH, (String) variant);
        }
    }

    binaryElement.setAttribute(ATTRNAME_MIMETYPE, mimeType);

    //  binaryElement.setAttribute(ATTRNAME_FULL, full);

    result.add(binaryElement);
}

From source file:net.sourceforge.eclipsetrader.ats.Repository.java

public void save() {
    try {// ww w .j  ava  2 s .c o  m
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        builder.setErrorHandler(errorHandler);
        Document document = builder.getDOMImplementation().createDocument(null, "data", null);

        Element root = document.getDocumentElement();
        root.setAttribute("nextId", String.valueOf(nextId));

        for (Iterator iter = systems.iterator(); iter.hasNext();) {
            TradingSystem system = (TradingSystem) iter.next();

            Element element = document.createElement("system");
            element.setAttribute("id", String.valueOf(system.getId()));

            Element node = document.createElement("name");
            node.appendChild(document.createTextNode(system.getName()));
            element.appendChild(node);

            if (system.getAccount().getId() != null) {
                node = document.createElement("account");
                node.appendChild(document.createTextNode(String.valueOf(system.getAccount().getId())));
                element.appendChild(node);
            }

            node = document.createElement("tradingProvider");
            node.appendChild(document.createTextNode(system.getTradingProviderId()));
            element.appendChild(node);

            if (system.getMoneyManager() != null) {
                node = document.createElement("moneyManager");
                saveComponent(system.getMoneyManager(), document, node);
                element.appendChild(node);
            }

            for (Iterator paramIter = system.getParams().keySet().iterator(); paramIter.hasNext();) {
                String key = (String) paramIter.next();
                node = document.createElement("param");
                node.setAttribute("key", key);
                node.setAttribute("value", (String) system.getParams().get(key));
                element.appendChild(node);
            }

            for (Iterator iter2 = system.getStrategies().iterator(); iter2.hasNext();)
                saveStrategy((Strategy) iter2.next(), document, element);

            root.appendChild(element);
        }

        saveDocument(document, "", "systems.xml");

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
}

From source file:fr.aliasource.webmail.proxy.impl.ResponderImpl.java

private void appendConversation(Element root, ConversationReference cr) {
    Element ce = DOMUtils.createElement(root, "cr");
    ce.setAttribute("id", cr.getId());
    ce.setAttribute("lastMessageDate", "" + cr.getLastMessageDate());
    ce.setAttribute("folder", cr.getSourceFolder());
    ce.setAttribute("read", "" + cr.isRead());
    ce.setAttribute("attach", "" + cr.isWithAttachments());
    ce.setAttribute("invitation", "" + cr.isWithInvitation());
    ce.setAttribute("star", "" + cr.isStarred());
    ce.setAttribute("answer", "" + cr.isAnswered());
    ce.setAttribute("hp", "" + cr.isHighPriority());

    if (cr.getPrev() != null) {
        ce.setAttribute("prev", cr.getPrev());
    }//from w w w. j  a v a 2 s .  c  o  m
    if (cr.getNext() != null) {
        ce.setAttribute("next", cr.getNext());
    }

    if (cr.getTitle() != null) {
        DOMUtils.createElementAndText(ce, "title", cr.getTitle());
    } else {
        DOMUtils.createElementAndText(ce, "title", "[No conversation topic]");
        if (logger.isDebugEnabled()) {
            logger.debug("Invalid conversation title for messages : ");
            for (MessageId mid : cr.getMessageIds()) {
                logger.debug("    * uid: " + mid.getImapId() + " has an invalid title (" + cr.getSourceFolder()
                        + ")");
            }
        }
    }

    Element ps = DOMUtils.createElement(ce, "participants");
    for (Address a : cr.getParticipants()) {
        if (a != null && a.getMail() != null) {
            Element p = DOMUtils.createElement(ps, "p");
            String ma = StringUtils.stripAddressForbiddenChars(a.getMail());
            if (a.getDisplayName() != null) {
                p.setAttribute("displayName", a.getDisplayName());
            } else {
                p.setAttribute("displayName", ma);
            }
            p.setAttribute("addr", ma);
        }
    }

    Element mids = DOMUtils.createElement(ce, "mids");
    for (MessageId id : cr.getMessageIds()) {
        Element m = DOMUtils.createElement(mids, "m");
        m.setAttribute("id", "" + id.getImapId());
    }

    Element metas = DOMUtils.createElement(ce, "metas");
    for (String mKey : cr.getMetadata().keySet()) {
        String val = cr.getMetadata().get(mKey);
        if (val != null) {
            Element m = DOMUtils.createElementAndText(metas, "meta", val);
            m.setAttribute("type", mKey);
        }
    }
}

From source file:marytts.tools.voiceimport.AllophonesExtractor.java

/**
 * /*w ww  .j  a  v a 2  s .  co m*/
 * @param basename
 * @throws IOException
 */
public void generateAllophonesFile(String basename) throws IOException, MaryConfigurationException {
    Locale localVoice = MaryUtils.string2locale(locale);
    String xmlLocale = MaryUtils.locale2xmllang(localVoice);
    String inputDir = db.getProp(db.TEXTDIR);
    String outputDir = promptAllophonesDir.getAbsolutePath();
    String fullFileName = inputDir + File.separator + basename + db.getProp(db.TEXTEXT);

    // this string controls whether style attributes are inserted into the prompt_allophones ("" -> disabled):
    String style = "";
    if (styleDefinition != null) {
        style = getStyleFromStyleDefinition(basename);
    }

    File textFile = new File(fullFileName);
    String text = FileUtils.readFileToString(textFile, "UTF-8");

    // First, test if there is a corresponding .rawmaryxml file in textdir:
    File rawmaryxmlFile = new File(
            db.getProp(db.MARYXMLDIR) + File.separator + basename + db.getProp(db.MARYXMLEXT));
    if (rawmaryxmlFile.exists()) {
        if (style.isEmpty()) {
            // just pass through the raw file:
            text = FileUtils.readFileToString(rawmaryxmlFile, "UTF-8");
        } else {
            // parse the .rawmaryxml file:
            Document document = null;
            try {
                document = DomUtils.parseDocument(rawmaryxmlFile);
            } catch (Exception e) {
                throw new IOException("Error parsing RAWMARYXML file: " + rawmaryxmlFile.getName(), e);
            }

            // get the <maryxml> node:
            Node maryXmlNode = document.getDocumentElement();
            Node firstMaryXmlChild = maryXmlNode.getFirstChild();
            Node lastMaryXmlChild = maryXmlNode.getLastChild();
            // wrap the <maryxml>'s content in new <prosody> element...
            Element topLevelProsody = DomUtils.encloseNodesWithNewElement(firstMaryXmlChild, lastMaryXmlChild,
                    MaryXML.PROSODY);
            // ...and set its style attribute:
            topLevelProsody.setAttribute("style", style);

            // convert the document to the text string: 
            text = DomUtils.document2String(document);
        }
    } else {
        String prosodyOpeningTag = "";
        String prosodyClosingTag = "";
        if (!style.isEmpty()) {
            prosodyOpeningTag = String.format("<%s style=\"%s\">\n", MaryXML.PROSODY, style);
            prosodyClosingTag = String.format("</%s>\n", MaryXML.PROSODY);
        }
        text = getMaryXMLHeaderWithInitialBoundary(xmlLocale) + prosodyOpeningTag + text + prosodyClosingTag
                + "</maryxml>";
    }

    OutputStream os = new BufferedOutputStream(new FileOutputStream(new File(outputDir, basename + featsExt)));
    MaryHttpClient maryClient = getMaryClient();
    maryClient.process(text, maryInputType, maryOutputType, db.getProp(db.LOCALE), null, null, os);
    os.flush();
    os.close();
}

From source file:Main.java

private static Node copyNodeExceptNamespace(Document document, Node srcNode, Set<String> namespace,
        List<String> exceptNamespaces) {

    if (srcNode.getNodeType() == Node.ELEMENT_NODE) {

        String nodeName = srcNode.getNodeName();
        nodeName = nodeName.substring(nodeName.indexOf(":") + 1);
        Element element = document.createElement(nodeName);

        for (int i = 0; i < srcNode.getAttributes().getLength(); i++) {
            Attr attr = (Attr) srcNode.getAttributes().item(i);
            String name = attr.getName();
            if (name.startsWith("xmlns:")) {
                String suffix = name.substring(6);
                if (!exceptNamespaces.contains(suffix)) {
                    namespace.add(suffix);
                }/*w  ww .ja  va2 s.  c  o  m*/
                continue;
            }
        }

        for (int i = 0; i < srcNode.getAttributes().getLength(); i++) {
            Attr attr = (Attr) srcNode.getAttributes().item(i);
            String name = attr.getName();
            if (name.startsWith("xmlns:")) {
                continue;
            }
            int semi = name.indexOf(":");
            if (semi > 0) {
                if (namespace.contains(name.substring(0, semi))) {
                    name = name.substring(semi + 1);
                }
            }
            element.setAttribute(name, attr.getValue());
        }

        NodeList nodeList = srcNode.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node childNode = nodeList.item(i);
            if (childNode.getNodeType() == Node.TEXT_NODE) {
                element.appendChild(document.createTextNode(childNode.getTextContent()));
            } else if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                Node node = copyNodeExceptNamespace(document, childNode, namespace, exceptNamespaces);
                element.appendChild(node);
            }
        }

        return element;
    }

    if (srcNode.getNodeType() == Node.TEXT_NODE) {
        Text text = document.createTextNode(srcNode.getTextContent());
        return text;
    }

    return null;
}