/**
   * 通过XSD(XML Schema)校验XML
   *
   * @throws FileNotFoundException
   */
  public boolean validateXMLByXSD(String testXSD, String xmlFileName) throws FileNotFoundException {
    //        String xmlFileName = "Q:\\_dev_stu\\xsdtest\\src\\note.xml";
    String xsdFileName = "E:/datashare/" + testXSD;
    FileInputStream fls = new FileInputStream(new File(xmlFileName));
    try {

      // 创建默认的XML错误处理器
      XMLErrorHandler errorHandler = new XMLErrorHandler();
      // 获取基于 SAX 的解析器的实例
      SAXParserFactory factory = SAXParserFactory.newInstance();
      // 解析器在解析时验证 XML 内容。
      factory.setValidating(true);
      // 指定由此代码生成的解析器将提供对 XML 名称空间的支持。
      factory.setNamespaceAware(true);
      // 使用当前配置的工厂参数创建 SAXParser 的一个新实例。
      SAXParser parser = factory.newSAXParser();
      // 创建一个读取工具
      SAXReader xmlReader = new SAXReader();
      // 获取要校验xml文档实例
      Document xmlDocument = (Document) xmlReader.read(fls);
      // 设置 XMLReader 的基础实现中的特定属性。核心功能和属性列表可以在
      // [url]http://sax.sourceforge.net/?selected=get-set[/url] 中找到。
      parser.setProperty(
          "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
          "http://www.w3.org/2001/XMLSchema");
      parser.setProperty(
          "http://java.sun.com/xml/jaxp/properties/schemaSource", "file:" + xsdFileName);
      // 创建一个SAXValidator校验工具,并设置校验工具的属性
      SAXValidator validator = new SAXValidator(parser.getXMLReader());
      // 设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。
      validator.setErrorHandler(errorHandler);
      // 校验
      validator.validate(xmlDocument);

      XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
      // 如果错误信息不为空,说明校验失败,打印错误信息
      if (errorHandler.getErrors().hasContent()) {
        System.out.println("XML文件校验失败!");
        writer.write(errorHandler.getErrors());
        return false;
      } else {
        System.out.println("XML文件校验成功!");
        return true;
      }
    } catch (Exception ex) {
      System.out.println(
          "XML文件: " + xmlFileName + " 通过XSD文件:" + xsdFileName + "检验失败。\n原因: " + ex.getMessage());
      // ex.printStackTrace();
      return false;
    } finally {
      try {
        fls.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
  private static Document doParse(
      final Configuration configuration,
      final String documentName,
      final TemplatePreprocessingReader reader,
      final SAXParser saxParser)
      throws IOException, SAXException {

    final InputSource inputSource = new InputSource(reader);

    final XmlSAXHandler handler =
        new XmlSAXHandler(documentName, new EntityResolver(configuration), ErrorHandler.INSTANCE);

    saxParser.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
    saxParser.setProperty("http://xml.org/sax/properties/declaration-handler", handler);

    saxParser.parse(inputSource, handler);

    final String docTypeClause = reader.getDocTypeClause();
    final String docTypeRootElementName = handler.getDocTypeRootElementName();
    final String docTypePublicId = handler.getDocTypePublicId();
    final String docTypeSystemId = handler.getDocTypeSystemId();

    // The DOCTYPE root element name could be null if we are parsing
    // a non-complete document, a fragment, without a DOCTYPE declaration.
    final DocType docType =
        (docTypeRootElementName != null
            ? new DocType(docTypeRootElementName, docTypePublicId, docTypeSystemId, docTypeClause)
            : null);

    final List<Node> rootNodes = handler.getRootNodes();

    final String xmlVersion = handler.getXmlVersion();
    final String xmlEncoding = handler.getXmlEncoding();
    final boolean xmlStandalone = handler.isXmlStandalone();

    final Document document = new Document(documentName, docType);

    if (xmlVersion != null) {
      document.setNodeProperty(Node.NODE_PROPERTY_XML_VERSION, xmlVersion);
    }

    if (xmlEncoding != null) {
      document.setNodeProperty(Node.NODE_PROPERTY_XML_ENCODING, xmlEncoding);
    }

    if (xmlStandalone) {
      document.setNodeProperty(Node.NODE_PROPERTY_XML_STANDALONE, Boolean.TRUE);
    }

    document.setChildren(rootNodes);

    return document;
  }
Example #3
0
  /**
   * Configure schema validation as recommended by the JAXP 1.2 spec. The <code>properties</code>
   * object may contains information about the schema local and language.
   *
   * @param properties parser optional info
   */
  private static void configureOldXerces(SAXParser parser, Properties properties)
      throws ParserConfigurationException, SAXNotSupportedException {

    String schemaLocation = (String) properties.get("schemaLocation");
    String schemaLanguage = (String) properties.get("schemaLanguage");

    try {
      if (schemaLocation != null) {
        parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage);
        parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation);
      }
    } catch (SAXNotRecognizedException e) {
      log.info(parser.getClass().getName() + ": " + e.getMessage() + " not supported.");
    }
  }
  public static ParentalControlConcern parse(File file) {

    try {

      log.info("Parsing '" + file.getCanonicalPath() + "'...");
      SAXParserFactory factory = SAXParserFactory.newInstance();
      factory.setNamespaceAware(true);
      factory.setValidating(true);
      SAXParser parser = factory.newSAXParser();
      parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
      ParentalControlConcernHandler handler = new ParentalControlConcernHandler();
      parser.parse(file, handler);
      log.info("Parsed '" + file.getCanonicalPath() + "'");
      return handler.result;

    } catch (SAXParseException ex) {

      log.error(
          "Could not validate the parental control concern XML file!  Validation error follows.");
      log.error(ex.getMessage());
      ex.printStackTrace();
      return null;

    } catch (Exception ex) {

      log.error(ex);
      return null;
    }
  }
Example #5
0
  private SAXParser getParser() throws BuildException {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    File schemaSource = new File(schemaDir + File.separatorChar + "web-facesconfig_1_2.xsd");
    try {
      SAXParser parser = factory.newSAXParser();
      parser.setProperty(
          "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
          "http://www.w3.org/2001/XMLSchema");
      parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaSource);
      return parser;
    } catch (Exception e) {
      throw new BuildException(e);
    }
  } // END getParser
Example #6
0
  public void convert(Reader reader, OutputStream finf) throws Exception {
    InputSource is = new InputSource(reader);

    SAXParser saxParser = getParser();
    SAXDocumentSerializer documentSerializer = getSerializer(finf);

    saxParser.setProperty("http://xml.org/sax/properties/lexical-handler", documentSerializer);
    saxParser.parse(is, documentSerializer);
  }
  /**
   * Parses the given xml stream and returns a list of the suppression rules contained.
   *
   * @param inputStream an InputStream containing suppression rues
   * @return a list of suppression rules
   * @throws SuppressionParseException if the xml cannot be parsed
   */
  public List<SuppressionRule> parseSuppressionRules(InputStream inputStream)
      throws SuppressionParseException, SAXException {
    try {
      final InputStream schemaStream =
          this.getClass()
              .getClassLoader()
              .getResourceAsStream("schema/dependency-suppression.1.1.xsd");
      final SuppressionHandler handler = new SuppressionHandler();
      final SAXParserFactory factory = SAXParserFactory.newInstance();
      factory.setNamespaceAware(true);
      factory.setValidating(true);
      final SAXParser saxParser = factory.newSAXParser();
      saxParser.setProperty(
          SuppressionParser.JAXP_SCHEMA_LANGUAGE, SuppressionParser.W3C_XML_SCHEMA);
      saxParser.setProperty(SuppressionParser.JAXP_SCHEMA_SOURCE, new InputSource(schemaStream));
      final XMLReader xmlReader = saxParser.getXMLReader();
      xmlReader.setErrorHandler(new SuppressionErrorHandler());
      xmlReader.setContentHandler(handler);

      final Reader reader = new InputStreamReader(inputStream, "UTF-8");
      final InputSource in = new InputSource(reader);
      // in.setEncoding("UTF-8");

      xmlReader.parse(in);

      return handler.getSuppressionRules();
    } catch (ParserConfigurationException ex) {
      LOGGER.debug("", ex);
      throw new SuppressionParseException(ex);
    } catch (SAXException ex) {
      if (ex.getMessage().contains("Cannot find the declaration of element 'suppressions'.")) {
        throw ex;
      } else {
        LOGGER.debug("", ex);
        throw new SuppressionParseException(ex);
      }
    } catch (FileNotFoundException ex) {
      LOGGER.debug("", ex);
      throw new SuppressionParseException(ex);
    } catch (IOException ex) {
      LOGGER.debug("", ex);
      throw new SuppressionParseException(ex);
    }
  }
  protected static SAXParser createParser() throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(true);
    SAXParser parser = spf.newSAXParser();
    parser.setProperty(
        "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
        "http://www.w3.org/2001/XMLSchema");

    return parser;
  }
  private static void setupValidationParser() throws Exception {
    // load validation XSD for validation using parser
    InputStream schemaStream =
        ValidationManagerImpl.class.getClassLoader().getResourceAsStream("komodoValidation.xsd");
    if (schemaStream == null) {
      throw new IllegalStateException("Validation schema file does not exist"); // $NON-NLS-1$
    }

    // create parser
    final SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(true);

    _parser = factory.newSAXParser();
    _parser.setProperty(
        "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
        "http://www.w3.org/2001/XMLSchema"); //$NON-NLS-1$ //$NON-NLS-2$
    _parser.setProperty(
        "http://java.sun.com/xml/jaxp/properties/schemaSource", schemaStream); // $NON-NLS-1$
  }
  /**
   * Parses the given xml stream and returns a list of the suppression rules contained.
   *
   * @param inputStream an InputStream containing suppression rues
   * @return a list of suppression rules
   * @throws SuppressionParseException if the xml cannot be parsed
   */
  private List<SuppressionRule> parseOldSuppressionRules(InputStream inputStream)
      throws SuppressionParseException {
    try {
      final InputStream schemaStream =
          this.getClass().getClassLoader().getResourceAsStream("schema/suppression.xsd");
      final SuppressionHandler handler = new SuppressionHandler();
      final SAXParserFactory factory = SAXParserFactory.newInstance();
      factory.setNamespaceAware(true);
      factory.setValidating(true);
      final SAXParser saxParser = factory.newSAXParser();
      saxParser.setProperty(
          SuppressionParser.JAXP_SCHEMA_LANGUAGE, SuppressionParser.W3C_XML_SCHEMA);
      saxParser.setProperty(SuppressionParser.JAXP_SCHEMA_SOURCE, new InputSource(schemaStream));
      final XMLReader xmlReader = saxParser.getXMLReader();
      xmlReader.setErrorHandler(new SuppressionErrorHandler());
      xmlReader.setContentHandler(handler);

      final Reader reader = new InputStreamReader(inputStream, "UTF-8");
      final InputSource in = new InputSource(reader);
      // in.setEncoding("UTF-8");

      xmlReader.parse(in);

      return handler.getSuppressionRules();
    } catch (ParserConfigurationException ex) {
      LOGGER.debug("", ex);
      throw new SuppressionParseException(ex);
    } catch (SAXException ex) {
      LOGGER.debug("", ex);
      throw new SuppressionParseException(ex);
    } catch (FileNotFoundException ex) {
      LOGGER.debug("", ex);
      throw new SuppressionParseException(ex);
    } catch (IOException ex) {
      LOGGER.debug("", ex);
      throw new SuppressionParseException(ex);
    }
  }
Example #11
0
 public Phylogeny[] parse() throws IOException, PhylogenyParserException {
   reset();
   final TolXmlHandler handler = new TolXmlHandler();
   final SAXParserFactory factory = SAXParserFactory.newInstance();
   factory.setNamespaceAware(true);
   try {
     if (!ForesterUtil.isEmpty(getSchemaLocation())) {
       factory.setFeature(SAX_FEATURES_VALIDATION, true);
       factory.setFeature(APACHE_FEATURES_VALIDATION_SCHEMA, true);
       factory.setFeature(APACHE_FEATURES_VALIDATION_SCHEMA_FULL, true);
     }
   } catch (final SAXNotRecognizedException e) {
     e.printStackTrace();
     throw new PhylogenyParserException("sax not recognized exception: " + e.getMessage());
   } catch (final SAXNotSupportedException e) {
     e.printStackTrace();
     throw new PhylogenyParserException("sax not supported exception: " + e.getMessage());
   } catch (final ParserConfigurationException e) {
     e.printStackTrace();
     throw new PhylogenyParserException("parser _configuration exception: " + e.getMessage());
   } catch (final Exception e) {
     e.printStackTrace();
     throw new PhylogenyParserException("error while configuring sax parser: " + e.getMessage());
   }
   try {
     final SAXParser parser = factory.newSAXParser();
     if (!ForesterUtil.isEmpty(getSchemaLocation())) {
       parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
       parser.setProperty(JAXP_SCHEMA_SOURCE, getSchemaLocation());
       parser.setProperty(APACHE_PROPERTIES_SCHEMA_EXTERNAL_LOCATION, getSchemaLocation());
     }
     final XMLReader xml_reader = parser.getXMLReader();
     xml_reader.setContentHandler(handler);
     xml_reader.setErrorHandler(new TolParserErrorHandler());
     if (getSource() instanceof File) {
       if (!getSource().toString().toLowerCase().endsWith(".zip")) {
         xml_reader.parse(new InputSource(new FileReader((File) getSource())));
       } else {
         final Reader reader = getReaderFromZipFile();
         if (reader == null) {
           throw new PhylogenyParserException(
               "Zip file \"" + getSource() + "\" appears not to contain any entries");
         }
         xml_reader.parse(new InputSource(reader));
       }
     } else if (getSource() instanceof InputSource) {
       xml_reader.parse((InputSource) getSource());
     } else if (getSource() instanceof InputStream) {
       if (!isZippedInputstream()) {
         final InputStream is = (InputStream) getSource();
         final Reader reader = new InputStreamReader(is);
         xml_reader.parse(new InputSource(reader));
       } else {
         final ZipInputStream zip_is = new ZipInputStream((InputStream) getSource());
         zip_is.getNextEntry();
         final Reader reader = new InputStreamReader(zip_is);
         if (reader == null) {
           throw new PhylogenyParserException(
               "Zip input stream \"" + getSource() + "\" appears not to contain any data");
         }
         xml_reader.parse(new InputSource(reader));
       }
     } else if (getSource() instanceof String) {
       final File file = new File(getSource().toString());
       final Reader reader = new FileReader(file);
       xml_reader.parse(new InputSource(reader));
     } else if (getSource() instanceof StringBuffer) {
       final StringReader string_reader = new StringReader(getSource().toString());
       xml_reader.parse(new InputSource(string_reader));
     } else {
       throw new PhylogenyParserException(
           "attempt to parse object of unsupported type: \"" + getSource().getClass() + "\"");
     }
   } catch (final SAXException sax_exception) {
     throw new PhylogenyParserException(
         "Failed to parse [" + getSource() + "]: " + sax_exception.getMessage());
   } catch (final ParserConfigurationException parser_config_exception) {
     throw new PhylogenyParserException(
         "Failed to parse ["
             + getSource()
             + "] Problem with xml parser _configuration: "
             + parser_config_exception.getMessage());
   } catch (final IOException e) {
     throw new PhylogenyParserException(
         "Problem with input source [" + getSource() + "]: \n" + e.getMessage());
   } catch (final Exception e) {
     e.printStackTrace();
     throw new PhylogenyParserException(
         "Failed to parse [" + getSource() + "]: " + e.getMessage());
   } catch (final Error err) {
     err.printStackTrace();
     throw new PhylogenyParserException("Severe error: " + err.getMessage());
   }
   final Phylogeny[] ps = new Phylogeny[handler.getPhylogenies().size()];
   int i = 0;
   for (final Phylogeny phylogeny : handler.getPhylogenies()) {
     ps[i++] = phylogeny;
   }
   return ps;
 }