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.persistent.cloudninja.controller.AuthFilterUtils.java

/**
 * Get Certificate thumb print and Issuer Name from the ACS token.
 * @param acsToken the acs token//from  w  w  w  .  j av  a2s  .  c  om
 * @return returnData the Map containing Thumb print and issuer name of X509Certiificate
 * @throws NoSuchAlgorithmException
 * @throws CertificateEncodingException
 */
public static Map<String, String> getCertificateThumbPrintAndIssuerName(String acsToken)
        throws NoSuchAlgorithmException, CertificateEncodingException {
    byte[] acsTokenByteArray = null;
    Map<String, String> returnData = new HashMap<String, String>();

    try {
        acsTokenByteArray = acsToken.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder;
    String issuerName = null;
    StringBuffer thumbprint = null;

    try {
        docBuilder = builderFactory.newDocumentBuilder();
        Document resultDoc = docBuilder.parse(new ByteArrayInputStream(acsTokenByteArray));
        Element keyInfo = (Element) resultDoc.getDocumentElement()
                .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "KeyInfo").item(0);

        NodeList x509CertNodeList = keyInfo.getElementsByTagName("X509Certificate");
        Element x509CertNode = (Element) x509CertNodeList.item(0);
        if (x509CertNode == null) {
            return null;
        }
        //generating Certificate to retrieve its detail.
        String x509CertificateData = x509CertNode.getTextContent();
        InputStream inStream = new Base64InputStream(new ByteArrayInputStream(x509CertificateData.getBytes()));
        CertificateFactory x509CertificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate x509Certificate = (X509Certificate) x509CertificateFactory
                .generateCertificate(inStream);
        String issuerDN = x509Certificate.getIssuerDN().toString();
        String[] issuerDNData = issuerDN.split("=");
        issuerName = issuerDNData[1];

        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] der = x509Certificate.getEncoded();
        md.update(der);
        thumbprint = new StringBuffer();
        thumbprint.append(Hex.encodeHex(md.digest()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    returnData.put("IssuerName", issuerName);
    returnData.put("Thumbprint", thumbprint.toString().toUpperCase());
    return returnData;
}

From source file:Main.java

public static ArrayList<String> getFontSizeList() {
    ArrayList<String> fontList = new ArrayList<String>();
    DocumentBuilderFactory dbfFont = null;
    DocumentBuilder dbFont = null;
    Document domFont = null;

    try {// w  ww . java 2s.co  m
        dbfFont = DocumentBuilderFactory.newInstance();
        String fontSizeFileName = "resources/FontSizes.xml";

        //Using factory get an instance of document builder
        dbFont = dbfFont.newDocumentBuilder();

        //parse using builder to get DOM representation of the XML file
        domFont = dbFont.parse(fontSizeFileName);

        //get the root elememt
        Element docEle = domFont.getDocumentElement();

        //get a nodelist of <sizes> elements
        NodeList sizeList = docEle.getElementsByTagName("size");
        if (sizeList != null && sizeList.getLength() > 0) {
            for (int i = 0; i < sizeList.getLength(); i++) {

                //get the employee element
                Element sizeElement = (Element) sizeList.item(i);
                fontList.add(sizeElement.getTextContent());
            }

        }
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (SAXException se) {
        se.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return fontList;

}

From source file:Main.java

/**
 * write out an XML file/*w w w.  j a va2s . c  o m*/
 * 
 * @param doc
 * @param os
 * @throws TransformerException 
 * @throws IOException 
 */
public static void writeXML(Document doc, OutputStream os) throws TransformerException, IOException {
    // write out xml file
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    //indent XML properly
    //formatXML(doc,doc.getDocumentElement(),"  ");

    //normalize document
    doc.getDocumentElement().normalize();

    //write XML to file
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(os);

    transformer.transform(source, result);
    os.close();
}

From source file:com.iflytek.spider.protocol.httpclient.Http.java

/**
 * Reads authentication configuration file (defined as 'http.auth.file' in
 * Nutch configuration file) and sets the credentials for the configured
 * authentication scopes in the HTTP client object.
 * //from  w w  w  .j a  va 2 s . co  m
 * @throws ParserConfigurationException
 *             If a document builder can not be created.
 * @throws SAXException
 *             If any parsing error occurs.
 * @throws IOException
 *             If any I/O error occurs.
 */
private static synchronized void setCredentials()
        throws ParserConfigurationException, SAXException, IOException {
    if (authFile == null || authFile.equals(""))
        authRulesRead = true;
    if (authRulesRead)
        return;

    authRulesRead = true; // Avoid re-attempting to read

    InputStream is = conf.getConfResourceAsInputStream(authFile);
    if (is != null) {
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);

        Element rootElement = doc.getDocumentElement();
        if (!"auth-configuration".equals(rootElement.getTagName())) {
            if (LOG.isWarnEnabled())
                LOG.warn("Bad auth conf file: root element <" + rootElement.getTagName() + "> found in "
                        + authFile + " - must be <auth-configuration>");
        }

        // For each set of credentials
        NodeList credList = rootElement.getChildNodes();
        for (int i = 0; i < credList.getLength(); i++) {
            Node credNode = credList.item(i);
            if (!(credNode instanceof Element))
                continue;

            Element credElement = (Element) credNode;
            if (!"credentials".equals(credElement.getTagName())) {
                if (LOG.isWarnEnabled())
                    LOG.warn("Bad auth conf file: Element <" + credElement.getTagName() + "> not recognized in "
                            + authFile + " - expected <credentials>");
                continue;
            }

            String username = credElement.getAttribute("username");
            String password = credElement.getAttribute("password");

            // For each authentication scope
            NodeList scopeList = credElement.getChildNodes();
            for (int j = 0; j < scopeList.getLength(); j++) {
                Node scopeNode = scopeList.item(j);
                if (!(scopeNode instanceof Element))
                    continue;

                Element scopeElement = (Element) scopeNode;

                if ("default".equals(scopeElement.getTagName())) {

                    // Determine realm and scheme, if any
                    String realm = scopeElement.getAttribute("realm");
                    String scheme = scopeElement.getAttribute("scheme");

                    // Set default credentials
                    defaultUsername = username;
                    defaultPassword = password;
                    defaultRealm = realm;
                    defaultScheme = scheme;

                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Credentials - username: " + username + "; set as default" + " for realm: "
                                + realm + "; scheme: " + scheme);
                    }

                } else if ("authscope".equals(scopeElement.getTagName())) {

                    // Determine authentication scope details
                    String host = scopeElement.getAttribute("host");
                    int port = -1; // For setting port to AuthScope.ANY_PORT
                    try {
                        port = Integer.parseInt(scopeElement.getAttribute("port"));
                    } catch (Exception ex) {
                        // do nothing, port is already set to any port
                    }
                    String realm = scopeElement.getAttribute("realm");
                    String scheme = scopeElement.getAttribute("scheme");

                    // Set credentials for the determined scope
                    AuthScope authScope = getAuthScope(host, port, realm, scheme);
                    NTCredentials credentials = new NTCredentials(username, password, agentHost, realm);

                    client.getState().setCredentials(authScope, credentials);

                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Credentials - username: " + username + "; set for AuthScope - " + "host: "
                                + host + "; port: " + port + "; realm: " + realm + "; scheme: " + scheme);
                    }

                } else {
                    if (LOG.isWarnEnabled())
                        LOG.warn("Bad auth conf file: Element <" + scopeElement.getTagName()
                                + "> not recognized in " + authFile + " - expected <authscope>");
                }
            }
            is.close();
        }
    }
}

From source file:com.jaspersoft.studio.server.ServerManager.java

public static void loadServerProfiles(MServers root) {
    root.removeChildren();/*from  w  w w  .j a v a2s .co m*/
    if (serverProfiles == null)
        serverProfiles = new HashMap<MServerProfile, String>();
    serverProfiles.clear();

    // Convert the old configuration
    ConfigurationManager.convertPropertyToStorage(PREF_TAG, PREF_TAG, new ServerNameProvider());

    // Read the configuration from the file storage
    File[] storageContent = ConfigurationManager.getStorageContent(PREF_TAG);
    for (File storageElement : storageContent) {
        try {
            InputStream inputStream = new FileInputStream(storageElement);
            Reader reader = new InputStreamReader(inputStream, "UTF-8");
            InputSource is = new InputSource(reader);
            is.setEncoding("UTF-8");
            Document document = JRXmlUtils.parse(is);
            Node serverNode = document.getDocumentElement();
            if (serverNode.getNodeType() == Node.ELEMENT_NODE) {
                try {
                    ServerProfile sprof = (ServerProfile) CastorHelper.read(serverNode,
                            MServerProfile.MAPPINGFILE);
                    MServerProfile sp = new MServerProfile(root, sprof);
                    new MDummy(sp);
                    serverProfiles.put(sp, storageElement.getName());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        } catch (Exception e) {
            UIUtils.showError(e);
        }
    }
}

From source file:com.github.alexfalappa.nbspringboot.projects.initializr.InitializrProjectWizardIterator.java

private static void filterProjectXML(FileObject fo, ZipInputStream str, String name) throws IOException {
    try {/*from  w w w. ja  v a 2 s  .c  om*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileUtil.copy(str, baos);
        Document doc = XMLUtil.parse(new InputSource(new ByteArrayInputStream(baos.toByteArray())), false,
                false, null, null);
        NodeList nl = doc.getDocumentElement().getElementsByTagName("name");
        if (nl != null) {
            for (int i = 0; i < nl.getLength(); i++) {
                Element el = (Element) nl.item(i);
                if (el.getParentNode() != null && "data".equals(el.getParentNode().getNodeName())) {
                    NodeList nl2 = el.getChildNodes();
                    if (nl2.getLength() > 0) {
                        nl2.item(0).setNodeValue(name);
                    }
                    break;
                }
            }
        }
        try (OutputStream out = fo.getOutputStream()) {
            XMLUtil.write(doc, out, "UTF-8");
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
        writeFile(str, fo);
    }

}

From source file:com.arcusys.liferay.vaadinplugin.util.ControlPanelPortletUtil.java

private static String getPomVaadinVersion(JarFile jarFile) {
    try {/* ww w  .  j a  va 2  s . c  o  m*/
        JarEntry pomEntry = null;

        // find pom.xml file in META-INF/maven and sub folders
        Enumeration<JarEntry> enumerator = jarFile.entries();
        while (enumerator.hasMoreElements()) {
            JarEntry entry = enumerator.nextElement();
            if (entry.getName().startsWith("META-INF/maven/") && entry.getName().endsWith("/pom.xml")) {
                pomEntry = entry;
                break;
            }
        }

        // read project version from pom.xml
        if (pomEntry != null) {
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(jarFile.getInputStream(pomEntry));
            NodeList children = document.getDocumentElement().getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                Node node = children.item(i + 1);
                if (node.getNodeName().equals("version")) {
                    return node.getTextContent();
                }
            }
        }
        return null;
    } catch (Exception exception) {
        return null;
    }
}

From source file:net.sourceforge.dita4publishers.impl.ditabos.DitaBosHelper.java

/**
 * Constructs a full DITA BOS from the specified root map using the specified BOS construction options.
 * @param bosOptions/*from   w ww  .  j a v a2s . c  o  m*/
 * @param log 
 * @param rootMap
 * @return
 * @throws Exception 
 */
public static DitaBoundedObjectSet calculateMapBos(BosConstructionOptions bosOptions, Log log, Document rootMap)
        throws Exception {

    Map<URI, Document> domCache = bosOptions.getDomCache();

    if (domCache == null) {
        domCache = new HashMap<URI, Document>();
        bosOptions.setDomCache(domCache);
    }

    DitaBoundedObjectSet bos = new DitaBoundedObjectSetImpl(bosOptions);

    if (!bosOptions.isQuiet())
        log.info("calculateMapBos(): Starting map BOS calculation...");

    Element elem = rootMap.getDocumentElement();
    if (!DitaUtil.isDitaMap(elem) && !DitaUtil.isDitaTopic(elem)) {
        throw new DitaBosHelperException(
                "Input root map " + rootMap.getDocumentURI() + " does not appear to be a DITA map or topic.");
    }

    DitaKeySpace keySpace;
    try {
        DitaKeyDefinitionContext keyDefContext = new KeyDefinitionContextImpl(rootMap);
        keySpace = new InMemoryDitaKeySpace(keyDefContext, rootMap, bosOptions);
    } catch (DitaApiException e) {
        throw new BosException("DITA API Exception: " + e.getMessage(), e);
    }

    DitaTreeWalker walker = new DitaDomTreeWalker(log, keySpace, bosOptions);
    walker.setRootObject(rootMap);
    walker.walk(bos);

    if (!bosOptions.isQuiet())
        log.info("calculateMapBos(): Returning BOS. BOS has " + bos.size() + " members.");
    return bos;
}

From source file:net.sourceforge.dita4publishers.word2dita.Word2DitaValidationHelper.java

/**
 * @param zipComponents /*  w w w .j av  a2s . c  om*/
 * @param logDoc
 * @param documentDom
 * @param commentsDom
 * @param commentTemplate
 * @throws XPathExpressionException
 */
static void addMessagesToDocxXml(Document logDoc, Document documentDom, Document commentsDom,
        Element commentTemplate) throws XPathExpressionException {
    NodeList messagesNl = logDoc.getDocumentElement().getElementsByTagName("message");

    for (int i = 0; i < messagesNl.getLength(); i++) {
        Element message = (Element) messagesNl.item(i);

        NodeList existingComments = commentsDom.getDocumentElement().getElementsByTagNameNS(wNs, "comment");
        String commentId = String.valueOf(existingComments.getLength());
        String messageText = message.getTextContent();

        addCommentToComments(commentsDom, commentTemplate, messageText, commentId);

        String xpath = message.getAttribute("wordParaXPath");
        // System.err.println("xpath=" + xpath);
        if (xpath == null || "".equals(xpath.trim())) {
            xpath = "/w:document/w:body[1]/w:p[1]";
        }

        addCommentRefToParaForXPath(documentDom, commentId, xpath);

    }
}

From source file:com.ibm.bi.dml.conf.DMLConfig.java

/**
 * //from  ww  w .j a  v  a2  s  . c  om
 * @param content
 * @return
 * @throws DMLRuntimeException
 */
public static DMLConfig parseDMLConfig(String content) throws DMLRuntimeException {
    DMLConfig ret = null;
    try {
        //System.out.println(content);
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document domTree = null;
        domTree = builder.parse(new ByteArrayInputStream(content.getBytes("utf-8")));
        Element root = domTree.getDocumentElement();
        ret = new DMLConfig(root);
    } catch (Exception ex) {
        throw new DMLRuntimeException("Unable to parse DML config.", ex);
    }

    return ret;
}