Example usage for org.w3c.dom Document getDocumentElement

List of usage examples for org.w3c.dom Document getDocumentElement

Introduction

In this page you can find the example usage for org.w3c.dom Document getDocumentElement.

Prototype

public Element getDocumentElement();

Source Link

Document

This is a convenience attribute that allows direct access to the child node that is the document element of the document.

Usage

From source file:com.wallellen.wechat.common.util.crypto.WxCryptUtil.java

static String extractEncryptPart(String xml) {
    try {/* w  w w . ja  v  a 2 s .c o  m*/
        DocumentBuilder db = builderLocal.get();
        Document document = db.parse(new InputSource(new StringReader(xml)));

        Element root = document.getDocumentElement();
        return root.getElementsByTagName("Encrypt").item(0).getTextContent();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static Element loadDocument(Reader target) {
    Document doc = null;
    try {//from  w w w  .j  a  v a 2 s  .  c  o m
        InputSource xmlInp = new InputSource(target);

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser = docBuilderFactory.newDocumentBuilder();
        doc = parser.parse(xmlInp);
        Element root = doc.getDocumentElement();
        root.normalize();
        return root;
    } catch (SAXParseException err) {
        System.err.println("URLMappingsXmlDAO ** Parsing error" + ", line " + err.getLineNumber() + ", uri "
                + err.getSystemId());
        System.err.println("URLMappingsXmlDAO error: " + err.getMessage());
    } catch (SAXException e) {
        System.err.println("URLMappingsXmlDAO error: " + e);
    } catch (java.net.MalformedURLException mfx) {
        System.err.println("URLMappingsXmlDAO error: " + mfx);
    } catch (java.io.IOException e) {
        System.err.println("URLMappingsXmlDAO error: " + e);
    } catch (Exception pce) {
        System.err.println("URLMappingsXmlDAO error: " + pce);
    }
    return null;
}

From source file:filehandling.FilePreprocessor.java

public static List<FileData> extractMDFilesFromXMLEmbedding(byte[] bytes, String basename, String extension) {

    List<FileData> returnList = new ArrayList<FileData>();
    try {/* w ww  .ja va  2  s.co m*/
        FileUtils.writeByteArrayToFile(new File("/tmp/debugData/instreamBeforeExtraction.xml"), bytes);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder dBuilder = dbf.newDocumentBuilder();

        Document doc = dBuilder.parse(new InputSource(new ByteArrayInputStream(bytes)));

        if (Master.DEBUG_LEVEL > Master.LOW) {
            System.out.println("Root element: " + doc.getDocumentElement().getNodeName());
        }

        NodeList entryElements = doc.getElementsByTagNameNS("http://www.w3.org/2005/Atom", "entry");
        for (int i = 0; i < entryElements.getLength(); i++) {
            Element entryElement = (Element) entryElements.item(i);
            FileData fd = null;
            /*
             * First try to find a <link> element pointing to Metadata as
             * this should be included by default
             */
            if (fd == null) {
                NodeList linkElements = entryElement.getElementsByTagNameNS("http://www.w3.org/2005/Atom",
                        "link");
                String iso19139Link = null;
                String iso19139_2Link = null;
                for (int j = 0; j < linkElements.getLength(); j++) {
                    Element linkElement = (Element) linkElements.item(j);
                    String relAttrValue = linkElement.getAttribute("rel");
                    String typeAttributeValue = linkElement.getAttribute("type");
                    if (relAttrValue != null && relAttrValue.equals("alternate")
                            && typeAttributeValue != null) {
                        switch (typeAttributeValue) {
                        case "application/vnd.iso.19139+xml":
                            iso19139Link = linkElement.getAttribute("href");
                            break;
                        case "application/vnd.iso.19139-2+xml":
                            iso19139_2Link = linkElement.getAttribute("href");
                            break;
                        }
                    }
                }
                /* iso19139-2 gets priority */
                String url = iso19139_2Link != null ? iso19139_2Link : iso19139Link;
                if (url != null) {
                    try (InputStream is = FileFetcher.fetchFileFromUrl(url)) {
                        Document doc2 = dBuilder.parse(new InputSource(is));
                        fd = processMDList(doc2.getDocumentElement(), extension, url);
                    }
                }
            }
            /*
             * Fallback to finding Metadata embedded directly in <entry>.
             * There will be either MI_Metadata or MD_Metadata, not both
             */
            if (fd == null) {
                fd = processMDList(entryElement.getElementsByTagName("gmi:MI_Metadata").item(0), extension,
                        null);
            }
            if (fd == null) {
                fd = processMDList(entryElement.getElementsByTagName("gmd:MD_Metadata").item(0), extension,
                        null);
            }

            if (fd != null) {
                returnList.add(fd);
            }
        }
    } catch (Exception e) {
        // TODO: handle exception

        if (Master.DEBUG_LEVEL > Master.LOW)
            System.out.println(e.getLocalizedMessage());
        GUIrefs.displayAlert("Error in FilePreprocessor.extractMDFilesFromXMLEmbedding"
                + StringUtilities.escapeQuotes(e.getMessage()));
    }
    return returnList;
}

From source file:Main.java

public static Element loadDocument(Reader target) {
    Document doc = null;
    try {//w  w  w  .java  2 s  . com
        InputSource xmlInp = new InputSource(target);

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder parser = docBuilderFactory.newDocumentBuilder();
        doc = parser.parse(xmlInp);
        Element root = doc.getDocumentElement();
        root.normalize();
        return root;
    } catch (SAXParseException err) {
        System.err.println("URLMappingsXmlDAO ** Parsing error, line " + err.getLineNumber() + ", uri "
                + err.getSystemId());
        System.err.println("URLMappingsXmlDAO error: " + err.getMessage());
    } catch (SAXException e) {
        System.err.println("URLMappingsXmlDAO error: " + e);
    } catch (MalformedURLException mfx) {
        System.err.println("URLMappingsXmlDAO error: " + mfx);
    } catch (IOException e) {
        System.err.println("URLMappingsXmlDAO error: " + e);
    } catch (Exception pce) {
        System.err.println("URLMappingsXmlDAO error: " + pce);
    }
    return null;
}

From source file:com.aurel.track.admin.customize.category.report.ReportBL.java

public static Map<String, String> getTemplateDescription2(InputStream is) {
    Map<String, String> description = new HashMap<String, String>();
    try {//ww w . java 2s .  co  m
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(is);
        doc.getDocumentElement().normalize();
        NodeList nl = doc.getDocumentElement().getChildNodes();
        for (int s = 0; s < nl.getLength(); s++) {
            if (nl.item(s).getNodeType() == Node.ELEMENT_NODE) {
                description.put(nl.item(s).getNodeName(), nl.item(s).getChildNodes().item(0).getNodeValue());
            }
        }
    } catch (Exception e) {
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    return description;
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.workspacecache.internal.InternalCacheLoader.java

/**
 * Save the local configuration data if it is dirty and the
 * {@link Workstation}'s cache is enabled.
 *
 * @param internalCache//www  . j av  a 2  s.  c  o m
 *        the cache to save (must not be <code>null</code>)
 * @param conflictingWorkspaces
 *        list of workspaces that were removed from the cache due to
 *        conflicts (must not be <code>null</code>)
 * @param workstationMutex
 *        the {@link Workstation}'s mutex object (must not be
 *        <code>null</code>), which is held during the save
 * @param file
 *        the file to save to (must not be <code>null</code>)
 */
public static void saveConfigIfDirty(final InternalCache internalCache,
        final AtomicReference<InternalWorkspaceConflictInfo[]> conflictingWorkspaces,
        final Object workstationMutex, final File file) {
    Check.notNull(conflictingWorkspaces, "conflictingWorkspaces"); //$NON-NLS-1$
    Check.notNull(workstationMutex, "workstationMutex"); //$NON-NLS-1$
    Check.notNull(file, "file"); //$NON-NLS-1$

    conflictingWorkspaces.set(InternalWorkspaceConflictInfo.EMPTY_ARRAY);

    // If the cached data hasn't changed in RAM or the cache directory is
    // inaccessible, we're done.
    if (!internalCache.isDirty()) {
        return;
    }

    // Create the document and the root node.
    final Document config = DOMCreateUtils.newDocument(XML_VERSION_CONTROL_SERVER);
    final Element rootNode = config.getDocumentElement();

    /*
     * We need to lock the cache file, if it exists, during the entire save
     * process. To prevent a deadlock where one thread grabs the file lock
     * and the other grabs the workstation lock, grab the workstation lock
     * first and hold it until the cache is marked clean (MarkClean()).
     */

    synchronized (workstationMutex) {
        final TFSFileLock lock = acquireLockOrThrow(file);

        try {
            // Read in the existing cache file, if any.
            final Document oldConfig = readCacheAsDocument(file);

            Element oldCacheNode = null;
            if (oldConfig != null) {
                oldCacheNode = DOMUtils.getFirstChildElement(oldConfig.getDocumentElement(), XML_SERVERS);
            }

            // Save the cached workspace data.
            final Element cacheNode = DOMUtils.appendChild(rootNode, XML_SERVERS);

            internalCache.save(oldCacheNode, cacheNode, conflictingWorkspaces);

            // Save the file.

            // Ensure the directories exist
            if (!file.exists() && file.getParentFile().exists() == false) {
                file.getParentFile().mkdirs();
            }

            OutputStream stream;
            try {
                stream = new FileOutputStream(file);

                DOMSerializeUtils.serializeToStream(config, stream, DOMSerializeUtils.ENCODING_UTF8,
                        DOMSerializeUtils.INDENT);
            } catch (final FileNotFoundException e) {
                // from FileOutputStream

                // We tried to create the directories above, so this may be
                // a permissions problem. Ignore the error and mark the
                // cache clean (below) during a normal exit.
            }
        } finally {
            lock.release();
            lock.close();
        }

        /*
         * The file has been saved and is no longer dirty. NOTE: This must
         * be inside the (synchronized) lock to prevent the race condition
         * where the cache gets marked clean right after another thread
         * modifies it (lock must be taken here and where the cache is
         * modified).
         */
        internalCache.markClean();
    }
}

From source file:Main.java

public static String documentToString(Document doc, String xslName) {
    StringWriter sw = new StringWriter();
    try {/*from  w  ww .  j  a  v  a 2 s  . com*/
        TransformerFactory transfactory = TransformerFactory.newInstance();
        Transformer transformer = transfactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        Source source = new DOMSource(doc.getDocumentElement());
        Result result = new StreamResult(sw);
        transformer.transform(source, result);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return head + xslName + sw.toString();
}

From source file:Main.java

private static String getValueExceptTags(String xmlContent, String... tags)
        throws TransformerException, SAXException, IOException, ParserConfigurationException {

    Document document = parse(xmlContent, CHARSET_UTF8);
    Element rootElement = document.getDocumentElement();
    replace2TextExceptTags(document, rootElement, tags);

    String rootTag = "xml_root_tag";
    Document newDocument = generate();
    Element newRootElement = newDocument.createElement(rootTag);
    newDocument.appendChild(newRootElement);
    copyNode(newDocument, newRootElement, rootElement);

    String text = write(newDocument);
    int startIndex = text.indexOf(">", text.indexOf("<" + rootTag));
    int lastIndex = text.lastIndexOf("</" + rootTag + ">");

    String result = "";
    if (startIndex > 0 && lastIndex > 0) {
        result = text.substring(startIndex + 1, lastIndex);
    }/* w  w  w.j a v  a  2s .  c o  m*/

    return result;
}

From source file:com.connexta.arbitro.TestUtil.java

/**
 * This creates the expected XACML response from a file
 *
 * @param rootDirectory   root directory of the  response files
 * @param versionDirectory   version directory of the  response files
 * @param responseId  response file name
 * @return ResponseCtx or null if any error
 *//*from ww w.  ja  v  a 2s.  c  o  m*/
public static ResponseCtx createResponse(String rootDirectory, String versionDirectory, String responseId) {

    File file = new File(".");
    try {
        String filePath = file.getCanonicalPath() + File.separator + TestConstants.RESOURCE_PATH
                + File.separator + rootDirectory + File.separator + versionDirectory + File.separator
                + TestConstants.RESPONSE_DIRECTORY + File.separator + responseId;

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        DocumentBuilder db = factory.newDocumentBuilder();
        Document doc = db.parse(new FileInputStream(filePath));
        return ResponseCtx.getInstance(doc.getDocumentElement());
    } catch (Exception e) {
        log.error("Error while reading expected response from file ", e);
        //ignore any exception and return null
    }

    return null;
}

From source file:com.mirth.connect.server.launcher.MirthLauncher.java

private static void addExtensionsToClasspath(List<URL> urls, String currentVersion) throws Exception {
    FileFilter extensionFileFilter = new NameFileFilter(
            new String[] { "plugin.xml", "source.xml", "destination.xml" }, IOCase.INSENSITIVE);
    FileFilter directoryFilter = FileFilterUtils.directoryFileFilter();
    File extensionPath = new File(EXTENSIONS_DIR);

    Properties extensionProperties = new Properties();
    File extensionPropertiesFile = new File(appDataDir, EXTENSION_PROPERTIES);

    /*/*w w  w  .  j  ava 2  s . c o m*/
     * If the file does not exist yet, an empty Properties object will be used, returning the
     * default of true for all extensions.
     */
    if (extensionPropertiesFile.exists()) {
        extensionProperties.load(new FileInputStream(extensionPropertiesFile));
    }

    if (extensionPath.exists() && extensionPath.isDirectory()) {
        File[] directories = extensionPath.listFiles(directoryFilter);

        for (File directory : directories) {
            File[] extensionFiles = directory.listFiles(extensionFileFilter);

            for (File extensionFile : extensionFiles) {
                try {
                    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                            .parse(extensionFile);
                    Element rootElement = document.getDocumentElement();

                    boolean enabled = extensionProperties
                            .getProperty(rootElement.getElementsByTagName("name").item(0).getTextContent(),
                                    "true")
                            .equalsIgnoreCase("true");
                    boolean compatible = isExtensionCompatible(
                            rootElement.getElementsByTagName("mirthVersion").item(0).getTextContent(),
                            currentVersion);

                    // Only add libraries from extensions that are not disabled and are compatible with the current version
                    if (enabled && compatible) {
                        NodeList libraries = rootElement.getElementsByTagName("library");

                        for (int i = 0; i < libraries.getLength(); i++) {
                            Element libraryElement = (Element) libraries.item(i);
                            String type = libraryElement.getAttribute("type");

                            if (type.equalsIgnoreCase("server") || type.equalsIgnoreCase("shared")) {
                                File pathFile = new File(directory, libraryElement.getAttribute("path"));

                                if (pathFile.exists()) {
                                    logger.trace("adding library to classpath: " + pathFile.getAbsolutePath());
                                    urls.add(pathFile.toURI().toURL());
                                } else {
                                    logger.error("could not locate library: " + pathFile.getAbsolutePath());
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("failed to parse extension metadata: " + extensionFile.getAbsolutePath(), e);
                }
            }
        }
    } else {
        logger.warn("no extensions found");
    }
}