List of usage examples for org.w3c.dom Element getTextContent
public String getTextContent() throws DOMException;
From source file:uk.co.markfrimston.tasktree.TaskTree.java
public void loadConfig() throws Exception { try {/* w w w .ja v a 2 s .c o m*/ File file = new File(filePath + CONFIG_FILENAME); if (!file.exists()) { saveConfig(); } DocumentBuilder builder = builderFact.newDocumentBuilder(); Document doc = builder.parse(file); Element root = doc.getDocumentElement(); if (root == null || !root.getNodeName().equals("config")) { throw new Exception("Missing root element \"config\""); } Iterator<Element> i = getElementChildren(root); loadUrl = null; saveUrl = null; mergeCommand = null; lastSyncTime = 0L; unsynchedChanges = true; while (i.hasNext()) { Element el = i.next(); if (el.getNodeName().equals("load-url")) { loadUrl = el.getTextContent(); if (loadUrl != null && loadUrl.length() == 0) { loadUrl = null; } } else if (el.getNodeName().equals("save-url")) { saveUrl = el.getTextContent(); if (saveUrl != null && saveUrl.length() == 0) { saveUrl = null; } } else if (el.getNodeName().equals("merge-command")) { mergeCommand = el.getTextContent(); if (mergeCommand != null && mergeCommand.length() == 0) { mergeCommand = null; } } else if (el.getNodeName().equals("last-sync")) { try { lastSyncTime = Long.parseLong(el.getTextContent()); } catch (NumberFormatException e) { } } else if (el.getNodeName().equals("unsynched-changes")) { unsynchedChanges = Boolean.parseBoolean(el.getTextContent()); } } } catch (Exception e) { throw new Exception("Failed to load config file: " + e.getClass().getName() + " - " + e.getMessage()); } }
From source file:cz.incad.kramerius.pdf.impl.FirstPagePDFServiceImpl.java
FirstPageViewObject prepareViewObject(ResourceBundle resourceBundle) throws IOException, ParserConfigurationException, SAXException, UnsupportedEncodingException { FirstPageViewObject fpvo = new FirstPageViewObject(); String xml = this.textsService.getText("first_page_nolines_xml", this.localesProvider.get()); org.w3c.dom.Document doc = XMLUtils.parseDocument(new ByteArrayInputStream(xml.getBytes("UTF-8")), false); Element head = XMLUtils.findElement(doc.getDocumentElement(), "head"); Element desc = XMLUtils.findElement(doc.getDocumentElement(), "desc"); fpvo.setConditionUsage(head.getTextContent()); fpvo.setConditionUsageText(desc.getTextContent()); fpvo.setDitigalLibrary(resourceBundle.getString("pdf.digitallibrary")); fpvo.setHyphLang(this.localesProvider.get().getLanguage()); fpvo.setHyphCountry(this.localesProvider.get().getCountry()); fpvo.setPdfContainsTitle(resourceBundle.getString("pdf.pdfcontainstitle")); return fpvo;//w ww . ja v a 2 s . c o m }
From source file:com.microsoft.windowsazure.management.RoleSizeOperationsImpl.java
/** * The List Role Sizes operation lists all of the role sizes that are valid * for your subscription./*from www. j a v a 2 s .co m*/ * * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @return The List Role Sizes operation response. */ @Override public RoleSizeListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/rolesizes"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("x-ms-version", "2014-10-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result RoleSizeListResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new RoleSizeListResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element roleSizesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "RoleSizes"); if (roleSizesSequenceElement != null) { for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(roleSizesSequenceElement, "http://schemas.microsoft.com/windowsazure", "RoleSize") .size(); i1 = i1 + 1) { org.w3c.dom.Element roleSizesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(roleSizesSequenceElement, "http://schemas.microsoft.com/windowsazure", "RoleSize") .get(i1)); RoleSizeListResponse.RoleSize roleSizeInstance = new RoleSizeListResponse.RoleSize(); result.getRoleSizes().add(roleSizeInstance); Element nameElement = XmlUtility.getElementByTagNameNS(roleSizesElement, "http://schemas.microsoft.com/windowsazure", "Name"); if (nameElement != null) { String nameInstance; nameInstance = nameElement.getTextContent(); roleSizeInstance.setName(nameInstance); } Element labelElement = XmlUtility.getElementByTagNameNS(roleSizesElement, "http://schemas.microsoft.com/windowsazure", "Label"); if (labelElement != null) { String labelInstance; labelInstance = labelElement.getTextContent(); roleSizeInstance.setLabel(labelInstance); } Element coresElement = XmlUtility.getElementByTagNameNS(roleSizesElement, "http://schemas.microsoft.com/windowsazure", "Cores"); if (coresElement != null) { int coresInstance; coresInstance = DatatypeConverter.parseInt(coresElement.getTextContent()); roleSizeInstance.setCores(coresInstance); } Element memoryInMbElement = XmlUtility.getElementByTagNameNS(roleSizesElement, "http://schemas.microsoft.com/windowsazure", "MemoryInMb"); if (memoryInMbElement != null) { int memoryInMbInstance; memoryInMbInstance = DatatypeConverter.parseInt(memoryInMbElement.getTextContent()); roleSizeInstance.setMemoryInMb(memoryInMbInstance); } Element supportedByWebWorkerRolesElement = XmlUtility.getElementByTagNameNS( roleSizesElement, "http://schemas.microsoft.com/windowsazure", "SupportedByWebWorkerRoles"); if (supportedByWebWorkerRolesElement != null) { boolean supportedByWebWorkerRolesInstance; supportedByWebWorkerRolesInstance = DatatypeConverter .parseBoolean(supportedByWebWorkerRolesElement.getTextContent().toLowerCase()); roleSizeInstance.setSupportedByWebWorkerRoles(supportedByWebWorkerRolesInstance); } Element supportedByVirtualMachinesElement = XmlUtility.getElementByTagNameNS( roleSizesElement, "http://schemas.microsoft.com/windowsazure", "SupportedByVirtualMachines"); if (supportedByVirtualMachinesElement != null) { boolean supportedByVirtualMachinesInstance; supportedByVirtualMachinesInstance = DatatypeConverter .parseBoolean(supportedByVirtualMachinesElement.getTextContent().toLowerCase()); roleSizeInstance.setSupportedByVirtualMachines(supportedByVirtualMachinesInstance); } Element maxDataDiskCountElement = XmlUtility.getElementByTagNameNS(roleSizesElement, "http://schemas.microsoft.com/windowsazure", "MaxDataDiskCount"); if (maxDataDiskCountElement != null) { int maxDataDiskCountInstance; maxDataDiskCountInstance = DatatypeConverter .parseInt(maxDataDiskCountElement.getTextContent()); roleSizeInstance.setMaxDataDiskCount(maxDataDiskCountInstance); } Element webWorkerResourceDiskSizeInMbElement = XmlUtility.getElementByTagNameNS( roleSizesElement, "http://schemas.microsoft.com/windowsazure", "WebWorkerResourceDiskSizeInMb"); if (webWorkerResourceDiskSizeInMbElement != null) { int webWorkerResourceDiskSizeInMbInstance; webWorkerResourceDiskSizeInMbInstance = DatatypeConverter .parseInt(webWorkerResourceDiskSizeInMbElement.getTextContent()); roleSizeInstance .setWebWorkerResourceDiskSizeInMb(webWorkerResourceDiskSizeInMbInstance); } Element virtualMachineResourceDiskSizeInMbElement = XmlUtility.getElementByTagNameNS( roleSizesElement, "http://schemas.microsoft.com/windowsazure", "VirtualMachineResourceDiskSizeInMb"); if (virtualMachineResourceDiskSizeInMbElement != null) { int virtualMachineResourceDiskSizeInMbInstance; virtualMachineResourceDiskSizeInMbInstance = DatatypeConverter .parseInt(virtualMachineResourceDiskSizeInMbElement.getTextContent()); roleSizeInstance.setVirtualMachineResourceDiskSizeInMb( virtualMachineResourceDiskSizeInMbInstance); } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:betullam.xmlmodifier.XMLmodifier.java
private boolean checkCondition(String condStructureType, String condMdName, String condMdValue, Document xmlDoc) throws XPathExpressionException { String textContent;/*from w w w. ja v a 2 s . c o m*/ // Get the IDs for the requestet structure type, e. g. for "Monograph", "JournalVolume", etc. List<String> dmdIDs = getDMDIDs(condStructureType, xmlDoc); // Loop over the structure types and check if the metadata and it's value matches the requestet metadata and value. // E. g.: Only change a file if "TitleDocMain" (=condMdName) of a "Monograph" (=condMdValue) has the value "Title of the Monograph" (=condMdValue) for (String dmdID : dmdIDs) { // If we do not check for the value of the "name" attribute, we always have a match, so return true if (condMdName.equals("null")) { return true; } else { String xPathString = "//dmdSec[@ID=\"" + dmdID + "\"]//goobi/metadata[@name=\"" + condMdName + "\"]"; XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); XPathExpression xPathExpr = xPath.compile(xPathString); NodeList nodeList = (NodeList) xPathExpr.evaluate(xmlDoc, XPathConstants.NODESET); // Check if there is at least 1 element with the given value (condMdName) if (nodeList.getLength() > 0) { if (condMdValue.equals("null")) { // If we do not check for the value of the element, we always have a match, so return true return true; } else { for (int i = 0; i < nodeList.getLength(); i++) { Element xmlElement = (Element) nodeList.item(i); textContent = xmlElement.getTextContent(); if (textContent.equals(condMdValue)) { // Return true immediatly if the condition is met, because there could be other values for a duplicate metadata, which could return false. return true; } } } } } } return false; }
From source file:eu.fbk.dh.tint.tokenizer.ItalianTokenizer.java
public ItalianTokenizer(@Nullable File settingFile) { Trie.TrieBuilder builder = Trie.builder().removeOverlaps(); InputStream stream = null; if (settingFile != null) { try { stream = new FileInputStream(settingFile); } catch (FileNotFoundException e) { // continue }/* ww w . ja v a 2s .co m*/ } if (stream == null) { stream = this.getClass().getResourceAsStream("/token-settings.xml"); } logger.trace("Loading model"); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr; NodeList nl; int count; Document doc = dBuilder.parse(stream); doc.getDocumentElement().normalize(); // Normalization rules expr = xpath.compile("/settings/normalization/char"); nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { Node item = nl.item(i); Element element = (Element) item; String hexCode = element.getAttribute("hexcode"); String content = element.getTextContent(); // Bad: need fix if (content.equals("`")) { content = "'"; } int num = Integer.parseInt(hexCode, 16); if (content.length() == 0) { continue; } normalizedChars.put(num, content); } logger.info("Loaded {} normalization rules", normalizedChars.size()); // end sentence chars expr = xpath.compile("/settings/sentenceSplitting/char"); nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { Node item = nl.item(i); Element element = (Element) item; String charID = element.getAttribute("id"); sentenceChars.add(Integer.parseInt(charID)); } logger.info("Loaded {} sentence splitting rules", sentenceChars.size()); // splitting rules expr = xpath.compile("/settings/tokenSplitting/char"); nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { Node item = nl.item(i); Element element = (Element) item; String charID = element.getAttribute("id"); splittingChars.add(Integer.parseInt(charID)); } logger.info("Loaded {} token splitting rules", splittingChars.size()); // expressions expr = xpath.compile("/settings/expressions/expression"); nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); StringBuilder b = new StringBuilder(); b.append("("); boolean first = true; count = 0; for (int i = 0; i < nl.getLength(); i++) { Node item = nl.item(i); Element element = (Element) item; String regExp = element.getAttribute("find"); boolean merge = PropertiesUtils.getBoolean(element.getAttribute("merge"), true); Integer group = PropertiesUtils.getInteger(element.getAttribute("get"), 1); if (merge) { if (!first) { b.append("|"); } b.append(regExp); count++; first = false; } else { expressions.put(Pattern.compile(regExp), group); count++; } } b.append(")"); expressions.put(Pattern.compile(b.toString()), 1); logger.info("Loaded {} regular expressions", count); // abbreviations expr = xpath.compile("/settings/abbreviations/abbreviation"); nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); count = 0; for (int i = 0; i < nl.getLength(); i++) { Node item = nl.item(i); String abbr = item.getTextContent(); abbr = getString(tokenArray(abbr)); builder.addKeyword(" " + abbr + " "); count++; } logger.info("Loaded {} abbreviations", count); } catch (Exception e) { e.printStackTrace(); } trie = builder.build(); }
From source file:io.sunrisedata.wikipedia.WikipediaPageRevision.java
public void readFromXml(String xml) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new StringInputStream(xml)); // and now the fun part NodeList n = doc.getChildNodes().item(0).getChildNodes(); for (int i = 0; i < n.getLength(); i++) { Node node = n.item(i);/* ww w .ja v a2s . c o m*/ if (node.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) node; switch (e.getTagName()) { case XML_TAG_CONTRIBUTOR: NodeList contribNodes = e.getChildNodes(); for (int j = 0; j < contribNodes.getLength(); j++) { Node contribNode = contribNodes.item(j); if (contribNode.getNodeType() == Node.ELEMENT_NODE) { Element contribEl = (Element) contribNode; switch (contribEl.getTagName()) { case XML_TAG_CONTRIBUTOR_ID: this.contributorId = contribEl.getTextContent(); break; case XML_TAG_CONTRIBUTOR_IP: this.contributorIp = contribEl.getTextContent(); break; case XML_TAG_CONTRIBUTOR_USERNAME: this.contributorUsername = contribEl.getTextContent(); break; } } } break; case XML_TAG_TEXT: contentWikiMarkup = e.getTextContent(); if (e.hasAttribute(XML_ATTRIBUTE_TEXT_BYTES)) { this.declaredContentLength = Integer.parseInt(e.getAttribute(XML_ATTRIBUTE_TEXT_BYTES)); if (this.declaredContentLength > 0 && isEmpty()) { this.isMetadata = true; } } // determine if article is a disambiguation, redirection, and/or stub page. // the first characters of the text must be equal to IDENTIFIER_REDIRECTION_UPPERCASE or IDENTIFIER_REDIRECTION_LOWERCASE this.isRedirect = contentWikiMarkup.startsWith(IDENTIFIER_REDIRECTION_LOWERCASE) || contentWikiMarkup.startsWith(IDENTIFIER_REDIRECTION_UPPERCASE); // to be a stub, the article must contain the IDENTIFIER_STUB_WIKIPEDIA_NAMESPACE or IDENTIFIER_STUB_TEMPLATE this.isStub = contentWikiMarkup.contains(IDENTIFIER_STUB_TEMPLATE); break; case XML_TAG_ID: this.revisionId = e.getTextContent(); break; case XML_TAG_TIMESTAMP: this.timestamp = e.getTextContent(); break; case XML_TAG_MINOR: // presence of the empty <minor/> tag indicates it is a minor revision this.isMinor = true; break; case XML_TAG_COMMENT: this.comment = e.getTextContent(); break; case XML_TAG_SHA1: this.sha1 = e.getTextContent(); break; case XML_TAG_MODEL: this.model = e.getTextContent(); break; case XML_TAG_FORMAT: this.format = e.getTextContent(); break; case XML_TAG_PARENTID: this.parentRevisionId = e.getTextContent(); break; } } } }
From source file:io.fabric8.devops.connector.DevOpsConnector.java
public static String removeBuildParameter(Logger log, String template, String parameterName) { try {/*from w w w. j a v a2 s . c o m*/ Document doc = parseXmlText(template); Element rootElement = doc.getDocumentElement(); NodeList stringDefs = rootElement.getElementsByTagName("hudson.model.StringParameterDefinition"); if (stringDefs != null) { for (int i = 0, size = stringDefs.getLength(); i < size; i++) { Node item = stringDefs.item(i); if (item instanceof Element) { Element element = (Element) item; Element name = DomHelper.firstChild(element, "name"); if (name != null) { String textContent = name.getTextContent(); if (textContent != null) { if (parameterName.equals(textContent.trim())) { Node parameterDefinitions = item.getParentNode(); Node parametersDefinitionProperty = parameterDefinitions != null ? parameterDefinitions.getParentNode() : null; DomHelper.detach(item); if (DomHelper.firstChildElement(parameterDefinitions) == null) { DomHelper.detach(parameterDefinitions); } if (DomHelper.firstChildElement(parametersDefinitionProperty) == null) { DomHelper.detach(parametersDefinitionProperty); } return DomHelper.toXml(doc); } } } } } } } catch (Exception e) { log.error("Failed to remove the build parameter from the Jenkins XML. " + e, e); } return template; }
From source file:greenfoot.export.mygame.MyGameClient.java
private List<String> parseTagListXmlElement(Element element) { List<String> tags = new ArrayList<String>(); Node child = element.getFirstChild(); while (child != null) { if (child.getNodeType() == Node.ELEMENT_NODE) { element = (Element) child; if (element.getTagName().equals("tag")) { tags.add(element.getTextContent()); }/*w w w .j a v a 2 s . c om*/ } child = child.getNextSibling(); } return tags; }
From source file:com.evolveum.midpoint.prism.marshaller.ItemPathHolder.java
public ItemPathHolder(Element domElement) { String xpath = "."; if (domElement != null) { xpath = domElement.getTextContent(); }//www .j a v a2 s . co m parse(xpath, domElement, null); }
From source file:com.evolveum.midpoint.model.common.expression.functions.BasicExpressionFunctions.java
public String determineLdapSingleAttributeValue(String dn, String attributeName, Collection<?> values) throws NamingException { if (values == null || values.isEmpty()) { return null; }/* www. j a v a 2 s . c o m*/ Collection<String> stringValues = null; // Determine item type, try to convert to strings Object firstElement = values.iterator().next(); if (firstElement instanceof String) { stringValues = (Collection) values; } else if (firstElement instanceof Element) { stringValues = new ArrayList<String>(values.size()); for (Object value : values) { Element element = (Element) value; stringValues.add(element.getTextContent()); } } else { throw new IllegalArgumentException("Unexpected value type " + firstElement.getClass()); } if (stringValues.size() == 1) { return stringValues.iterator().next(); } if (StringUtils.isBlank(dn)) { throw new IllegalArgumentException( "No dn argument specified, cannot determine which of " + values.size() + " values to use"); } LdapName parsedDn = new LdapName(dn); for (int i = 0; i < parsedDn.size(); i++) { Rdn rdn = parsedDn.getRdn(i); Attributes rdnAttributes = rdn.toAttributes(); NamingEnumeration<String> rdnIDs = rdnAttributes.getIDs(); while (rdnIDs.hasMore()) { String rdnID = rdnIDs.next(); Attribute attribute = rdnAttributes.get(rdnID); if (attributeName.equals(attribute.getID())) { for (int j = 0; j < attribute.size(); j++) { Object value = attribute.get(j); if (stringValues.contains(value)) { return (String) value; } } } } } // Fallback. No values in DN. Just return the first alphabetically-wise value. return Collections.min(stringValues); }