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:edu.internet2.middleware.shibboleth.common.config.attribute.resolver.attributeDefinition.MappedAttributeDefinitionBeanDefinitionParser.java

/**
 * Process the value map elements.//from   w w  w .j av  a  2  s.  c o  m
 * 
 * @param pluginId ID of this data connector
 * @param pluginConfigChildren configuration elements
 * @param pluginBuilder the bean definition parser
 * 
 * @return the list of value maps
 */
protected List<ValueMap> processValueMaps(String pluginId, Map<QName, List<Element>> pluginConfigChildren,
        BeanDefinitionBuilder pluginBuilder) {
    List<ValueMap> maps = new ArrayList<ValueMap>(5);

    ValueMap valueMap;
    String returnValue;
    String sourceValue;
    boolean ignoreCase;
    boolean partialMatch;
    if (pluginConfigChildren.containsKey(VALUEMAP_ELEMENT_NAME)) {
        for (Element valueMapElem : pluginConfigChildren.get(VALUEMAP_ELEMENT_NAME)) {
            valueMap = new ValueMap();

            Map<QName, List<Element>> children = XMLHelper.getChildElements(valueMapElem);

            if (children.containsKey(RETURN_VALUE_ELEMENT_NAME)) {
                List<Element> returnValueElems = children.get(RETURN_VALUE_ELEMENT_NAME);
                returnValue = DatatypeHelper.safeTrimOrNullString(returnValueElems.get(0).getTextContent());
                valueMap.setReturnValue(returnValue);
            }

            if (children.containsKey(SOURCE_VALUE_ELEMENT_NAME)) {
                for (Element sourceValueElem : children.get(SOURCE_VALUE_ELEMENT_NAME)) {
                    sourceValue = DatatypeHelper.safeTrim(sourceValueElem.getTextContent());

                    if (sourceValueElem.hasAttributeNS(null, "ignoreCase")) {
                        ignoreCase = XMLHelper.getAttributeValueAsBoolean(
                                sourceValueElem.getAttributeNodeNS(null, "ignoreCase"));
                    } else {
                        ignoreCase = false;
                    }

                    if (sourceValueElem.hasAttributeNS(null, "partialMatch")) {
                        partialMatch = XMLHelper.getAttributeValueAsBoolean(
                                sourceValueElem.getAttributeNodeNS(null, "partialMatch"));
                    } else {
                        partialMatch = false;
                    }

                    valueMap.getSourceValues()
                            .add(valueMap.new SourceValue(sourceValue, ignoreCase, partialMatch));
                }
            }

            maps.add(valueMap);
        }
    }

    return maps;
}

From source file:edu.internet2.middleware.shibboleth.common.config.attribute.resolver.attributeDefinition.MappedAttributeDefinitionBeanDefinitionParser.java

/** {@inheritDoc} */
protected void doParse(String pluginId, Element pluginConfig, Map<QName, List<Element>> pluginConfigChildren,
        BeanDefinitionBuilder pluginBuilder, ParserContext parserContext) {
    super.doParse(pluginId, pluginConfig, pluginConfigChildren, pluginBuilder, parserContext);

    List<ValueMap> valueMaps = processValueMaps(pluginId, pluginConfigChildren, pluginBuilder);
    pluginBuilder.addPropertyValue("valueMaps", valueMaps);

    if (pluginConfigChildren.containsKey(DEFAULT_VALUE_ELEMENT_NAME)) {
        Element defaultValueElem = pluginConfigChildren.get(DEFAULT_VALUE_ELEMENT_NAME).get(0);
        String defaultValue = DatatypeHelper.safeTrimOrNullString(defaultValueElem.getTextContent());
        pluginBuilder.addPropertyValue("defaultValue", defaultValue);
        if (log.isDebugEnabled()) {
            log.debug("Attribute definition {} default value: {}", pluginId, defaultValue);
        }//from   w  w w.ja v a2s. c o m

        boolean passThru = false;
        if (defaultValueElem.hasAttributeNS(null, "passThru")) {
            passThru = XMLHelper
                    .getAttributeValueAsBoolean(defaultValueElem.getAttributeNodeNS(null, "passThru"));
        }
        pluginBuilder.addPropertyValue("passThru", passThru);
        if (log.isDebugEnabled()) {
            log.debug("Attribute definition {} uses default value pass thru: {}", pluginId, passThru);
        }
    }

}

From source file:de.mpg.imeji.presentation.servlet.autocompleter.java

private String parseCCLicense(String str) {
    str = "<licences>" + str + "</licences>";
    try {/*from   ww w.  j a v a 2 s. com*/
        JSONArray json = new JSONArray();
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        org.w3c.dom.Document doc = dBuilder.parse(new ByteArrayInputStream(str.getBytes()));
        doc.getDocumentElement().normalize();
        NodeList nList = ((org.w3c.dom.Document) doc).getElementsByTagName("option");
        for (int i = 0; i < nList.getLength(); i++) {
            Node nNode = nList.item(i);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                JSONObject license = new JSONObject();
                Element eElement = (Element) nNode;
                license.put("label", eElement.getTextContent());
                license.put("value", eElement.getTextContent());
                license.put("licenseId", eElement.getAttribute("value"));
                json.add(license);
            }
        }
        StringWriter out = new StringWriter();
        JSONArray.writeJSONString(json, out);
        return out.toString();
    } catch (Exception e) {
        log("Error Parsing CC License", e);
    }
    return str;
}

From source file:com.persistent.cloudninja.scheduler.DeploymentMonitor.java

/**
 * Parses the response received by making call to REST API.
 * It parses and gets the total no. roles and their instances.
 * /*from w ww.  j  ava2 s .c o  m*/
 * @param roleInfo
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 * @throws ParseException
 */
private void parseRoleInfo(StringBuffer roleInfo) throws ParserConfigurationException, SAXException,
        IOException, XPathExpressionException, ParseException {
    DocumentBuilder docBuilder = null;
    Document doc = null;
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setIgnoringElementContentWhitespace(true);
    docBuilder = docBuilderFactory.newDocumentBuilder();
    doc = docBuilder.parse(new InputSource(new StringReader(roleInfo.toString())));

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    NodeList roleList = (NodeList) xPath.evaluate("/Deployment/RoleList/Role/RoleName", doc,
            XPathConstants.NODESET);
    //get all the roles
    String roleName = null;
    List<String> listRoleNames = new ArrayList<String>();
    for (int i = 0; i < roleList.getLength(); i++) {
        Element element = (Element) roleList.item(i);
        roleName = element.getTextContent();
        RoleEntity roleEntity = roleDao.findByRoleName(roleName);
        if (roleEntity == null) {
            roleEntity = new RoleEntity();
            roleEntity.setName(roleName);
            roleDao.add(roleEntity);
        }
        listRoleNames.add(roleName);
    }

    xPathFactory = XPathFactory.newInstance();
    xPath = xPathFactory.newXPath();
    RoleInstancesEntity roleInstancesEntity = null;
    RoleInstancesId roleInstancesId = null;
    for (String name : listRoleNames) {
        roleList = (NodeList) xPath.evaluate(
                "/Deployment/RoleInstanceList/RoleInstance[RoleName='" + name + "']", doc,
                XPathConstants.NODESET);
        //get no. of instances for WorkerRole
        int noOfInstances = roleList.getLength();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        String date = dateFormat.format(calendar.getTime());
        roleInstancesId = new RoleInstancesId(dateFormat.parse(date), name);
        roleInstancesEntity = new RoleInstancesEntity(roleInstancesId, noOfInstances, "UPDATE");
        roleInstancesDao.add(roleInstancesEntity);
    }

}

From source file:com.clustercontrol.infra.util.WinRs.java

public String runCommand(String shellId, String command, String[] args) throws WsmanException {
    WsmanConnection conn = createConnection();
    ManagedReference ref = conn.newReference(RESOURCE_URI_CMD);
    ref.addSelector("ShellId", shellId);

    ManagedInstance shellInst = ref.createMethod(NAMESPACE_SHELL, "CommandLine");
    shellInst.addProperty("Command", command);
    for (String arg : args) {
        shellInst.addProperty("Arguments", arg);
    }//from   w  ww.j  a va  2  s .c o  m

    ManagedInstance resp = ref.invoke(shellInst, NAMESPACE_SHELL + "/Command");

    Element commandIdNode = WsmanUtils.findChild(resp.getBody(), NAMESPACE_SHELL, "CommandId");
    return commandIdNode.getTextContent();
}

From source file:com.t2tierp.controller.nfe.EnviaNfe.java

@SuppressWarnings("rawtypes")
public Map enviaNfe(String xml, String alias, KeyStore ks, char[] senha, String codigoUf, String ambiente)
        throws Exception {
    String versaoDados = "3.10";
    String url = "";
    if (codigoUf.equals("52")) {
        if (ambiente.equals("1")) {
            url = "https://nfe.sefaz.go.gov.br/nfe/services/v2/NfeAutorizacao?wsdl";
        } else if (ambiente.equals("2")) {
            url = "https://homolog.sefaz.go.gov.br/nfe/services/v2/NfeAutorizacao?wsdl";
        }/*from  w w w  . ja v a2s .  c  o  m*/
    }
    /* fica a cargo de cada participante definir a url que sera utiizada de acordo com o codigo da UF
     * URLs disponiveis em:
     * Homologacao: http://hom.nfe.fazenda.gov.br/PORTAL/WebServices.aspx
     * Producao: http://www.nfe.fazenda.gov.br/portal/WebServices.aspx
     */

    if (url.equals("")) {
        throw new Exception("URL da sefaz no definida para o cdigo de UF = " + codigoUf);
    }

    X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
    PrivateKey privatekey = (PrivateKey) ks.getKey(alias, senha);
    SocketFactoryDinamico socketFactory = new SocketFactoryDinamico(certificate, privatekey);
    //arquivo que contem a cadeia de certificados do servico a ser consumido
    socketFactory.setFileCacerts(this.getClass().getResourceAsStream("/br/inf/portalfiscal/nfe/jssecacerts"));

    //define o protocolo a ser utilizado na conexao
    Protocol protocol = new Protocol("https", socketFactory, 443);
    Protocol.registerProtocol("https", protocol);

    OMElement omElement = AXIOMUtil.stringToOM(xml);

    NfeAutorizacaoStub.NfeDadosMsg dadosMsg = new NfeAutorizacaoStub.NfeDadosMsg();
    dadosMsg.setExtraElement(omElement);

    NfeAutorizacaoStub.NfeCabecMsg cabecMsg = new NfeAutorizacaoStub.NfeCabecMsg();
    cabecMsg.setCUF(codigoUf);
    cabecMsg.setVersaoDados(versaoDados);

    NfeAutorizacaoStub.NfeCabecMsgE cabecMsgE = new NfeAutorizacaoStub.NfeCabecMsgE();
    cabecMsgE.setNfeCabecMsg(cabecMsg);

    NfeAutorizacaoStub stub = new NfeAutorizacaoStub(url);

    NfeAutorizacaoStub.NfeAutorizacaoLoteResult result = stub.nfeAutorizacaoLote(dadosMsg, cabecMsgE);

    ByteArrayInputStream in = new ByteArrayInputStream(result.getExtraElement().toString().getBytes("UTF-8"));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().parse(in);

    String recibo = "";
    NodeList nodeList = doc.getDocumentElement().getElementsByTagName("nRec");

    for (int i = 0; i < nodeList.getLength(); i++) {
        Element element = (Element) nodeList.item(i);
        recibo = element.getTextContent();
    }

    Thread.sleep(3000);
    return consultaEnvioNfe(recibo, xml, codigoUf, ambiente);
}

From source file:com.netscape.certsrv.client.PKIClient.java

public byte[] downloadCACertChain(String uri, String servletPath)
        throws ParserConfigurationException, SAXException, IOException {

    URL url = new URL(uri + servletPath);

    if (verbose)/*from ww w.j  a va2  s  . c o  m*/
        System.out.println("Retrieving CA certificate chain from " + url + ".");

    DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();

    Document document = documentBuilder.parse(url.openStream());
    NodeList list = document.getElementsByTagName("ChainBase64");
    Element element = (Element) list.item(0);

    String encodedChain = element.getTextContent();
    byte[] bytes = Utils.base64decode(encodedChain);

    if (verbose) {
        System.out.println("-----BEGIN PKCS7-----");
        System.out.print(new Base64(64).encodeToString(bytes));
        System.out.println("-----END PKCS7-----");
    }

    return bytes;
}

From source file:org.freeeed.search.web.solr.SolrSearchService.java

private Set<String> getHighlight(Document solrDoc) {
    Set<String> result = new HashSet<String>();

    Element root = solrDoc.getDocumentElement();
    NodeList lists = root.getElementsByTagName("lst");
    for (int i = 0; i < lists.getLength(); i++) {
        Element lstEl = (Element) lists.item(i);
        String name = lstEl.getAttribute("name");
        if (("highlighting").equals(name)) {
            NodeList markedStrings = lstEl.getElementsByTagName("str");
            for (int j = 0; j < markedStrings.getLength(); j++) {
                Element strEl = (Element) markedStrings.item(j);
                String str = strEl.getTextContent();
                int start = str.indexOf("<em>");
                while (start > -1) {
                    int end = str.indexOf("</em>", start);
                    if (end != -1) {
                        String word = str.substring(start + 4, end);
                        result.add(word);
                    }/*from  ww  w  . j a  v  a 2 s .c o m*/

                    start = str.indexOf("<em>", end);
                }
            }
        }
    }

    return result;
}

From source file:edu.cornell.mannlib.vitro.webapp.web.templatemodels.customlistview.CustomListViewConfigFile.java

private String parseTemplateName(Document doc) throws InvalidConfigurationException {
    Element element = getExactlyOneElement(doc, TAG_TEMPLATE);
    elementMustNotBeEmpty(element);// www.j  a v a 2  s.c o m
    return element.getTextContent();
}

From source file:com.concursive.connect.web.modules.members.portlets.JoinPortlet.java

public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
    // Determine the project container to use
    Project project = PortalUtils.findProject(request);

    // Check the user's permissions
    User user = PortalUtils.getUser(request);

    try {//from  w w  w  . j a  v a 2 s. co  m
        // Get the urls to display
        ArrayList<HashMap> urlList = new ArrayList<HashMap>();
        String[] urls = request.getPreferences().getValues(PREF_URLS, new String[0]);
        for (String urlPreference : urls) {
            XMLUtils xml = new XMLUtils("<values>" + urlPreference + "</values>", true);
            ArrayList<Element> items = new ArrayList<Element>();
            XMLUtils.getAllChildren(xml.getDocumentElement(), items);
            HashMap<String, String> url = new HashMap<String, String>();
            for (Element thisItem : items) {
                String name = thisItem.getTagName();
                String value = thisItem.getTextContent();
                if (value.contains("${")) {
                    Template template = new Template(value);
                    for (String templateVariable : template.getVariables()) {
                        String[] variable = templateVariable.split("\\.");
                        template.addParseElement("${" + templateVariable + "}", ObjectUtils
                                .getParam(PortalUtils.getGeneratedData(request, variable[0]), variable[1]));
                    }
                    value = template.getParsedText();
                }
                url.put(name, value);
            }

            // Determine if the url can be shown
            boolean valid = true;
            // See if there are any special rules
            if (url.containsKey("rule")) {
                String rule = url.get("rule");
                if ("userCanRequestToJoin".equals(rule)) {
                    boolean canRequestToJoin = TeamMemberUtils.userCanRequestToJoin(user, project);
                    if (!canRequestToJoin) {
                        valid = false;
                    }
                } else if ("userCanJoin".equals(rule)) {
                    // TODO: Update the code that adds the user, and set the team member status to pending, then remove the membership required part
                    boolean canJoin = TeamMemberUtils.userCanJoin(user, project);
                    if (!canJoin) {
                        valid = false;
                    }
                } else {
                    LOG.error("Rule not found: " + rule);
                    valid = false;
                }
            }

            if (valid) {
                // Add to the list
                urlList.add(url);
            }
        }
        request.setAttribute(URL_LIST, urlList);

        // Only output the portlet if there are any urls to show
        if (urlList.size() > 0) {
            // Don't show the portlet on the user's own page
            if (user.getProfileProjectId() != project.getId()) {
                // Let the view know if this is a user profile
                if (project.getProfile()) {
                    request.setAttribute(IS_USER_PROFILE, "true");
                }
                // Show the view
                PortletContext context = getPortletContext();
                PortletRequestDispatcher requestDispatcher = context
                        .getRequestDispatcher(MEMBER_JOIN_PROFILE_FORM);
                requestDispatcher.include(request, response);
            }
        }
    } catch (Exception e) {
        LOG.error("doView", e);
        throw new PortletException(e.getMessage());
    }
}