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:net.sf.zekr.engine.bookmark.BookmarkSet.java

private void _updateXml(BookmarkItem item, Node node) {
    List<BookmarkItem> list = item.getChildren();
    for (BookmarkItem childItem : list) {
        if (childItem.isFolder()) {
            Element fe = xmlDocument.createElement("folder");
            fe.setAttribute("name", childItem.getName());
            fe.setAttribute("desc", childItem.getDescription());
            _updateXml(childItem, fe);//from   w w  w.  java  2s. c om
            node.appendChild(fe);
        } else {
            Element ie = xmlDocument.createElement("item");
            ie.setAttribute("name", childItem.getName());
            ie.setAttribute("desc", childItem.getDescription());
            ie.setAttribute("data", CollectionUtils.toString(childItem.getLocations(), ","));
            node.appendChild(ie);
        }
    }
}

From source file:com.photon.phresco.plugins.xcode.Instrumentation.java

private void generateXMLReport(String location) {

    try {// w w  w . j a v a2  s.  com
        String startTime = "";
        int total, pass, fail;
        total = pass = fail = 0;
        config = new XMLPropertyListConfiguration(location);
        ArrayList list = (ArrayList) config.getRoot().getChild(0).getValue();
        String key;

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();

        Element root = doc.createElement(XMLConstants.TESTSUITES_NAME);
        doc.appendChild(root);
        Element testSuite = doc.createElement(XMLConstants.TESTSUITE_NAME);
        testSuite.setAttribute(XMLConstants.NAME, "FunctionalTestSuite");
        root.appendChild(testSuite);

        for (Object object : list) {

            XMLPropertyListConfiguration config = (XMLPropertyListConfiguration) object;

            startTime = config.getRoot().getChild(2).getValue().toString();

            break;
        }

        for (Object object : list) {

            XMLPropertyListConfiguration config = (XMLPropertyListConfiguration) object;

            ConfigurationNode con = config.getRoot().getChild(0);
            key = con.getName();

            if (key.equals(XMLConstants.LOGTYPE) && con.getValue().equals(XMLConstants.PASS)) {
                pass++;
                total++;
                Element child1 = doc.createElement(XMLConstants.TESTCASE_NAME);
                child1.setAttribute(XMLConstants.NAME, (String) config.getRoot().getChild(1).getValue());
                child1.setAttribute(XMLConstants.RESULT, (String) con.getValue());

                String endTime = config.getRoot().getChild(2).getValue().toString();

                long differ = getTimeDiff(startTime, endTime);
                startTime = endTime;
                child1.setAttribute(XMLConstants.TIME, differ + "");
                testSuite.appendChild(child1);
            } else if (key.equals(XMLConstants.LOGTYPE) && con.getValue().equals(XMLConstants.ERROR)) {
                fail++;
                total++;
                Element child1 = doc.createElement(XMLConstants.TESTCASE_NAME);
                child1.setAttribute(XMLConstants.NAME, (String) config.getRoot().getChild(1).getValue());
                child1.setAttribute(XMLConstants.RESULT, (String) con.getValue());

                String endTime = config.getRoot().getChild(2).getValue().toString();

                long differ = getTimeDiff(startTime, endTime);
                startTime = endTime;
                child1.setAttribute(XMLConstants.TIME, differ + "");
                testSuite.appendChild(child1);
            }

        }

        testSuite.setAttribute(XMLConstants.TESTS, String.valueOf(total));
        testSuite.setAttribute(XMLConstants.SUCCESS, String.valueOf(pass));
        testSuite.setAttribute(XMLConstants.FAILURES, String.valueOf(fail));

        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.INDENT, "yes");

        File file = new File(project.getBasedir().getAbsolutePath() + File.separator + xmlResult);
        Writer bw = new BufferedWriter(new FileWriter(file));
        StreamResult result = new StreamResult(bw);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);

    } catch (Exception e) {
        getLog().error("Interrupted while generating XML file");
    }
}

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

private void getElements(final String protocol, final VFSPath dir, final Node root, final Document doc) {
    final Element files = doc.createElement(protocol + "s");
    root.appendChild(files);/*www  .  j a  v  a 2  s  .c o m*/
    VFSPathToken[] fileList;
    try {
        fileList = list(dir);
        ArrayList<String> sortedFileList = new ArrayList<String>();
        for (int i = 0; i < fileList.length; i++)
            sortedFileList.add(fileList[i].toString());

        Collections.sort(sortedFileList, new AlphanumericComparator());

        for (final String element : sortedFileList) {
            final VFSPath current = dir.child(new VFSPathToken(element));
            if ("Folder".equals(protocol) == vfs.isCollection(current)) {
                final Element myEl = doc.createElement(protocol);
                myEl.setAttribute("name", element);
                myEl.setAttribute("url", current.toString());

                if (protocol.equals("File"))
                    myEl.setAttribute("size", "" + vfs.getLength(current));

                files.appendChild(myEl);
            }
        }
    } catch (final Exception e) {
        TrivialExceptionHandler.ignore(this, e);
    }
}

From source file:fr.aliasource.webmail.server.proxy.client.http.AbstractMessageMethod.java

protected Document getMessageAsXML(ClientMessage m, SendParameters sp)
        throws ParserConfigurationException, FactoryConfigurationError {
    Document doc = DOMUtils.createDoc("http://obm.aliasource.fr/xsd/messages", "messages");
    Element root = doc.getDocumentElement();
    Element me = DOMUtils.createElement(root, "m");
    Date d = m.getDate();//from  w w  w. j a  va2  s .  co m
    if (d == null) {
        d = new Date();
    }
    me.setAttribute("date", "" + d.getTime());

    DOMUtils.createElementAndText(me, "subject", m.getSubject());

    if (m.getMessageId() != null) {
        DOMUtils.createElementAndText(me, "messageId", m.getMessageId().getConversationId());
    }
    Element from = DOMUtils.createElement(me, "from");
    from.setAttribute("addr", m.getSender().getEmail());
    from.setAttribute("displayName", m.getSender().getDisplay());

    Element recipients = DOMUtils.createElement(me, "to");
    List<EmailAddress> recip = m.getTo();
    addRecips(recipients, recip);
    recipients = DOMUtils.createElement(me, "cc");
    recip = m.getCc();
    addRecips(recipients, recip);
    recipients = DOMUtils.createElement(me, "bcc");
    recip = m.getBcc();
    addRecips(recipients, recip);

    Element attachements = DOMUtils.createElement(me, "attachements");
    String[] attachIds = m.getAttachments();
    for (String attach : attachIds) {
        Element ae = DOMUtils.createElement(attachements, "a");
        ae.setAttribute("id", attach);
    }

    Element body = DOMUtils.createElement(me, "body");
    body.setAttribute("type", "text/plain");

    if (sp.isSendPlainText() && m.getBody().getHtml() != null) {
        // we do this server side as firefox richtextarea::getText() seems
        // to drop carriage returns.
        body.setTextContent(new HTMLToPlainConverter().convert(m.getBody().getHtml()));
    } else {
        String plain = m.getBody().getPlain();
        StringBuilder sb = new StringBuilder();
        String[] lines = plain.split("\n");
        for (int i = 0; i < lines.length; i++) {
            if (lines[i].startsWith("> ")) {
                sb.append(lines[i]).append("\n");
            } else {
                sb.append(WordUtils.wrap(lines[i], 80)).append("\n");
            }
        }
        body.setTextContent(sb.toString());
    }

    if (!sp.isSendPlainText()) {
        if (m.getBody().getHtml() != null) {
            body = DOMUtils.createElementAndText(me, "body", m.getBody().getHtml());
            body.setAttribute("type", "text/html");
        }

        if (m.getBody().getCleanHtml() != null) {
            body = DOMUtils.createElementAndText(me, "body", m.getBody().getCleanHtml());
            body.setAttribute("type", "text/cleanHtml");
        }

        if (m.getBody().getPartialCleanHtml() != null) {
            body = DOMUtils.createElementAndText(me, "body", m.getBody().getPartialCleanHtml());
            body.setAttribute("type", "text/partialCleanHtml");
        }
    }

    return doc;
}

From source file:com.seajas.search.attender.service.template.TemplateService.java

/**
 * Create a results template result.//w  w w  .  j  a v a  2 s.com
 * 
 * @param language
 * @param queryString
 * @param query
 * @param uuid
 * @param searchResults
 * @return TemplateResult
 */
public TemplateResult createResults(final String language, final String queryString, final String query,
        final String subscriberUUID, final String profileUUID, final List<SearchResult> searchResults)
        throws ScriptException {
    Template template = templateDAO.findTemplate(TemplateType.Results, language);

    if (template == null) {
        logger.warn("Could not retrieve results template for language " + language
                + " - falling back to default language " + attenderService.getDefaultApplicationLanguage());

        template = templateDAO.findTemplate(TemplateType.Confirmation,
                attenderService.getDefaultApplicationLanguage());

        if (template == null) {
            logger.error("Could not retrieve fall-back results template for language "
                    + attenderService.getDefaultApplicationLanguage() + " - not generating a template result");

            return null;
        }
    }

    // Create an input document

    Document document;

    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

        documentBuilderFactory.setCoalescing(true);
        documentBuilderFactory.setNamespaceAware(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        document = documentBuilder.newDocument();

        Element results = document.createElement("results");

        results.setAttribute("templateLanguage", language);
        results.setAttribute("profileQuery", query);
        results.setAttribute("subscriberUUID", subscriberUUID);
        results.setAttribute("profileUUID", profileUUID);
        results.setAttribute("queryString", queryString);

        for (SearchResult searchResult : searchResults)
            results.appendChild(searchResult.toElement(document));

        document.appendChild(results);

        // Plain text

        Transformer textTransformer = getTransformer(template, true);
        StringWriter textWriter = new StringWriter();

        textTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
        textTransformer.transform(new DOMSource(document), new StreamResult(textWriter));

        // HTML

        Transformer htmlTransformer = getTransformer(template, false);
        StringWriter htmlWriter = new StringWriter();

        htmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");
        htmlTransformer.transform(new DOMSource(document), new StreamResult(htmlWriter));

        return new TemplateResult(textWriter.toString(), htmlWriter.toString());
    } catch (ScriptException e) {
        throw e;
    } catch (Exception e) {
        throw new ScriptException(e);
    }
}

From source file:com.icesoft.faces.component.style.OutputStyleRenderer.java

public void encodeEnd(FacesContext facesContext, UIComponent uiComponent) throws IOException {
    validateParameters(facesContext, uiComponent, OutputStyle.class);
    try {//from ww w. j a  va  2 s . c  o  m
        DOMContext domContext = DOMContext.attachDOMContext(facesContext, uiComponent);
        if (!domContext.isInitialized()) {
            OutputStyle outputStyle = (OutputStyle) uiComponent;
            Element styleEle = buildCssElement(domContext);
            String href = outputStyle.getHref();
            styleEle.setAttribute(HTML.HREF_ATTR, getResourceURL(facesContext, href));
            domContext.setRootNode(styleEle);
            int browserType = browserType(facesContext, uiComponent);
            if (browserType != DEFAULT_TYPE) {
                if (href.endsWith(CSS_EXTENTION)) {
                    int i = href.indexOf(CSS_EXTENTION);
                    if (i > 0) {
                        String start = href.substring(0, i);
                        Element ieStyleEle = buildCssElement(domContext);
                        String extention = IE_EXTENTION;
                        if (browserType == SAFARI) {
                            extention = SAFARI_EXTENTION;
                        }
                        if (browserType == DT) {
                            extention = DT_EXTENTION;
                        }
                        if (browserType == IE_7) {
                            extention = IE_7_EXTENTION;
                        }
                        if (browserType == IE_8) {
                            extention = IE_8_EXTENSION;
                        }
                        if (browserType == SAFARI_MOBILE) {
                            extention = SAFARI_MOBILE_EXTENTION;
                        }
                        if (browserType == OPERA) {
                            extention = OPERA_EXTENTION;
                        }
                        if (browserType == OPERA_MOBILE) {
                            extention = OPERA_MOBILE_EXTENTION;
                        }
                        String browserSpecificFilename = useSpecific(facesContext, start, extention);
                        if (browserSpecificFilename != null) {
                            // W3C spec: To make a style sheet preferred, set the rel attribute to "stylesheet" and name the style sheet with the title attribute
                            ieStyleEle.setAttribute(HTML.TITLE_ATTR, extention);
                            String hrefURL = CoreUtils.resolveResourceURL(facesContext,
                                    browserSpecificFilename);
                            ieStyleEle.setAttribute(HTML.HREF_ATTR, hrefURL);
                            styleEle.getParentNode().appendChild(ieStyleEle);
                        }
                    } else {
                        throw new RuntimeException("OutputStyle file attribute is too short. "
                                + "Needs at least one character before .css. Current Value is [" + href + "]");
                    }
                } else {
                    Matcher matcher = Pattern
                            .compile(".*javax\\.faces\\.resource/((.*)\\.css)(\\..*)?\\?ln=([^&]*)(&.*|$)")
                            .matcher(href);
                    if (matcher.matches()) {
                        Element ieStyleEle = buildCssElement(domContext);
                        String extension = browserType >= 0 && browserType < extensions.length
                                ? extensions[browserType]
                                : IE_EXTENTION;
                        ieStyleEle.setAttribute(HTML.TITLE_ATTR, extension);
                        String hrefURL = new StringBuffer(matcher.group(0)).insert(matcher.end(2), extension)
                                .toString();
                        ieStyleEle.setAttribute(HTML.HREF_ATTR, hrefURL);
                        String resourceName = new StringBuffer(matcher.group(1))
                                .insert(matcher.end(2) - matcher.start(2), extension).toString();
                        Resource resource = facesContext.getApplication().getResourceHandler()
                                .createResource(resourceName, matcher.group(4));
                        if (resource != null) {
                            styleEle.getParentNode().appendChild(ieStyleEle);
                        }
                    }
                }
            }

        }
        domContext.stepOver();
    } catch (Exception e) {
        log.error("Error in OutputStyleRenderer", e);
    }
}

From source file:com.wavemaker.tools.project.LocalDeploymentManager.java

private void updateTomcatDeployConfig(Map<String, Object> properties) {
    LocalFolder projectDir = (LocalFolder) properties.get(PROJECT_DIR_PROPERTY);
    String deployName = (String) properties.get(DEPLOY_NAME_PROPERTY);
    LocalFile tomcatConfigXml = (LocalFile) projectDir.getFile(deployName + ".xml");
    if (tomcatConfigXml.exists()) {
        tomcatConfigXml.delete();//from  w w w  .j  a  va2  s .  c o  m
    }
    tomcatConfigXml.createIfMissing();
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();

        NodeList nodeList = doc.getElementsByTagName("Context");

        if (nodeList != null && nodeList.getLength() > 0) {
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getParentNode() != null) {
                    node.getParentNode().removeChild(node);
                }
            }
        }

        Element context = doc.createElement("Context");
        context.setAttribute("antiJARLocking", "true'");
        context.setAttribute("antiResourceLocking", "false");
        context.setAttribute("privileged", "true");
        String docBase = ((LocalFolder) properties.get(BUILD_WEBAPPROOT_PROPERTY)).getLocalFile()
                .getAbsolutePath();
        context.setAttribute("docBase", docBase);

        doc.appendChild(context);

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer tFormer = tFactory.newTransformer();

        Source source = new DOMSource(doc);
        Result dest = new StreamResult(tomcatConfigXml.getLocalFile());
        tFormer.transform(source, dest);

    } catch (Exception e) {
        throw new WMRuntimeException(e);
    }
}

From source file:es.bsc.servicess.ide.actions.DeployAction.java

private void addLocalhostToProjectFile(IJavaProject pr, String coreLocation)
        throws ConfigurationException, SAXException, IOException, CoreException, ParserConfigurationException,
        TransformerFactoryConfigurationError, TransformerException {
    /*//from   w  ww  .j a  va2  s . c  om
     * <Worker Name="enric2"> <InstallDir>/IT_worker/</InstallDir>
     * <WorkingDir>/home/user/</WorkingDir> <User>user</User>
     * <LimitOfTasks>1</LimitOfTasks> </Worker>
     */
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(getProjectFileLocation(pr));

    Element project = doc.getDocumentElement();
    Element worker = doc.createElement("Worker");
    worker.setAttribute("Name", "localhost");
    Element installDir = doc.createElement("InstallDir");
    installDir.setNodeValue(coreLocation);
    worker.appendChild(installDir);
    Element workingDir = doc.createElement("WorkingDir");
    workingDir.setNodeValue(coreLocation);
    worker.appendChild(workingDir);
    Element user = doc.createElement("User");
    user.setNodeValue(System.getProperty("user.name"));
    worker.appendChild(user);
    Element limit = doc.createElement("LimitOfTasks");
    limit.setNodeValue("2");
    worker.appendChild(limit);
    project.appendChild(project);
    Source source = new DOMSource(doc);
    IFolder output = pr.getProject().getFolder("output");
    if (output != null && output.exists()) {
        IFolder war_folder = output.getFolder(pr.getProject().getName());
        // Prepare the output file
        File file = (war_folder.getFile("project.xml").getLocation().toFile());
        Result result = new StreamResult(file);

        // Write the DOM document to the file
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        xformer.transform(source, result);
    }

}

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

private void formatBody(MailMessage m, Element me) {
    for (String format : m.getBody().availableFormats()) {
        Element body = DOMUtils.createElementAndText(me, "body", m.getBody().getValue(format));
        body.setAttribute("type", format);
    }/*from w  w w  .  ja v  a 2 s. c  om*/
}

From source file:com.bstek.dorado.idesupport.resolver.RobotResolver.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    DoradoContext context = DoradoContext.getCurrent();
    Document document = null;//from   w w  w.j a  v  a2 s  . com
    List<Element> resultElements = null;
    Exception error = null;

    String robotName = getRobotName(request);
    Assert.notEmpty(robotName, "\"robotName\" undefined.");

    Robot robot = robotRegistry.getRobot(robotName);
    if (robot == null) {
        throw new IllegalArgumentException("Unknown robotName \"" + robotName + "\".");
    }

    ServletInputStream in = request.getInputStream();
    try {
        String charset = request.getCharacterEncoding();
        document = getXmlDocumentBuilder(context)
                .loadDocument(new InputStreamResource(in, request.getRequestURI()), charset);
    } catch (Exception e) {
        logger.error(e, e);
        error = e;
    } finally {
        in.close();
    }

    Element documentElement = document.getDocumentElement();

    Element contentElement = DomUtils.getChildByTagName(documentElement, "Content");
    List<Element> elements = DomUtils.getChildElements(contentElement);

    Properties properties = null;
    Element propertiesElement = DomUtils.getChildByTagName(documentElement, "Properties");
    if (propertiesElement != null) {
        List<Element> propertieElements = DomUtils.getChildElements(propertiesElement);
        if (!propertieElements.isEmpty()) {
            properties = new Properties();
            for (Element propertyElement : propertieElements) {
                properties.setProperty(propertyElement.getAttribute("name"),
                        DomUtils.getTextContent(propertyElement));
            }
        }
    }

    resultElements = new ArrayList<Element>();
    for (Element element : elements) {
        resultElements.add((Element) robot.execute(element, properties));
    }

    // Output
    document = getXmlDocumentBuilder(context).newDocument();
    Element responseElement = document.createElement("Response");
    document.appendChild(responseElement);
    if (error == null) {
        assembleContent(document, responseElement, resultElements);
    } else {
        responseElement.setAttribute("failed", "true");
        assembleError(document, responseElement, error);
    }

    PrintWriter writer = null;
    TransformerFactory transFactory = TransformerFactory.newInstance();
    try {
        Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty("encoding", Constants.DEFAULT_CHARSET);
        transformer.setOutputProperty("indent", "yes");

        DOMSource source = new DOMSource(document);
        writer = getWriter(request, response);
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
    } finally {
        if (writer != null) {
            writer.flush();
            writer.close();
        }
    }
}