List of usage examples for org.w3c.dom Element getTagName
public String getTagName();
From source file:at.ac.tuwien.big.testsuite.impl.validator.WaiValidator.java
private boolean extractDescription(Element container, StringBuilder sb) { for (Element e : DomUtils.asList(container.getChildNodes())) { if ("span".equals(e.getTagName()) && e.getAttribute("class").contains("gd_msg")) { String text = e.getTextContent(); Matcher matcher = CHECK_PATTERN.matcher(text); if (matcher.matches() && IGNORED_MESSAGES.contains(matcher.group(1))) { return false; }//from www . j a v a2 s .com sb.append(text.replaceAll("\\s*\\n\\s*", " ").trim()); } else if ("div".equals(e.getTagName()) && e.getAttribute("class").contains("gd_question_section")) { sb.append('\n'); sb.append(e.getTextContent().replaceAll("\\s*\\n\\s*", " ").trim()); } else if ("table".equals(e.getTagName()) && e.getAttribute("class").contains("data")) { sb.append('\n'); sb.append(DomUtils.textByXpath(e, ".//em").replaceAll("\\s*\\n\\s*", " ").trim()); sb.append('\n'); sb.append(DomUtils.textByXpath(e, ".//pre").replaceAll("\\s*\\n\\s*", " ").trim()); } } return true; }
From source file:de.egore911.reader.servlets.OpmlImportServlet.java
@SuppressWarnings("null") private void importRecursive(@Nonnull CategoryDao categoryDao, @Nonnull FeedUserDao feedUserDao, @Nonnull FeedDao feedDao, @Nonnull User user, @Nullable Key parent, NodeList nodes) throws ServletException { for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; if (!"outline".equals(element.getTagName())) { throw new ServletException("Invalid XML"); }//w ww .ja v a 2s.co m String xmlUrl = element.getAttribute("xmlUrl"); String title = element.getAttribute("title"); if (Strings.isNullOrEmpty(xmlUrl)) { // It does not have a xmlUrl -> this is a category if (title == null) { throw new ServletException("Invalid XML"); } Category category = categoryDao.getByName(title, user, parent); if (category == null) { category = new Category(parent, title, user); categoryDao.persist(category); } importRecursive(categoryDao, feedUserDao, feedDao, user, category.getId(), element.getChildNodes()); } else { Feed feed = feedDao.getByUrl(xmlUrl); if (feed == null) { feed = new Feed(title, xmlUrl); feedDao.persist(feed); FeedUser feedUser = new FeedUser(feed.getId(), user, parent); feedUserDao.persist(feedUser); } else { boolean found = false; for (FeedUser feedUser : feedUserDao.getFeedUsers(feed.getId())) { if (feedUser.getUser().equals(user)) { found = true; break; } } if (!found) { FeedUser feedUser = new FeedUser(feed.getId(), user, parent); feedUserDao.persist(feedUser); } } } } } }
From source file:com.digitalpebble.storm.crawler.filtering.regex.RegexURLNormalizer.java
private List<Rule> readConfiguration(Reader reader) { List<Rule> rules = new ArrayList<Rule>(); try {/* www . j a v a 2 s .co m*/ // borrowed heavily from code in Configuration.java Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader)); Element root = doc.getDocumentElement(); if ((!"regex-normalize".equals(root.getTagName())) && (LOG.isErrorEnabled())) { LOG.error("bad conf file: top-level element not <regex-normalize>"); } NodeList regexes = root.getChildNodes(); for (int i = 0; i < regexes.getLength(); i++) { Node regexNode = regexes.item(i); if (!(regexNode instanceof Element)) { continue; } Element regex = (Element) regexNode; if ((!"regex".equals(regex.getTagName())) && (LOG.isWarnEnabled())) { LOG.warn("bad conf file: element not <regex>"); } NodeList fields = regex.getChildNodes(); String patternValue = null; String subValue = null; for (int j = 0; j < fields.getLength(); j++) { Node fieldNode = fields.item(j); if (!(fieldNode instanceof Element)) { continue; } Element field = (Element) fieldNode; if ("pattern".equals(field.getTagName()) && field.hasChildNodes()) { patternValue = ((Text) field.getFirstChild()).getData(); } if ("substitution".equals(field.getTagName()) && field.hasChildNodes()) { subValue = ((Text) field.getFirstChild()).getData(); } if (!field.hasChildNodes()) { subValue = ""; } } if (patternValue != null && subValue != null) { Rule rule = createRule(patternValue, subValue); rules.add(rule); } } } catch (Exception e) { LOG.error("error parsing conf file", e); return EMPTY_RULES; } if (rules.size() == 0) { return EMPTY_RULES; } return rules; }
From source file:com.digitalpebble.stormcrawler.filtering.regex.RegexURLNormalizer.java
private List<Rule> readConfiguration(Reader reader) { List<Rule> rules = new ArrayList<>(); try {/*from w w w .ja va2s . co m*/ // borrowed heavily from code in Configuration.java Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader)); Element root = doc.getDocumentElement(); if ((!"regex-normalize".equals(root.getTagName())) && (LOG.isErrorEnabled())) { LOG.error("bad conf file: top-level element not <regex-normalize>"); } NodeList regexes = root.getChildNodes(); for (int i = 0; i < regexes.getLength(); i++) { Node regexNode = regexes.item(i); if (!(regexNode instanceof Element)) { continue; } Element regex = (Element) regexNode; if ((!"regex".equals(regex.getTagName())) && (LOG.isWarnEnabled())) { LOG.warn("bad conf file: element not <regex>"); } NodeList fields = regex.getChildNodes(); String patternValue = null; String subValue = null; for (int j = 0; j < fields.getLength(); j++) { Node fieldNode = fields.item(j); if (!(fieldNode instanceof Element)) { continue; } Element field = (Element) fieldNode; if ("pattern".equals(field.getTagName()) && field.hasChildNodes()) { patternValue = ((Text) field.getFirstChild()).getData(); } if ("substitution".equals(field.getTagName()) && field.hasChildNodes()) { subValue = ((Text) field.getFirstChild()).getData(); } if (!field.hasChildNodes()) { subValue = ""; } } if (patternValue != null && subValue != null) { Rule rule = createRule(patternValue, subValue); rules.add(rule); } } } catch (Exception e) { LOG.error("error parsing conf file", e); return EMPTY_RULES; } if (rules.size() == 0) { return EMPTY_RULES; } return rules; }
From source file:at.ac.tuwien.big.testsuite.impl.validator.WaiValidator.java
@Override public ValidationResult validate(File fileToValidate, String exerciseId) throws Exception { CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpPost request = new HttpPost("http://localhost:8080/" + contextPath + "/checker/index.php"); List<ValidationResultEntry> validationResultEntries = new ArrayList<>(); try {//from w w w. j a v a 2 s .c o m MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("uri", new StringBody("")); multipartEntity.addPart("MAX_FILE_SIZE", new StringBody("52428800")); multipartEntity.addPart("uploadfile", new FileBody(fileToValidate, "text/html")); multipartEntity.addPart("validate_file", new StringBody("Check It")); multipartEntity.addPart("pastehtml", new StringBody("")); multipartEntity.addPart("radio_gid[]", new StringBody("8")); multipartEntity.addPart("checkbox_gid[]", new StringBody("8")); multipartEntity.addPart("rpt_format", new StringBody("1")); request.setEntity(multipartEntity); Document doc = httpClient.execute(request, new DomResponseHandler(httpClient, request), httpContext); Element errorsContainer = DomUtils.byId(doc.getDocumentElement(), "AC_errors"); String title = ""; StringBuilder descriptionSb = new StringBuilder(); boolean descriptionStarted = false; for (Element e : DomUtils.asList(errorsContainer.getChildNodes())) { if ("h3".equals(e.getTagName())) { if (descriptionStarted) { validationResultEntries.add(new DefaultValidationResultEntry(title, descriptionSb.toString(), ValidationResultEntryType.ERROR)); } title = e.getTextContent(); descriptionSb.setLength(0); descriptionStarted = false; } else if ("div".equals(e.getTagName()) && e.getAttribute("class").contains("gd_one_check")) { if (descriptionStarted) { descriptionSb.append('\n'); } if (extractDescription(e, descriptionSb)) { descriptionStarted = true; } } } if (descriptionStarted) { validationResultEntries.add(new DefaultValidationResultEntry(title, descriptionSb.toString(), ValidationResultEntryType.ERROR)); } } finally { request.releaseConnection(); } return new DefaultValidationResult("WAI Validation", fileToValidate.getName(), new DefaultValidationResultType("WAI"), validationResultEntries); }
From source file:de.egore911.reader.servlets.OpmlImportServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { User user = getUserOrRedirect(resp); if (user == null) { return;//from www. j a va 2 s . c o m } boolean success = false; String reason = null; ServletFileUpload upload = new ServletFileUpload(); CategoryDao categoryDao = new CategoryDao(); FeedUserDao feedUserDao = new FeedUserDao(); FeedDao feedDao = new FeedDao(); try { FileItemIterator iter = upload.getItemIterator(req); // Parse the request while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if ("subscriptions".equals(name) && !item.isFormField() && "text/xml".equals(item.getContentType())) { try (InputStream stream = item.openStream()) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(stream); document.getDocumentElement().normalize(); Element opml = document.getDocumentElement(); if (!"opml".equals(opml.getTagName())) { throw new ServletException("Invalid XML"); } NodeList nodes = opml.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; if ("body".equals(element.getTagName())) { if (countFeeds(element.getChildNodes()) < 20) { importRecursive(categoryDao, feedUserDao, feedDao, user, Category.ROOT, element.getChildNodes()); success = true; } else { reason = "to_many_feeds"; } } } } } catch (ParserConfigurationException | SAXException e) { throw new ServletException(e.getMessage(), e); } } } } catch (FileUploadException e) { throw new ServletException(e.getMessage(), e); } if (success) { resp.sendRedirect("/reader"); } else { String redirectTo = "/import?msg=import_failed"; if (reason != null) { redirectTo += "&reason=" + reason; } resp.sendRedirect(redirectTo); } }
From source file:org.fcrepo.auth.xacml.FedoraPolicyFinderModule.java
/** * Creates a new policy or policy set object from the given policy node * * @param policyBinary/*from w ww . ja v a2 s . co m*/ * @return */ private AbstractPolicy loadPolicy(final FedoraBinary policyBinary) { String policyName = "unparsed"; try { // create the factory final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(true); factory.setNamespaceAware(true); factory.setValidating(false); final DocumentBuilder db = factory.newDocumentBuilder(); // Parse the policy content final Document doc = db.parse(policyBinary.getContent()); // handle the policy, if it's a known type final Element root = doc.getDocumentElement(); final String name = root.getTagName(); policyName = PolicyUtil.getID(doc); if (name.equals("Policy")) { return Policy.getInstance(root); } else if (name.equals("PolicySet")) { return PolicySet.getInstance(root, finder); } else { // this isn't a root type that we know how to handle throw new Exception("Unknown root document type: " + name); } } catch (final Exception e) { LOGGER.error("Unable to parse policy from {}", policyName, e); } // a default fall-through in the case of an error return null; }
From source file:com.ryantenney.metrics.spring.config.AnnotationDrivenBeanDefinitionParser.java
@Override public BeanDefinition parse(Element element, ParserContext parserContext) { final Object source = parserContext.extractSource(element); final CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source);/* w ww . jav a 2 s .co m*/ parserContext.pushContainingComponent(compDefinition); String metricsBeanName = element.getAttribute("metric-registry"); if (!StringUtils.hasText(metricsBeanName)) { metricsBeanName = registerComponent(parserContext, build(MetricRegistry.class, source, ROLE_APPLICATION)); } String healthCheckBeanName = element.getAttribute("health-check-registry"); if (!StringUtils.hasText(healthCheckBeanName)) { healthCheckBeanName = registerComponent(parserContext, build(HealthCheckRegistry.class, source, ROLE_APPLICATION)); } final ProxyConfig proxyConfig = new ProxyConfig(); if (StringUtils.hasText(element.getAttribute("expose-proxy"))) { proxyConfig.setExposeProxy(Boolean.valueOf(element.getAttribute("expose-proxy"))); } if (StringUtils.hasText(element.getAttribute("proxy-target-class"))) { proxyConfig.setProxyTargetClass(Boolean.valueOf(element.getAttribute("proxy-target-class"))); } //@formatter:off registerComponent(parserContext, build(MetricsBeanPostProcessorFactory.class, source, ROLE_INFRASTRUCTURE) .setFactoryMethod("exceptionMetered").addConstructorArgReference(metricsBeanName) .addConstructorArgValue(proxyConfig)); registerComponent(parserContext, build(MetricsBeanPostProcessorFactory.class, source, ROLE_INFRASTRUCTURE) .setFactoryMethod("metered").addConstructorArgReference(metricsBeanName) .addConstructorArgValue(proxyConfig)); registerComponent(parserContext, build(MetricsBeanPostProcessorFactory.class, source, ROLE_INFRASTRUCTURE).setFactoryMethod("timed") .addConstructorArgReference(metricsBeanName).addConstructorArgValue(proxyConfig)); registerComponent(parserContext, build(MetricsBeanPostProcessorFactory.class, source, ROLE_INFRASTRUCTURE) .setFactoryMethod("gauge").addConstructorArgReference(metricsBeanName)); registerComponent(parserContext, build(MetricsBeanPostProcessorFactory.class, source, ROLE_INFRASTRUCTURE) .setFactoryMethod("injectMetric").addConstructorArgReference(metricsBeanName)); registerComponent(parserContext, build(MetricsBeanPostProcessorFactory.class, source, ROLE_INFRASTRUCTURE) .setFactoryMethod("healthCheck").addConstructorArgReference(healthCheckBeanName)); //@formatter:on parserContext.popAndRegisterContainingComponent(); return null; }
From source file:com.amalto.core.storage.record.XmlDOMDataRecordReader.java
private void _read(MetadataRepository repository, DataRecord dataRecord, ComplexTypeMetadata type, Element element) { // TODO Don't use getChildNodes() but getNextSibling() calls (but cause regressions -> see TMDM-5410). String tagName = element.getTagName(); NodeList children = element.getChildNodes(); NamedNodeMap attributes = element.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); if (!type.hasField(attribute.getNodeName())) { continue; }/*from w ww.ja v a2 s. co m*/ FieldMetadata field = type.getField(attribute.getNodeName()); dataRecord.set(field, StorageMetadataUtils.convert(attribute.getNodeValue(), field)); } for (int i = 0; i < children.getLength(); i++) { Node currentChild = children.item(i); if (currentChild instanceof Element) { Element child = (Element) currentChild; if (METADATA_NAMESPACE.equals(child.getNamespaceURI())) { DataRecordMetadataHelper.setMetadataValue(dataRecord.getRecordMetadata(), child.getLocalName(), child.getTextContent()); } else { if (!type.hasField(child.getTagName())) { continue; } FieldMetadata field = type.getField(child.getTagName()); if (field.getType() instanceof ContainedComplexTypeMetadata) { ComplexTypeMetadata containedType = (ComplexTypeMetadata) field.getType(); String xsiType = child.getAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "type"); //$NON-NLS-1$ if (xsiType.startsWith("java:")) { //$NON-NLS-1$ // Special format for 'java:' type names (used in Castor XML to indicate actual class name) xsiType = ClassRepository.format(StringUtils .substringAfterLast(StringUtils.substringAfter(xsiType, "java:"), ".")); //$NON-NLS-1$ //$NON-NLS-2$ } if (!xsiType.isEmpty()) { for (ComplexTypeMetadata subType : containedType.getSubTypes()) { if (subType.getName().equals(xsiType)) { containedType = subType; break; } } } DataRecord containedRecord = new DataRecord(containedType, UnsupportedDataRecordMetadata.INSTANCE); dataRecord.set(field, containedRecord); _read(repository, containedRecord, containedType, child); } else if (ClassRepository.EMBEDDED_XML.equals(field.getType().getName())) { try { dataRecord.set(field, Util.nodeToString(element)); } catch (TransformerException e) { throw new RuntimeException(e); } } else { _read(repository, dataRecord, type, child); } } } else if (currentChild instanceof Text) { StringBuilder builder = new StringBuilder(); for (int j = 0; j < element.getChildNodes().getLength(); j++) { String nodeValue = element.getChildNodes().item(j).getNodeValue(); if (nodeValue != null) { builder.append(nodeValue.trim()); } } String textContent = builder.toString(); if (!textContent.isEmpty()) { FieldMetadata field = type.getField(tagName); if (field instanceof ReferenceFieldMetadata) { ComplexTypeMetadata actualType = ((ReferenceFieldMetadata) field).getReferencedType(); String mdmType = element.getAttributeNS(SkipAttributeDocumentBuilder.TALEND_NAMESPACE, "type"); //$NON-NLS-1$ if (!mdmType.isEmpty()) { actualType = repository.getComplexType(mdmType); } if (actualType == null) { throw new IllegalArgumentException("Type '" + mdmType + "' does not exist."); } dataRecord.set(field, StorageMetadataUtils.convert(textContent, field, actualType)); } else { dataRecord.set(field, StorageMetadataUtils.convert(textContent, field, type)); } } } } }
From source file:isl.FIMS.servlet.export.ExportXML.java
private void writeFile(String type, String id, String filePath, String username) throws IOException { BufferedWriter outTemp = null; try {/* ww w . j a va 2s.c om*/ DBCollection col = new DBCollection(this.DBURI, this.systemDbCollection + type, this.DBuser, this.DBpassword); String collectionPath = UtilsQueries.getPathforFile(col, id + ".xml", id.split(type)[1]); col = new DBCollection(this.DBURI, collectionPath, this.DBuser, this.DBpassword); DBFile dbf = col.getFile(id + ".xml"); String isWritable = "true"; if (GetEntityCategory.getEntityCategory(type).equals("primary")) { isWritable = dbf .queryString("//admin/write='" + username + "'" + "or //admin/status='published'")[0]; } //check for each file if user has writes(only if type of file is primary) if (isWritable.equals("true")) { String xmlToString = dbf.getXMLAsString(); xmlToString = "<?xml version=\"1.0\"?>" + "\n" + xmlToString; File file = new File(filePath + System.getProperty("file.separator") + id + ".xml"); outTemp = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(filePath + System.getProperty("file.separator") + id + ".xml"), "UTF-8")); outTemp.write(xmlToString); outTemp.close(); /*Remove admin part from output xml*/ Document doc = ParseXMLFile .parseFile(filePath + System.getProperty("file.separator") + id + ".xml"); Element root = doc.getDocumentElement(); String rootName = root.getTagName(); String extention = ".xml"; if (rootName.equals("x3ml")) { File x3ml = new File(filePath + System.getProperty("file.separator") + id + ".x3ml"); file.renameTo(x3ml); extention = ".x3ml"; } Node admin = Utils.removeNode(root, "admin", true); // Node admin = root.getElementsByTagName("admin").item(0); // root.removeChild(admin); ParseXMLFile.saveXMLDocument(filePath + System.getProperty("file.separator") + id + extention, doc); } } catch (IOException ex) { } }