Example usage for org.w3c.dom Element toString

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

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.dita.dost.reader.ChunkMapReader.java

/**
 * Generate stump topic for to-content content.
 * @param topicref topicref without href to generate stump topic for
 *//*from  w  ww.j av a 2s  .c  om*/
private void generateStumpTopic(final Element topicref) {
    logger.info("generateStumpTopic: " + topicref.toString());
    final URI copytoValue = toURI(getValue(topicref, ATTRIBUTE_NAME_COPY_TO));
    final String idValue = getValue(topicref, ATTRIBUTE_NAME_ID);

    File outputFileName;
    if (copytoValue != null) {
        outputFileName = resolve(fileDir, copytoValue.toString());
    } else if (idValue != null) {
        outputFileName = resolve(fileDir, idValue + FILE_EXTENSION_DITA);
    } else {
        do {
            outputFileName = resolve(fileDir, generateFilename());
        } while (outputFileName.exists());
    }

    final String id = getBaseName(outputFileName.getName());
    String navtitleValue = getChildElementValueOfTopicmeta(topicref, TOPIC_NAVTITLE);
    if (navtitleValue == null) {
        navtitleValue = getValue(topicref, ATTRIBUTE_NAME_NAVTITLE);
    }
    if (navtitleValue == null) {
        navtitleValue = id;
    }
    final String shortDescValue = getChildElementValueOfTopicmeta(topicref, MAP_SHORTDESC);

    OutputStream output = null;
    try {
        output = new FileOutputStream(outputFileName);
        final XMLSerializer serializer = XMLSerializer.newInstance(output);
        serializer.writeStartDocument();
        serializer.writeStartElement(TOPIC_TOPIC.localName);
        serializer.writeAttribute(DITA_NAMESPACE,
                ATTRIBUTE_PREFIX_DITAARCHVERSION + ":" + ATTRIBUTE_NAME_DITAARCHVERSION, "1.2");
        serializer.writeAttribute(ATTRIBUTE_NAME_ID, id);
        serializer.writeAttribute(ATTRIBUTE_NAME_CLASS, TOPIC_TOPIC.toString());
        serializer.writeAttribute(ATTRIBUTE_NAME_DOMAINS, "");
        serializer.writeStartElement(TOPIC_TITLE.localName);
        serializer.writeAttribute(ATTRIBUTE_NAME_CLASS, TOPIC_TITLE.toString());
        serializer.writeCharacters(navtitleValue);
        serializer.writeEndElement(); // title
        if (shortDescValue != null) {
            serializer.writeStartElement(TOPIC_SHORTDESC.localName);
            serializer.writeAttribute(ATTRIBUTE_NAME_CLASS, TOPIC_SHORTDESC.toString());
            serializer.writeCharacters(shortDescValue);
            serializer.writeEndElement(); // shortdesc
        }
        serializer.writeEndElement(); // topic
        serializer.writeEndDocument();
        serializer.close();
    } catch (final IOException | SAXException e) {
        logger.error("Failed to write generated chunk: " + e.getMessage(), e);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                logger.error("Failed to close output stream: " + e.getMessage(), e);
            }
        }
    }

    // update current element's @href value
    final URI relativePath = toURI(getRelativePath(new File(fileDir, FILE_NAME_STUB_DITAMAP), outputFileName));
    topicref.setAttribute(ATTRIBUTE_NAME_HREF, relativePath.toString());

    final URI relativeToBase = URLUtils.getRelativePath(job.tempDir.toURI().resolve("dummy"),
            outputFileName.toURI());
    job.add(new Job.FileInfo.Builder().uri(relativeToBase).format(ATTR_FORMAT_VALUE_DITA).build());
}

From source file:org.etudes.component.app.melete.MeleteSecurityServiceImpl.java

/**
 * {@inheritDoc}//from  www.ja  v a  2  s .co m
 */
public String merge(String siteId, Element root, String archivePath, String fromSiteId, Map attachmentNames,
        Map userIdTrans, Set userListAllowImport) {
    logger.debug("merge of melete" + siteId + "," + fromSiteId + "," + root.toString());
    int count = 0;
    try {
        org.w3c.dom.Document w3doc = Xml.createDocument();
        org.w3c.dom.Element w3root = (org.w3c.dom.Element) w3doc.importNode(root, true);
        w3doc.appendChild(w3root);

        //convert to dom4j doc
        org.dom4j.io.DOMReader domReader = new org.dom4j.io.DOMReader();
        org.dom4j.Document domDoc = domReader.read(w3doc);
        logger.debug("archive str " + archivePath + archivePath.lastIndexOf(File.separator));
        archivePath = archivePath.substring(0, archivePath.lastIndexOf("/"));
        count = getMeleteImportService().mergeAndBuildModules(domDoc, archivePath, siteId);
    } catch (Exception e) {
        e.printStackTrace();
        return "error on merging modules content";
    }
    return "merging modules content: (" + count + ") modules \n";
}

From source file:org.etudes.mneme.impl.ImportQtiServiceImpl.java

/**
 * Find all the items from the root using the path, and combine their text content.
 * /* w  w  w  .j a va 2 s  . c  o  m*/
 * @param path
 *        The XPath
 * @param root
 *        The Document or Element root
 * @return The combined values for these hits.
 */
protected String combineHits(XPath path, Object root) {
    StringBuilder rv = new StringBuilder();
    try {
        List hits = path.selectNodes(root);
        for (Object o : hits) {
            Element e = (Element) o;
            String value = StringUtil.trimToNull(e.getTextContent());
            if (value != null) {
                if (rv.length() > 0) {
                    rv.append("/n");
                }
                rv.append(value);
            }
        }
    } catch (JaxenException e) {
        System.out.println(e.toString());
    }

    if (rv.length() == 0)
        return null;
    return rv.toString();
}

From source file:org.etudes.mneme.impl.ImportQtiServiceImpl.java

/**
 * Find all the items from the root using the path, and combine their text content.
 * /*from   w ww .  ja  v a2 s. c o m*/
 * @param textPath
 *        Text XPath
 * @param blanksPath
 *        Blanks XPath
 * @param answersPath
 *        Answers XPath
 * @param root
 *        The Document or Element root
 * @return The question.
 */
protected String buildFillInQuestionText(XPath textPath, XPath blanksPath, XPath answersPath, Object root) {
    StringBuilder rv = new StringBuilder();
    String questionText = null;
    try {
        List hits = textPath.selectNodes(root);
        List blankHits = blanksPath.selectNodes(root);
        List answerHits = answersPath.selectNodes(root);

        if (answerHits.size() != blankHits.size())
            return null;

        int count = 0, blanksCount = 0;

        blanksCount = blankHits.size();

        for (Object o : hits) {
            // add braces for the text
            if (count > 0 && blanksCount > 0) {
                rv.append(" {} ");
                blanksCount--;
            }

            Element e = (Element) o;
            String value = StringUtil.trimToNull(e.getTextContent());
            if (value != null) {
                rv.append(value);
            }
            count++;
        }

        // fill the braces({}) with answers
        questionText = rv.toString();
        Element e;
        String answer;
        for (int index = 0; index < answerHits.size(); index++) {
            e = (Element) answerHits.get(index);
            answer = StringUtil.trimToNull(e.getTextContent());
            questionText = questionText.replaceFirst("\\{\\}", Matcher.quoteReplacement("{" + answer + "}"));
        }
    } catch (JaxenException e) {
        M_log.warn(e.toString());
    }

    if (questionText.length() == 0)
        return null;
    return questionText;
}

From source file:org.exist.xquery.xproc.ProcessFunction.java

protected void parseOptions(UserArgs userArgs, Sequence optSeq) throws XPathException {

    if (optSeq.isEmpty())
        return;/*from  w  w  w .  j  ava  2 s.  c  o  m*/

    SequenceIterator iter = optSeq.iterate();
    while (iter.hasNext()) {
        Element element = (Element) iter.nextItem();

        String localName = element.getLocalName();
        if ("input".equalsIgnoreCase(localName)) {

            String port = element.getAttribute("port");
            if (port == null || port.isEmpty()) {
                throw new XPathException(this, "Input pipe port undefined at '" + element.toString() + "'");
            }

            com.xmlcalabash.util.Input.Type type;
            String _type = element.getAttribute("type");
            if (_type == null || _type.isEmpty()) {
                throw new XPathException(this, "Input pine type undefined at '" + element.toString() + "'");
            } else if ("XML".equalsIgnoreCase(_type)) {
                type = com.xmlcalabash.util.Input.Type.XML;
            } else if ("DATA".equalsIgnoreCase(_type)) {
                type = com.xmlcalabash.util.Input.Type.DATA;
            } else {
                throw new XPathException(this, "Unknown input pine type '" + _type + "'");
            }

            String url = element.getAttribute("url");
            if (url == null || url.isEmpty()) {
                throw new XPathException(this, "Input pine url undefined at '" + element.toString() + "'");
            }

            userArgs.addInput(port, url, type);

        } else if ("output".equalsIgnoreCase(localName)) {

            String port = element.getAttribute("port");
            if (port == null || port.isEmpty()) {
                throw new XPathException(this, "Output pipe port undefined at '" + element.toString() + "'");
            }

            String url = element.getAttribute("url");
            if (url == null || url.isEmpty()) {
                throw new XPathException(this, "Output pine url undefined at '" + element.toString() + "'");
            }

            userArgs.addOutput(port, url);

        } else if ("option".equalsIgnoreCase(localName)) {

            String name = element.getAttribute("name");
            if (name == null || name.isEmpty()) {
                throw new XPathException(this, "Option name undefined at '" + element.toString() + "'");
            }

            String value = element.getAttribute("value");
            if (value == null || value.isEmpty()) {
                throw new XPathException(this, "Option value undefined at '" + element.toString() + "'");
            }

            userArgs.addOption(name, value);
        } else
            throw new XPathException(this, "Unknown option '" + localName + "'.");
    }
}

From source file:org.mule.service.soap.client.SoapCxfClient.java

private Optional<String> parseExceptionDetail(Element detail) {
    try {/*from   w ww  .  j a va 2s .c o m*/
        return ofNullable(XmlTransformationUtils.nodeToString(detail));
    } catch (XmlTransformationException e) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Error while parsing Soap Exception detail: " + detail.toString(), e);
        }
        return empty();
    }
}

From source file:org.sakaiproject.assignment.impl.AssignmentServiceImpl.java

@Override
@Transactional/*from w  ww. ja v  a  2 s.  c om*/
public Assignment mergeAssignment(Element el) throws IdInvalidException, IdUsedException, PermissionException {
    // TODO need to write a test for this
    // this may also need to handle submission serialization?
    Assignment assignmentFromXml = assignmentRepository.fromXML(el.toString());

    return addAssignment(assignmentFromXml.getContext());
}

From source file:org.wso2.carbon.repository.core.config.RepositoryConfigurationProcessor.java

private static void readMounts(Element configElement, RepositoryContext repositoryContext)
        throws RepositoryException {

    try {//from  w  w  w. j  ava2  s . c o  m
        NodeList mounts = configElement.getElementsByTagName("mount");
        List<String> pathList = new ArrayList<String>();

        for (int mountItem = 0; mountItem < mounts.getLength(); mountItem++) {
            Node mountNode = mounts.item(mountItem);

            if (mountNode != null && mountNode.getNodeType() == Node.ELEMENT_NODE) {
                Element mountElement = (Element) mountNode;

                String path = mountElement.getAttribute("path");

                if (path == null) {
                    String msg = "The path attribute was not specified for remote mount. "
                            + "Skipping creation of remote mount. Element: " + mountElement.toString();
                    log.warn(msg);
                    continue;
                }

                if (pathList.contains(path)) {
                    String msg = "Two remote instances can't have the same path.";
                    log.error(msg);
                    throw new RepositoryConfigurationException(msg);
                }

                NodeList mountChildren = mountElement.getChildNodes();

                String instanceId = null;
                String targetPath = null;

                for (int mountIndex = 0; mountIndex < mountChildren.getLength(); mountIndex++) {
                    Node mountChild = mountChildren.item(mountIndex);

                    if (mountChild != null && mountChild.getNodeType() == Node.ELEMENT_NODE) {
                        if (mountChild.getNodeName() == "instanceid") {
                            instanceId = mountChild.getTextContent();
                        } else if (mountChild.getNodeName() == "targetPath") {
                            targetPath = mountChild.getTextContent();
                        } else {
                            String msg = "The instance identifier or targetPath is not specified for the mount: "
                                    + path;
                            log.warn(msg);
                            continue;
                        }
                    }
                }

                pathList.add(path);

                String overwriteStr = mountElement.getAttribute("overwrite");
                boolean overwrite = false;
                boolean virtual = false;

                if (overwriteStr != null) {
                    overwrite = Boolean.toString(true).equalsIgnoreCase(overwriteStr);
                    if (!overwrite) {
                        virtual = "virtual".equalsIgnoreCase(overwriteStr);
                    }
                }

                Mount mount = new Mount();

                mount.setPath(path);
                mount.setOverwrite(overwrite);
                mount.setVirtual(virtual);
                mount.setInstanceId(instanceId);
                mount.setTargetPath(targetPath);

                repositoryContext.getMounts().add(mount);
            }
        }
    } catch (Exception e) {
        String msg = "Could not read remote instance configuration. Caused by: " + e.getMessage();
        log.error(msg, e);
        throw new RepositoryConfigurationException(msg, e);
    }

}

From source file:us.derfers.tribex.rapids.Loader.java

/**
 * Loads scripts and styles from link tags.
 * @param linkElement The element from which to load the content from.
 * @param engine The ScriptEngine to run links to scripts in.
 * @return//  w ww  .java 2  s  .  c o m
 */
private boolean parseLinks(Element linkElement, ScriptEngine engine) {

    //Check and see if the <link> tag contains a rel and href attribute
    if (linkElement.getAttribute("href") != null) {
        //If it links to a stylesheet
        if ((linkElement.getAttributeNode("rel") != null
                && linkElement.getAttributeNode("rel").getTextContent().equals("stylesheet"))
                || linkElement.getAttributeNode("href").getTextContent().endsWith(".css")) {

            //Check and see if the href and URL exist.
            if (linkElement.getAttributeNode("href").getNodeValue().contains("://")) {
                try {
                    if (this.loadStyles(
                            IOUtils.toString(new URL(linkElement.getAttributeNode("href").getNodeValue())),
                            null) == false) {
                        Utilities.showError("Error: invalid file in link tag pointing to "
                                + linkElement.getAttributeNode("href").getTextContent());
                        return false;
                    }

                    if (linkElement.getAttributeNode("cache") != null) {
                        try {
                            FileUtils.writeStringToFile(
                                    new File(Globals
                                            .getCWD(linkElement.getAttributeNode("cache").getTextContent())),
                                    IOUtils.toString(
                                            new URL(linkElement.getAttributeNode("href").getNodeValue())));
                        } catch (Exception e2) {
                            Utilities.showError("Error: unable to cache to file "
                                    + linkElement.getAttributeNode("cache").getTextContent());
                        }
                    }

                } catch (Exception e) {
                    Utilities.showError(
                            "Unable to locate " + linkElement.getAttributeNode("href").getNodeValue());
                    //Attempt to load from the fallback file. (If tag and file exist)
                    if (linkElement.getAttributeNode("fallback") != null) {
                        if (this.loadStyles(null, Globals
                                .getCWD(linkElement.getAttributeNode("fallback").getTextContent())) == false) {
                            Utilities.showError("Error: invalid file in fallback tag pointing to "
                                    + linkElement.getAttributeNode("fallback").getTextContent());
                            return false;
                        }
                        ;
                    }
                }
                //Load from file
            } else {
                if (this.loadStyles(null,
                        Globals.getCWD(linkElement.getAttributeNode("href").getTextContent())) == false) {
                    Utilities.showError("Error: invalid file in link tag pointing to "
                            + linkElement.getAttributeNode("href").getTextContent());
                    return false;
                }
                ;
            }

            //If it links to a script
        } else if ((linkElement.getAttributeNode("rel") != null
                && linkElement.getAttributeNode("rel").getTextContent().equals("script"))
                || linkElement.getAttributeNode("href").getTextContent().endsWith(".js")) {

            //Check and see if the file exists
            if (linkElement.getAttributeNode("href").getNodeValue().contains("://")) {
                //Run script in file
                URL url;
                try {
                    url = new URL(linkElement.getAttributeNode("href").getTextContent());

                    URLConnection connection = url.openConnection();
                    connection.setConnectTimeout(10000);
                    connection.setReadTimeout(10000);
                    engine.eval(new InputStreamReader(connection.getInputStream()),
                            "Remote file: " + linkElement.getAttributeNode("href").getTextContent());

                    if (linkElement.getAttributeNode("cache") != null) {
                        try {
                            FileUtils.writeStringToFile(
                                    new File(Globals
                                            .getCWD(linkElement.getAttributeNode("cache").getTextContent())),
                                    IOUtils.toString(
                                            new URL(linkElement.getAttributeNode("href").getNodeValue())));
                        } catch (Exception e2) {
                            Utilities.showError("Error: unable to cache to file "
                                    + linkElement.getAttributeNode("cache").getTextContent());
                        }
                    }

                    return true;
                } catch (Exception e) {
                    //Attempt to load from the fallback file. (If tag and file exist)
                    if (linkElement.getAttributeNode("fallback") != null) {
                        try {
                            engine.eval(
                                    new java.io.FileReader(Globals
                                            .getCWD(linkElement.getAttributeNode("fallback").getTextContent())),
                                    linkElement.getAttributeNode("fallback").getTextContent());
                        } catch (Exception e2) {
                            Utilities.showError("Error: invalid file in fallback tag pointing to "
                                    + linkElement.getAttributeNode("fallback").getTextContent());
                        }
                    } else {
                        Utilities.showError(
                                "Unable to load " + linkElement.getAttributeNode("href").getTextContent()
                                        + ". No fallback found.");
                    }

                }

            } else {
                try {
                    //Run script in file
                    engine.eval(
                            new java.io.FileReader(
                                    Globals.getCWD(linkElement.getAttributeNode("href").getTextContent())),
                            linkElement.getAttributeNode("href").getTextContent());
                    return true;

                } catch (FileNotFoundException e) {
                    Utilities.showError("Error: invalid file in link tag pointing to "
                            + linkElement.getAttributeNode("href").getTextContent());
                    e.printStackTrace();
                    return false;
                } catch (DOMException e) {
                    Utilities.showError("Error: Improperly formatted XML");
                    e.printStackTrace();
                    return false;
                } catch (Exception e) {
                    Utilities.showError("Error: invalid script in file "
                            + linkElement.getAttributeNode("href").getTextContent());
                    e.printStackTrace();
                    return false;
                }
            }
        } else {
            //Attempt to load as a .rsm file

            //If the file is a URL on the internet:
            if (linkElement.getAttributeNode("href").getNodeValue().contains("://")) {
                try {
                    //Load the file from the internet.
                    Main.loader.loadAll(Utilities.EscapeScriptTags(
                            IOUtils.toString(new URL(linkElement.getAttributeNode("href").getNodeValue()))));

                    if (linkElement.getAttributeNode("cache") != null) {
                        try {
                            FileUtils.writeStringToFile(
                                    new File(Globals
                                            .getCWD(linkElement.getAttributeNode("cache").getTextContent())),
                                    IOUtils.toString(
                                            new URL(linkElement.getAttributeNode("href").getNodeValue())));
                        } catch (Exception e2) {
                            Utilities.showError("Error: unable to cache to file "
                                    + linkElement.getAttributeNode("cache").getTextContent());
                        }
                    }
                } catch (Exception e) {
                    if (linkElement.getAttributeNode("fallback") != null) {
                        try {
                            Main.loader.loadAll(Utilities.EscapeScriptTags(FileUtils.readFileToString(new File(
                                    Globals.getCWD(linkElement.getAttributeNode("fallback").getNodeValue())))));
                        } catch (Exception e2) {
                            Utilities.showError("Error: invalid file in fallback tag pointing to "
                                    + linkElement.getAttributeNode("fallback").getTextContent());
                        }
                    }
                }

                //Load the file from the Hard Drive
            } else {
                try {
                    Main.loader.loadAll(Utilities.EscapeScriptTags(FileUtils.readFileToString(
                            new File(Globals.getCWD(linkElement.getAttributeNode("href").getNodeValue())))));
                } catch (DOMException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    } else {
        System.out.println(linkElement.toString());
        Utilities.showError(
                "Warning: <link> tags must contain a href attribute and a rel attribute. Skipping tag.");
    }
    return false;
}