Example usage for org.w3c.dom Element getTextContent

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

Introduction

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

Prototype

public String getTextContent() throws DOMException;

Source Link

Document

This attribute returns the text content of this node and its descendants.

Usage

From source file:org.jasig.cas.support.pac4j.web.flow.ClientLogoutAction.java

private void logExtAuthentication(Object client, Object externalAuth, String action, String clientName,
        String tgtId) {/*ww  w . j a  v  a  2s.  c o  m*/

    logger.debug("==========================================");
    logger.debug("ClientLogoutAction ExtAuthentication:");
    logger.debug("TGT(" + tgtId + ") action : " + action);
    logger.debug("TGT(" + tgtId + ") clientName : " + clientName);

    if (client instanceof CasClientWrapper) {

        String casCredential = (String) ((org.springframework.security.core.Authentication) externalAuth)
                .getCredentials();
        CasClientWrapper clientWrapper = (CasClientWrapper) client;

        logger.debug("TGT(" + tgtId + ") externalAuth.name : "
                + ((org.springframework.security.core.Authentication) externalAuth).getName());//externalAuth.name : alecas
        logger.debug("TGT(" + tgtId + ") externalAuth.principal : "
                + ((org.springframework.security.core.Authentication) externalAuth).getPrincipal()); //externalAuth.principal : alecas
        logger.debug("TGT(" + tgtId + ") externalAuth.details : "
                + ((org.springframework.security.core.Authentication) externalAuth).getDetails());//externalAuth.details : org.springframework.security.web.authentication.WebAuthenticationDetails@ffff10d0: RemoteIpAddress: 131.175.80.175; SessionId: 22466E1781FC5BB68EDA8D5CB9BDA221>
        logger.debug("TGT(" + tgtId + ") externalAuth.casCredential : " + casCredential); //casCredential : ST-1-Yh3wBtU9yTa06g6qh6Mx-cas-server.cas.alessandro.it>
        logger.debug("TGT(" + tgtId + ") client.callbackUrl : " + clientWrapper.getCallbackUrl()); //https://cas.alessandro.it:6443/caspac/logout?action=SingleLogout

    }

    if (client instanceof Saml2ClientWrapper) {

        SAMLCredential sAMLCredential = (SAMLCredential) ((org.springframework.security.core.Authentication) externalAuth)
                .getCredentials();
        List<Attribute> attributes = sAMLCredential.getAttributes();
        Saml2ClientWrapper clientWrapper = (Saml2ClientWrapper) client;

        logger.debug("TGT(" + tgtId + ") externalAuth.name : "
                + ((org.springframework.security.core.Authentication) externalAuth).getName());
        logger.debug("TGT(" + tgtId + ") externalAuth.principal : "
                + ((org.springframework.security.core.Authentication) externalAuth).getPrincipal());

        for (int i = 0; i < attributes.size(); i++) {
            org.opensaml.saml2.core.impl.AttributeImpl attribute = (AttributeImpl) attributes.get(i);
            logger.debug("credentials.attributes.friendlyName: " + attribute.getFriendlyName());

            for (XMLObject attributeValue : attribute.getAttributeValues()) {
                Element attributeValueElement = attributeValue.getDOM();
                String value = attributeValueElement.getTextContent();
                logger.debug(attribute.getFriendlyName() + " value: " + value);
            }
        }
        logger.debug("TGT(" + tgtId + ") client.callbackUrl : " + clientWrapper.getCallbackUrl()); //https://cas.alessandro.it:6443/caspac/logout?action=SingleLogout

    }

    logger.debug("==========================================");

}

From source file:com.moviejukebox.reader.MovieNFOReader.java

/**
 * Parse Genres from the XML NFO file/*from   w ww  . j  av  a  2 s  .c o m*/
 *
 * Caters for multiple genres on the same line and multiple lines.
 *
 * @param nlElements
 * @param movie
 */
private static void parseGenres(NodeList nlElements, List<String> newGenres) {
    Node nElements;
    for (int looper = 0; looper < nlElements.getLength(); looper++) {
        nElements = nlElements.item(looper);
        if (nElements.getNodeType() == Node.ELEMENT_NODE) {
            Element eGenre = (Element) nElements;
            NodeList nlNames = eGenre.getElementsByTagName("name");
            if ((nlNames != null) && (nlNames.getLength() > 0)) {
                parseGenres(nlNames, newGenres);
            } else {
                newGenres.addAll(StringTools.splitList(eGenre.getTextContent(), SPLIT_GENRE));
            }
        }
    }
}

From source file:com.nextep.designer.p2.services.impl.LicenseService.java

private ILicenseInformation getLicenseFromUrl(String licenseKey, String uri)
        throws UnavailableLicenseServerException {

    // As we don't have CXF WebClient here for connect & parse, we use the
    // old doc builder way
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {/*from  w w  w  .ja  v a  2  s.  c  om*/
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(uri);
        Element elt = doc.getDocumentElement();
        NodeList list = elt.getElementsByTagName("license"); //$NON-NLS-1$
        Element license = (Element) list.item(0);
        if (license != null) {
            NodeList urls = license.getElementsByTagName("updateUrl"); //$NON-NLS-1$
            Element updateUrlElt = (Element) urls.item(0);
            String updateUrl = updateUrlElt.getTextContent();

            NodeList organizations = license.getElementsByTagName("organization"); //$NON-NLS-1$
            String organization = ((Element) organizations.item(0)).getTextContent();

            NodeList contactEmails = license.getElementsByTagName("contactEmail"); //$NON-NLS-1$
            String contactEmail = "unknown";
            if (contactEmails != null && contactEmails.getLength() > 0) {
                contactEmail = ((Element) contactEmails.item(0)).getTextContent();
            }

            NodeList contactNames = license.getElementsByTagName("contactName"); //$NON-NLS-1$
            String contactName = null;
            if (contactNames != null && contactNames.getLength() > 0) {
                contactName = ((Element) contactNames.item(0)).getTextContent();
            }

            //            NodeList validFromNode = license.getElementsByTagName("validFrom"); //$NON-NLS-1$
            // long validFrom = Long.parseLong(((Element)
            // validFromNode.item(0)).getTextContent());
            // Date validFromDate = new Date(validFrom);

            NodeList validUntilNode = license.getElementsByTagName("validUntil"); //$NON-NLS-1$
            long validUntil = Long.parseLong(((Element) validUntilNode.item(0)).getTextContent());
            Date validUntilDate = new Date(validUntil);

            NodeList permissions = license.getElementsByTagName(PERMISSION);
            if (permissions != null && permissions.getLength() > 0) {
                String val = permissions.item(0).getTextContent();
                if (PERMISSION_WARN.equals(val)) {
                    String msgKey = "preferences.license.licenseExpiredMsg"; //$NON-NLS-1$
                    if (validUntil > System.currentTimeMillis()) {
                        msgKey = "preferences.license.licenseQuotaMsg"; //$NON-NLS-1$
                    }
                    // Injecting contact email and name into warning message
                    final String dlgMsg = MessageFormat.format(P2Messages.getString(msgKey), contactName,
                            contactEmail);

                    // Popping our dialog
                    Display.getDefault().syncExec(new Runnable() {

                        @Override
                        public void run() {
                            MessageDialog.openWarning(null,
                                    P2Messages.getString("preferences.license.licenseExpiredTitle"), //$NON-NLS-1$
                                    dlgMsg);

                        }
                    });
                } else if (PERMISSION_ERROR.equals(val)) {
                    String msgKey = "preferences.license.licenseExpiredError"; //$NON-NLS-1$
                    if (validUntil > System.currentTimeMillis()) {
                        msgKey = "preferences.license.licenseQuotaError"; //$NON-NLS-1$
                    }
                    // Injecting contact email and name into warning message
                    final String dlgMsg = MessageFormat.format(P2Messages.getString(msgKey), contactName,
                            contactEmail);
                    Display.getDefault().syncExec(new Runnable() {

                        @Override
                        public void run() {
                            MessageDialog.openWarning(null,
                                    P2Messages.getString("preferences.license.licenseExpiredTitle"), //$NON-NLS-1$
                                    dlgMsg);
                            System.exit(-1);
                        }
                    });
                }
            }
            LicenseInformation info = new LicenseInformation();
            info.setUpdateSiteLocation(updateUrl);
            info.setLicenseKey(licenseKey);
            info.setOrganization(organization);
            info.setExpirationDate(validUntilDate);
            return info;
        }
    } catch (RuntimeException e) {
        throw new UnavailableLicenseServerException(
                P2Messages.getString("service.license.unexpectedException") + e.getMessage(), e); //$NON-NLS-1$
    } catch (Exception e) {
        throw new UnavailableLicenseServerException(
                P2Messages.getString("service.license.serverProblemException") + e.getMessage(), e); //$NON-NLS-1$
    }
    throw new UnavailableLicenseServerException(
            MessageFormat.format(P2Messages.getString("service.license.unregisteredLicense"), //$NON-NLS-1$
                    licenseKey));
}

From source file:org.gvnix.dynamic.configuration.roo.addon.config.XpathElementsDynamicConfiguration.java

/**
 * {@inheritDoc}//from   www  .  j  a v a 2s.  com
 */
@Override
public DynPropertyList read() {

    DynPropertyList dynProps = new DynPropertyList();

    // Get the XML file path
    MutableFile file = getFile();

    // If managed file not exists, nothing to do
    if (file != null) {

        // Obtain the XML file on DOM document format
        Document doc = getXmlDocument(file);

        // Obtain all xpath elements
        List<Element> elems = XmlUtils.findElements(getXpath(), doc.getDocumentElement());
        for (Element elem : elems) {

            // Create dynamic property with key and value elements
            Element key = XmlUtils.findFirstElement(getKey(), elem);
            Element value = XmlUtils.findFirstElement(getValue(), elem);
            if (key == null || value == null) {

                logger.log(Level.WARNING, "Element " + elem + " to get not exists on file");
                continue;
            }
            dynProps.add(new DynProperty(setKeyValue(key.getTextContent()), value.getTextContent()));
        }
    }

    return dynProps;
}

From source file:importer.handler.post.stages.Discriminator.java

/**
 * Does the element only contain corrected text?
 * @param elem the element to test/*from ww  w  . jav  a  2 s  .co m*/
 * @return true if it is else false
 */
boolean isCorrected(Element elem) {
    boolean result = false;
    if (isCorrectedElem(elem))
        result = true;
    else {
        String text = elem.getTextContent();
        int textLen = (text != null) ? text.length() : 0;
        int childLen = 0;
        Element child = firstChild(elem);
        while (child != null && !result) {
            String childText = elem.getTextContent();
            if (isCorrected(child))
                childLen += (childText != null) ? childText.length() : 0;
            child = nextSibling(child, true);
        }
        result = childLen == textLen;
    }
    return result;
}

From source file:com.evolveum.midpoint.schema.processor.MidPointSchemaDefinitionFactory.java

private ResourceAttributeDefinition getAnnotationReference(XSAnnotation annotation, QName qname,
        ObjectClassComplexTypeDefinition objectClass) throws SchemaException {
    Element element = SchemaProcessorUtil.getAnnotationElement(annotation, qname);
    if (element != null) {
        String reference = element.getTextContent();
        if (reference == null || reference.isEmpty()) {
            // Compatibility
            reference = element.getAttribute("ref");
        }/*from w  w  w. j a  v  a2  s.c  o  m*/
        if (reference != null && !reference.isEmpty()) {
            QName referenceItemName = DOMUtil.resolveQName(element, reference);
            PrismPropertyDefinition definition = objectClass.findPropertyDefinition(referenceItemName);
            if (definition == null) {
                throw new SchemaException("The annotation " + qname + " in " + objectClass + " is pointing to "
                        + referenceItemName + " which does not exist");
            }
            if (definition instanceof ResourceAttributeDefinition) {
                return (ResourceAttributeDefinition) definition;
            } else {
                throw new SchemaException("The annotation " + qname + " in " + objectClass + " is pointing to "
                        + referenceItemName + " which is not an attribute, it is " + definition);
            }
        }
    }
    return null;
}

From source file:com.cloud.agent.api.storage.OVFHelper.java

public void rewriteOVFFile(final String origOvfFilePath, final String newOvfFilePath, final String diskName) {
    try {//from   w  ww. ja v  a 2s  . c o m
        final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new File(origOvfFilePath));
        NodeList disks = doc.getElementsByTagName("Disk");
        NodeList files = doc.getElementsByTagName("File");
        NodeList items = doc.getElementsByTagName("Item");
        String keepfile = null;
        List<Element> toremove = new ArrayList<Element>();
        for (int j = 0; j < files.getLength(); j++) {
            Element file = (Element) files.item(j);
            String href = file.getAttribute("ovf:href");
            if (diskName.equals(href)) {
                keepfile = file.getAttribute("ovf:id");
            } else {
                toremove.add(file);
            }
        }
        String keepdisk = null;
        for (int i = 0; i < disks.getLength(); i++) {
            Element disk = (Element) disks.item(i);
            String fileRef = disk.getAttribute("ovf:fileRef");
            if (keepfile == null) {
                s_logger.info("FATAL: OVA format error");
            } else if (keepfile.equals(fileRef)) {
                keepdisk = disk.getAttribute("ovf:diskId");
            } else {
                toremove.add(disk);
            }
        }
        for (int k = 0; k < items.getLength(); k++) {
            Element item = (Element) items.item(k);
            NodeList cn = item.getChildNodes();
            for (int l = 0; l < cn.getLength(); l++) {
                if (cn.item(l) instanceof Element) {
                    Element el = (Element) cn.item(l);
                    if ("rasd:HostResource".equals(el.getNodeName())
                            && !(el.getTextContent().contains("ovf:/file/" + keepdisk)
                                    || el.getTextContent().contains("ovf:/disk/" + keepdisk))) {
                        toremove.add(item);
                        break;
                    }
                }
            }
        }

        for (Element rme : toremove) {
            if (rme.getParentNode() != null) {
                rme.getParentNode().removeChild(rme);
            }
        }

        final StringWriter writer = new StringWriter();
        final StreamResult result = new StreamResult(writer);
        final TransformerFactory tf = TransformerFactory.newInstance();
        final Transformer transformer = tf.newTransformer();
        final DOMSource domSource = new DOMSource(doc);
        transformer.transform(domSource, result);
        PrintWriter outfile = new PrintWriter(newOvfFilePath);
        outfile.write(writer.toString());
        outfile.close();
    } catch (SAXException | IOException | ParserConfigurationException | TransformerException e) {
        s_logger.info("Unexpected exception caught while removing network elements from OVF:" + e.getMessage(),
                e);
        throw new CloudRuntimeException(e);
    }
}

From source file:com.mirth.connect.server.servlets.WebStartServlet.java

private Document getAdministratorJnlp(HttpServletRequest request) throws Exception {
    InputStream is = ResourceUtil.getResourceStream(this.getClass(), "mirth-client.jnlp");
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
    IOUtils.closeQuietly(is);//from   w w w  .j a v a  2s . c o  m

    Element jnlpElement = document.getDocumentElement();

    // Change the title to include the version of Mirth Connect
    PropertiesConfiguration versionProperties = new PropertiesConfiguration();
    versionProperties.setDelimiterParsingDisabled(true);
    versionProperties.load(ResourceUtil.getResourceStream(getClass(), "version.properties"));
    String version = versionProperties.getString("mirth.version");

    Element informationElement = (Element) jnlpElement.getElementsByTagName("information").item(0);
    Element title = (Element) informationElement.getElementsByTagName("title").item(0);
    String titleText = title.getTextContent() + " " + version;

    // If a server name is set, prepend the application title with it
    String serverName = configurationController.getServerSettings().getServerName();
    if (StringUtils.isNotBlank(serverName)) {
        titleText = serverName + " - " + titleText;
    }

    title.setTextContent(titleText);

    String scheme = request.getScheme();
    String serverHostname = request.getServerName();
    int serverPort = request.getServerPort();
    String contextPath = request.getContextPath();
    String codebase = scheme + "://" + serverHostname + ":" + serverPort + contextPath;

    PropertiesConfiguration mirthProperties = new PropertiesConfiguration();
    mirthProperties.setDelimiterParsingDisabled(true);
    mirthProperties.load(ResourceUtil.getResourceStream(getClass(), "mirth.properties"));

    String server = null;

    if (StringUtils.isNotBlank(mirthProperties.getString("server.url"))) {
        server = mirthProperties.getString("server.url");
    } else {
        int httpsPort = mirthProperties.getInt("https.port", 8443);
        String contextPathProp = mirthProperties.getString("http.contextpath", "");

        // Add a starting slash if one does not exist
        if (!contextPathProp.startsWith("/")) {
            contextPathProp = "/" + contextPathProp;
        }

        // Remove a trailing slash if one exists
        if (contextPathProp.endsWith("/")) {
            contextPathProp = contextPathProp.substring(0, contextPathProp.length() - 1);
        }

        server = "https://" + serverHostname + ":" + httpsPort + contextPathProp;
    }

    jnlpElement.setAttribute("codebase", codebase);

    Element resourcesElement = (Element) jnlpElement.getElementsByTagName("resources").item(0);

    String maxHeapSize = request.getParameter("maxHeapSize");
    if (StringUtils.isBlank(maxHeapSize)) {
        maxHeapSize = mirthProperties.getString("administrator.maxheapsize");
    }
    if (StringUtils.isNotBlank(maxHeapSize)) {
        Element j2se = (Element) resourcesElement.getElementsByTagName("j2se").item(0);
        j2se.setAttribute("max-heap-size", maxHeapSize);
    }

    List<String> defaultClientLibs = new ArrayList<String>();
    defaultClientLibs.add("mirth-client.jar");
    defaultClientLibs.add("mirth-client-core.jar");
    defaultClientLibs.add("mirth-crypto.jar");
    defaultClientLibs.add("mirth-vocab.jar");

    for (String defaultClientLib : defaultClientLibs) {
        Element jarElement = document.createElement("jar");
        jarElement.setAttribute("download", "eager");
        jarElement.setAttribute("href", "webstart/client-lib/" + defaultClientLib);

        if (defaultClientLib.equals("mirth-client.jar")) {
            jarElement.setAttribute("main", "true");
        }

        resourcesElement.appendChild(jarElement);
    }

    List<String> clientLibs = ControllerFactory.getFactory().createExtensionController().getClientLibraries();

    for (String clientLib : clientLibs) {
        if (!defaultClientLibs.contains(clientLib)) {
            Element jarElement = document.createElement("jar");
            jarElement.setAttribute("download", "eager");
            jarElement.setAttribute("href", "webstart/client-lib/" + clientLib);
            resourcesElement.appendChild(jarElement);
        }
    }

    List<MetaData> allExtensions = new ArrayList<MetaData>();
    allExtensions
            .addAll(ControllerFactory.getFactory().createExtensionController().getConnectorMetaData().values());
    allExtensions
            .addAll(ControllerFactory.getFactory().createExtensionController().getPluginMetaData().values());

    // we are using a set so that we don't have duplicates
    Set<String> extensionPathsToAddToJnlp = new HashSet<String>();

    for (MetaData extension : allExtensions) {
        if (doesExtensionHaveClientOrSharedLibraries(extension)) {
            extensionPathsToAddToJnlp.add(extension.getPath());
        }
    }

    for (String extensionPath : extensionPathsToAddToJnlp) {
        Element extensionElement = document.createElement("extension");
        extensionElement.setAttribute("href", "webstart/extensions/" + extensionPath + ".jnlp");
        resourcesElement.appendChild(extensionElement);
    }

    Element applicationDescElement = (Element) jnlpElement.getElementsByTagName("application-desc").item(0);
    Element serverArgumentElement = document.createElement("argument");
    serverArgumentElement.setTextContent(server);
    applicationDescElement.appendChild(serverArgumentElement);
    Element versionArgumentElement = document.createElement("argument");
    versionArgumentElement.setTextContent(version);
    applicationDescElement.appendChild(versionArgumentElement);

    String[] protocols = configurationController.getHttpsClientProtocols();
    String[] cipherSuites = configurationController.getHttpsCipherSuites();

    // Only add arguments for the protocols / cipher suites if they are non-default
    if (!Arrays.areEqual(protocols, MirthSSLUtil.DEFAULT_HTTPS_CLIENT_PROTOCOLS)
            || !Arrays.areEqual(cipherSuites, MirthSSLUtil.DEFAULT_HTTPS_CIPHER_SUITES)) {
        Element sslArgumentElement = document.createElement("argument");
        sslArgumentElement.setTextContent("-ssl");
        applicationDescElement.appendChild(sslArgumentElement);

        Element protocolsArgumentElement = document.createElement("argument");
        protocolsArgumentElement.setTextContent(StringUtils.join(protocols, ','));
        applicationDescElement.appendChild(protocolsArgumentElement);

        Element cipherSuitesArgumentElement = document.createElement("argument");
        cipherSuitesArgumentElement.setTextContent(StringUtils.join(cipherSuites, ','));
        applicationDescElement.appendChild(cipherSuitesArgumentElement);
    }

    return document;
}

From source file:io.spring.initializr.test.generator.PomAssert.java

private void parseProperties() {
    NodeList nodes;//  ww  w  .ja  v a 2s . c om
    try {
        nodes = this.eng.getMatchingNodes(createRootNodeXPath("properties/*"), this.doc);
    } catch (XpathException e) {
        throw new IllegalStateException("Cannot find path", e);
    }
    for (int i = 0; i < nodes.getLength(); i++) {
        Node item = nodes.item(i);
        if (item instanceof Element) {
            Element element = (Element) item;
            this.properties.put(element.getTagName(), element.getTextContent());
        }
    }
}

From source file:de.betterform.xml.xforms.ui.Itemset.java

private Item initializeSelectorItem(int position) throws XFormsException {
    // detect reference node
    Node before = DOMUtil.findNthChildNS(this.element, NamespaceConstants.XFORMS_NS, XFormsConstants.ITEM,
            position);// w  ww.  j  a v a  2s .  c  o m
    if (before == null) {
        before = DOMUtil.findFirstChildNS(this.element, NamespaceConstants.BETTERFORM_NS, "data");
    }

    // create selector item
    Element element = (Element) this.prototype.cloneNode(true);
    this.element.insertBefore(element, before);

    if (this.model.isReady()) {
        // dispatch internal betterform event
        HashMap map = new HashMap();
        map.put("originalId", this.originalId != null ? this.originalId : this.id);
        map.put("prototypeId", this.prototype.getAttributeNS(null, "id"));
        this.container.dispatch(this.target, BetterFormEventNames.PROTOTYPE_CLONED, map);
    }

    // initialize selector item
    Item item = (Item) this.container.getElementFactory().createXFormsElement(element, this.model);
    item.setItemset(this);
    item.setPosition(position);
    item.setGeneratedId(this.container.generateId());
    item.registerId();
    item.init();

    if (this.model.isReady()) {
        // dispatch internal betterform event
        HashMap map = new HashMap();
        map.put("originalId", this.originalId != null ? this.originalId : this.id);
        map.put("position", String.valueOf(position));

        Element itemValueCopy = (Element) DOMUtil.getFirstChildByTagNameNS(element,
                NamespaceConstants.XFORMS_NS, "copy");
        if (itemValueCopy != null) {
            String copyValue = getXFormsAttribute(itemValueCopy, "id");
            map.put("value", copyValue);
        }

        Element itemLabel = (Element) DOMUtil.getFirstChildByTagNameNS(element, NamespaceConstants.XFORMS_NS,
                "label");
        if (itemLabel != null) {
            map.put("label", itemLabel.getTextContent());
        }
        this.container.dispatch(this.target, BetterFormEventNames.ITEM_INSERTED, map);
    }
    return item;
}