Example #1
0
 @SuppressWarnings("unchecked")
 public static <T> T unmarshal(final InputStream in) throws IOException {
   final Unmarshaller unmarshaller = SardineUtil.createUnmarshaller();
   try {
     final XMLReader reader = XMLReaderFactory.createXMLReader();
     try {
       reader.setFeature("http://xml.org/sax/features/external-general-entities", Boolean.FALSE);
     } catch (final SAXException e) {; // Not all parsers will support this attribute
     }
     try {
       reader.setFeature("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE);
     } catch (final SAXException e) {; // Not all parsers will support this attribute
     }
     try {
       reader.setFeature(
           "http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE);
     } catch (final SAXException e) {; // Not all parsers will support this attribute
     }
     try {
       reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
     } catch (final SAXException e) {; // Not all parsers will support this attribute
     }
     return (T) unmarshaller.unmarshal(new SAXSource(reader, new InputSource(in)));
   } catch (final SAXException e) {
     throw new RuntimeException(e.getMessage(), e);
   } catch (final JAXBException e) {
     // Server does not return any valid WebDAV XML that matches our JAXB context
     final IOException failure = new IOException("Not a valid DAV response");
     // Backward compatibility
     failure.initCause(e);
     throw failure;
   }
 }
Example #2
0
  private XMLReader getXMLReader(ContentHandler contentHandler, ErrorHandler errorHandler)
      throws ParserConfigurationException, SAXException {

    // setup sax factory ; be sure just one instance!
    SAXParserFactory saxFactory = SAXParserFactory.newInstance();

    // Enable validation stuff
    saxFactory.setValidating(true);
    saxFactory.setNamespaceAware(true);

    // Create xml reader
    SAXParser saxParser = saxFactory.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();

    // Setup xmlreader
    xmlReader.setProperty(
        XMLReaderObjectFactory.APACHE_PROPERTIES_INTERNAL_GRAMMARPOOL, grammarPool);

    xmlReader.setFeature(Namespaces.SAX_VALIDATION, true);
    xmlReader.setFeature(Namespaces.SAX_VALIDATION_DYNAMIC, false);
    xmlReader.setFeature(XMLReaderObjectFactory.APACHE_FEATURES_VALIDATION_SCHEMA, true);
    xmlReader.setFeature(XMLReaderObjectFactory.APACHE_PROPERTIES_LOAD_EXT_DTD, true);
    xmlReader.setFeature(Namespaces.SAX_NAMESPACES_PREFIXES, true);

    xmlReader.setContentHandler(contentHandler);
    xmlReader.setErrorHandler(errorHandler);

    return xmlReader;
  }
Example #3
0
  public Struct validate(InputSource xml) throws PageException {
    CFMLEngine engine = CFMLEngineFactory.getInstance();
    warnings = engine.getCreationUtil().createArray();
    errors = engine.getCreationUtil().createArray();
    fatals = engine.getCreationUtil().createArray();

    try {
      XMLReader parser = new XMLUtilImpl().createXMLReader("org.apache.xerces.parsers.SAXParser");
      parser.setContentHandler(this);
      parser.setErrorHandler(this);
      parser.setEntityResolver(this);
      parser.setFeature("http://xml.org/sax/features/validation", true);
      parser.setFeature("http://apache.org/xml/features/validation/schema", true);
      parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
      // if(!validateNamespace)
      if (!Util.isEmpty(strSchema))
        parser.setProperty(
            "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
            strSchema);
      parser.parse(xml);
    } catch (SAXException e) {
    } catch (IOException e) {
      throw engine.getExceptionUtil().createXMLException(e.getMessage());
    }

    // result
    Struct result = engine.getCreationUtil().createStruct();
    result.setEL("warnings", warnings);
    result.setEL("errors", errors);
    result.setEL("fatalerrors", fatals);
    result.setEL("status", engine.getCastUtil().toBoolean(!hasErrors));
    release();
    return result;
  }
  /**
   * Reads malformed XML from the InputStream original and returns a new InputStream which can be
   * used to read a well-formed version of the input
   *
   * @param original original input
   * @return an {@link InputStream} which can be used to read a well-formed version of the input XML
   * @throws ParseException if an exception occurs while parsing the input
   */
  public static InputStream xmlizeInputStream(InputStream original) throws ParseException {
    try {
      ByteArrayOutputStream out = new ByteArrayOutputStream();

      HTMLSchema schema = new HTMLSchema();
      XMLReader reader = new Parser();

      // TODO walk through the javadoc and tune more settings
      // see tagsoup javadoc for details
      reader.setProperty(Parser.schemaProperty, schema);
      reader.setFeature(Parser.bogonsEmptyFeature, false);
      reader.setFeature(Parser.ignorableWhitespaceFeature, true);
      reader.setFeature(Parser.ignoreBogonsFeature, false);

      Writer writeger = new OutputStreamWriter(out);
      XMLWriter x = new XMLWriter(writeger);

      reader.setContentHandler(x);

      InputSource s = new InputSource(original);

      reader.parse(s);
      return new ByteArrayInputStream(out.toByteArray());
    } catch (SAXException e) {
      throw new ParseException(R("PBadXML"), e);
    } catch (IOException e) {
      throw new ParseException(R("PBadXML"), e);
    }
  }
  @Override
  public void internalParse(InputStream input) {
    try {
      try {
        Thread.sleep(4000);
      } catch (Throwable t) {

      }

      SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
      saxParserFactory.setValidating(false);
      SAXParser saxParser = saxParserFactory.newSAXParser();
      XMLReader xmlReader = saxParser.getXMLReader();
      xmlReader.setFeature("http://xml.org/sax/features/validation", false);
      xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

      ZipInputStream zis = new ZipInputStream(input);
      ZipEntry ze = zis.getNextEntry();
      while (ze != null && !ze.getName().equals("content.xml")) {
        ze = zis.getNextEntry();
      }

      OpenOfficeContentHandler contentHandler = new OpenOfficeContentHandler();
      xmlReader.setContentHandler(contentHandler);
      try {
        xmlReader.parse(new InputSource(zis));
      } finally {
        zis.close();
      }

      content.append(StringUtil.writeToString(new StringReader(contentHandler.getContent())));
    } catch (Exception e) {
      log.warn("Failed to extract OpenOffice text content", e);
    }
  }
Example #6
0
  public static void main(String argv[]) {
    if (argv.length != 1) {
      System.err.println("Usage: java Validate [filename.xml | URLToFile]");
      System.exit(1);
    }

    try {
      // get a parser
      XMLReader reader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");

      // request validation
      reader.setFeature("http://xml.org/sax/features/validation", true);
      reader.setFeature("http://apache.org/xml/features/validation/schema", true);
      reader.setErrorHandler(new Validate());

      // associate an InputSource object with the file name or URL
      InputSource inputSource = new InputSource(argv[0]);

      // go ahead and parse
      reader.parse(inputSource);
    } catch (org.xml.sax.SAXException e) {
      System.out.println("Error in parsing " + e);
      valid = false;

    } catch (java.io.IOException e) {
      System.out.println("Error in I/O " + e);
      System.exit(0);
    }
    System.out.println("Valid Document is " + valid);
  }
Example #7
0
  /** Default constructor of MapLinksReader class. */
  public MapLinksReader() {
    super();
    map = new HashMap<String, Map<String, String>>();
    ancestorList = new ArrayList<String>(INT_16);
    matchList = new ArrayList<String>(INT_16);
    indexEntries = new StringBuffer(INT_1024);
    firstMatchElement = null;
    lastMatchElement = new HashSet<String>();
    level = 0;
    match = false;
    validHref = true;
    needResolveEntity = false;
    topicPath = null;
    inputFile = null;

    try {
      reader = StringUtils.getXMLReader();
      reader.setContentHandler(this);
      reader.setProperty(LEXICAL_HANDLER_PROPERTY, this);
      // Added by william on 2009-11-8 for ampbug:2893664 start
      reader.setFeature("http://apache.org/xml/features/scanner/notify-char-refs", true);
      reader.setFeature("http://apache.org/xml/features/scanner/notify-builtin-refs", true);
      // Added by william on 2009-11-8 for ampbug:2893664 end
      reader.setFeature("http://xml.org/sax/features/namespaces", false);
    } catch (final Exception e) {
      logger.logException(e);
    }
  }
 private void init(XMLReader expatReader) throws SAXException {
   if (expatReader == null) throw new NullPointerException("expatReader cannot be null");
   this.expatReader = expatReader;
   expatReader.setContentHandler(handler);
   expatReader.setFeature(FEATURE_NAMESPACE_PREFIXES, true);
   expatReader.setFeature(FEATURE_NAMESPACES, false);
 }
Example #9
0
  /**
   * parse XML/HTML String to a XML DOM representation
   *
   * @param xml XML InputSource
   * @param isHtml is a HTML or XML Object
   * @return parsed Document
   * @throws SAXException
   * @throws IOException
   * @throws ParserConfigurationException
   */
  public static final Document parse(InputSource xml, InputSource validator, boolean isHtml)
      throws SAXException, IOException {

    if (!isHtml) {
      // try to load org.apache.xerces.jaxp.DocumentBuilderFactoryImpl, oracle impl sucks
      DocumentBuilderFactory factory = null;
      try {
        factory = new DocumentBuilderFactoryImpl();
      } catch (Throwable t) {
        factory = DocumentBuilderFactory.newInstance();
      }

      // print.o(factory);
      if (validator == null) {
        XMLUtil.setAttributeEL(factory, XMLConstants.NON_VALIDATING_DTD_EXTERNAL, Boolean.FALSE);
        XMLUtil.setAttributeEL(factory, XMLConstants.NON_VALIDATING_DTD_GRAMMAR, Boolean.FALSE);
      } else {
        XMLUtil.setAttributeEL(factory, XMLConstants.VALIDATION_SCHEMA, Boolean.TRUE);
        XMLUtil.setAttributeEL(factory, XMLConstants.VALIDATION_SCHEMA_FULL_CHECKING, Boolean.TRUE);
      }

      factory.setNamespaceAware(true);
      factory.setValidating(validator != null);

      try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new XMLEntityResolverDefaultHandler(validator));
        builder.setErrorHandler(new ThrowingErrorHandler(true, true, false));
        return builder.parse(xml);
      } catch (ParserConfigurationException e) {
        throw new SAXException(e);
      }

      /*DOMParser parser = new DOMParser();
      print.out("parse");
      parser.setEntityResolver(new XMLEntityResolverDefaultHandler(validator));
      parser.parse(xml);
      return parser.getDocument();*/
    }

    XMLReader reader = new Parser();
    reader.setFeature(Parser.namespacesFeature, true);
    reader.setFeature(Parser.namespacePrefixesFeature, true);

    try {
      Transformer transformer = TransformerFactory.newInstance().newTransformer();

      DOMResult result = new DOMResult();
      transformer.transform(new SAXSource(reader, xml), result);
      return XMLUtil.getDocument(result.getNode());
    } catch (Exception e) {
      throw new SAXException(e);
    }
  }
Example #10
0
  /** Constructor. */
  public ConrefPushReader() {
    pushtable = new Hashtable<>();
    try {
      reader = XMLUtils.getXMLReader();
      reader.setFeature(FEATURE_NAMESPACE_PREFIX, false);
      reader.setFeature(FEATURE_NAMESPACE, true);
      reader.setContentHandler(this);
    } catch (final Exception e) {
      throw new RuntimeException("Failed to initialize XML parser: " + e.getMessage(), e);
    }

    final DocumentBuilder documentBuilder = XMLUtils.getDocumentBuilder();
    pushDocument = documentBuilder.newDocument();
  }
  /*
   * (non-Javadoc)
   *
   * @see org.exoplatform.services.document.DocumentReader#getContentAsText(java.
   *      io.InputStream)
   */
  public String getContentAsText(InputStream is) throws IOException, DocumentReadException {
    if (is == null) {
      throw new IllegalArgumentException("InputStream is null.");
    }
    try {

      ZipInputStream zis = new ZipInputStream(is);
      try {
        ZipEntry ze = zis.getNextEntry();

        if (ze == null) {
          return "";
        }

        while (!ze.getName().equals("content.xml")) {
          ze = zis.getNextEntry();
        }

        OpenOfficeContentHandler contentHandler = new OpenOfficeContentHandler();
        XMLReader xmlReader = SAXHelper.newXMLReader();
        xmlReader.setFeature("http://xml.org/sax/features/validation", false);

        xmlReader.setFeature(
            "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        xmlReader.setContentHandler(contentHandler);
        xmlReader.parse(new InputSource(zis));
        return contentHandler.getContent();
      } finally {
        try {
          zis.close();
        } catch (IOException e) {
          if (LOG.isTraceEnabled()) {
            LOG.trace("An exception occurred: " + e.getMessage());
          }
        }
      }
    } catch (ParserConfigurationException e) {
      throw new DocumentReadException(e.getMessage(), e);
    } catch (SAXException e) {
      throw new DocumentReadException(e.getMessage(), e);
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        if (LOG.isTraceEnabled()) {
          LOG.trace("An exception occurred: " + e.getMessage());
        }
      }
    }
  }
  private void downloadAndExtract() throws MojoFailureException, MojoExecutionException {
    // if the output directory already exists, delete it
    if (outputDir.exists()) cleanOutputDirectory();

    // find the requested version in the download page to get a URL
    getLog().info("retrieving download list");
    final String downloadUrl;
    try {
      final String version = getApiDependency().getVersion();

      final XMLReader reader = new Parser();
      reader.setFeature(Parser.namespacesFeature, false);
      reader.setFeature(Parser.namespacePrefixesFeature, false);

      final Pattern pattern =
          Pattern.compile("/minecraftforge-src-[\\d.]+-" + Pattern.quote(version) + "\\.zip$");

      final FileListHandler handler = new FileListHandler(pattern);
      reader.setContentHandler(handler);

      reader.parse(new InputSource((new URL("http://files.minecraftforge.net/")).openStream()));

      downloadUrl = handler.downloadUrl;
    } catch (IOException caught) {
      throw new MojoFailureException("unable to download Forge release list", caught);
    } catch (Exception caught) {
      throw new MojoFailureException("unable to parse Forge release list", caught);
    }

    // download the Forge distribution to the output directory
    getLog().info("downloading " + downloadUrl);
    final File downloadFile =
        new File(outputDir, downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1));
    try {
      FileUtils.copyURLToFile(new URL(downloadUrl), downloadFile);
    } catch (IOException caught) {
      throw new MojoFailureException("unable to download Forge source release", caught);
    }

    // extract the distribution
    getLog().info("extracting distribution");
    try {
      final Expand zip = new Expand();
      zip.setSrc(downloadFile);
      zip.setDest(outputDir);
      zip.execute();
    } catch (Exception caught) {
      throw new MojoFailureException("unable to extract Forge release", caught);
    }
  }
 /** Turns off expansion of external entities. */
 public Object unmarshal(InputSource source) throws JAXBException {
   try {
     SAXParserFactory spf = SAXParserFactory.newInstance();
     SAXParser sp = spf.newSAXParser();
     XMLReader xmlReader = sp.getXMLReader();
     xmlReader.setFeature("http://xml.org/sax/features/validation", false);
     xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
     SAXSource saxSource = new SAXSource(xmlReader, source);
     return delegate.unmarshal(saxSource);
   } catch (SAXException e) {
     throw new JAXBException(e);
   } catch (ParserConfigurationException e) {
     throw new JAXBException(e);
   }
 }
Example #14
0
 /**
  * Starts the reading of the CML file. Whenever a new Molecule is read, a event is thrown to the
  * ReaderListener.
  */
 public void process() throws CDKException {
   logger.debug("Started parsing from input...");
   try {
     parser.setFeature("http://xml.org/sax/features/validation", false);
     logger.info("Deactivated validation");
   } catch (SAXException e) {
     logger.warn("Cannot deactivate validation.");
   }
   parser.setContentHandler(new EventCMLHandler(this, builder));
   parser.setEntityResolver(new CMLResolver());
   parser.setErrorHandler(new CMLErrorHandler());
   try {
     logger.debug("Parsing from Reader");
     parser.parse(new InputSource(input));
   } catch (IOException e) {
     String error = "Error while reading file: " + e.getMessage();
     logger.error(error);
     logger.debug(e);
     throw new CDKException(error, e);
   } catch (SAXParseException saxe) {
     SAXParseException spe = (SAXParseException) saxe;
     String error = "Found well-formedness error in line " + spe.getLineNumber();
     logger.error(error);
     logger.debug(saxe);
     throw new CDKException(error, saxe);
   } catch (SAXException saxe) {
     String error = "Error while parsing XML: " + saxe.getMessage();
     logger.error(error);
     logger.debug(saxe);
     throw new CDKException(error, saxe);
   }
 }
Example #15
0
 static {
   try {
     xmlReader = XMLReaderFactory.createXMLReader();
     xmlReader.setFeature("http://xml.org/sax/features/validation", false);
     if (false) {
       // FIXME AK: we need  real handling for the normal case (HTML->FOP XML)
       EntityResolver resolver =
           new EntityResolver() {
             public InputSource resolveEntity(String arg0, String arg1)
                 throws SAXException, IOException {
               log.info(arg0 + "::" + arg1);
               InputSource source =
                   new InputSource(
                       (new URL("file:///Volumes/Home/Desktop/dtd/xhtml1-transitional.dtd"))
                           .openStream());
               source.setSystemId(arg1);
               return source;
             }
           };
       xmlReader.setEntityResolver(resolver);
     }
   } catch (SAXException e) {
     e.printStackTrace();
   }
 }
Example #16
0
  /**
   * Parse the input source into a set of modifications.
   *
   * @param is
   * @return an array of type Modification
   * @throws ParserConfigurationException
   * @throws IOException
   * @throws SAXException
   */
  public Modification[] parse(InputSource is)
      throws ParserConfigurationException, IOException, SAXException {
    final XMLReader reader = broker.getBrokerPool().getParserPool().borrowXMLReader();
    try {
      reader.setProperty(Namespaces.SAX_LEXICAL_HANDLER, this);
      reader.setFeature(Namespaces.SAX_NAMESPACES, true);
      reader.setFeature(Namespaces.SAX_NAMESPACES_PREFIXES, false);
      reader.setContentHandler(this);

      reader.parse(is);
      final Modification mods[] = new Modification[modifications.size()];
      return modifications.toArray(mods);
    } finally {
      broker.getBrokerPool().getParserPool().returnXMLReader(reader);
    }
  }
Example #17
0
 /**
  * Sets the reader's named feature to the supplied value, only if the feature is not already set
  * to that value. This method does nothing if the feature is not known to the reader.
  *
  * @param reader the reader; may not be null
  * @param featureName the name of the feature; may not be null
  * @param value the value for the feature
  */
 void setFeature(XMLReader reader, String featureName, boolean value) {
   try {
     if (reader.getFeature(featureName) != value) {
       reader.setFeature(featureName, value);
     }
   } catch (SAXException e) {
     getLogger().warn(e, "Cannot set feature " + featureName);
   }
 }
 /** Constructor. */
 public SeparateChunkTopicParser() {
   super(true);
   try {
     reader = getXMLReader();
     reader.setContentHandler(this);
     reader.setFeature(FEATURE_NAMESPACE_PREFIX, true);
   } catch (final Exception e) {
     throw new RuntimeException("Failed to initialize XML parser: " + e.getMessage(), e);
   }
 }
Example #19
0
 protected final SAXParser createParser(SAXParserFactory parserFactory)
     throws ParserConfigurationException, SAXException {
   parserFactory.setNamespaceAware(true);
   final SAXParser parser = parserFactory.newSAXParser();
   final XMLReader reader = parser.getXMLReader();
   // reader.setProperty("http://xml.org/sax/properties/lexical-handler", this); //$NON-NLS-1$
   // disable DTD validation (bug 63625)
   try {
     //	be sure validation is "off" or the feature to ignore DTD's will not apply
     reader.setFeature("http://xml.org/sax/features/validation", false); // $NON-NLS-1$
     reader.setFeature(
         "http://apache.org/xml/features/nonvalidating/load-external-dtd", false); // $NON-NLS-1$
   } catch (SAXNotRecognizedException e) {
     // not a big deal if the parser does not recognize the features
   } catch (SAXNotSupportedException e) {
     // not a big deal if the parser does not support the features
   }
   return parser;
 }
  public <T> JAXBElement<T> unmarshal(Source source, Class<T> declaredType) throws JAXBException {
    if (source instanceof SAXSource) {
      try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xmlReader = sp.getXMLReader();
        xmlReader.setFeature("http://xml.org/sax/features/validation", false);
        xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
        ((SAXSource) source).setXMLReader(xmlReader);
        return delegate.unmarshal(source, declaredType);
      } catch (SAXException e) {
        throw new JAXBException(e);
      } catch (ParserConfigurationException e) {
        throw new JAXBException(e);
      }
    }

    throw new UnsupportedOperationException(errorMessage("Source, Class<T>"));
  }
  /**
   * start the parsing
   *
   * @param file to parse
   * @return Vector containing the test cases
   */
  public XMLcpimParser() {
    try {
      SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
      saxParser = saxParserFactory.newSAXParser().getXMLReader();
      saxParser.setContentHandler(this);
      saxParser.setFeature("http://xml.org/sax/features/validation", true);
      // parse the xml specification for the event tags.

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see org.exoplatform.services.document.DocumentReader#getProperties(java.io.
   *      InputStream)
   */
  public Properties getProperties(InputStream is) throws IOException, DocumentReadException {
    try {

      ZipInputStream zis = new ZipInputStream(is);
      try {
        ZipEntry ze = zis.getNextEntry();
        while (!ze.getName().equals("meta.xml")) {
          ze = zis.getNextEntry();
        }

        OpenOfficeMetaHandler metaHandler = new OpenOfficeMetaHandler();
        XMLReader xmlReader = SAXHelper.newXMLReader();

        xmlReader.setFeature("http://xml.org/sax/features/validation", false);
        xmlReader.setFeature(
            "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        xmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
        xmlReader.setContentHandler(metaHandler);
        xmlReader.parse(new InputSource(zis));
        return metaHandler.getProperties();
      } finally {
        zis.close();
      }
    } catch (ParserConfigurationException e) {
      throw new DocumentReadException(e.getMessage(), e);
    } catch (SAXException e) {
      throw new DocumentReadException(e.getMessage(), e);
    } finally {
      if (is != null)
        try {
          is.close();
        } catch (IOException e) {
          if (LOG.isTraceEnabled()) {
            LOG.trace("An exception occurred: " + e.getMessage());
          }
        }
    }
  }
Example #23
0
  public void parse(InputSource input) throws SAXException, IOException {
    try {
      SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
      XMLReader reader = parser.getXMLReader();

      reader.setFeature("http://xml.org/sax/features/namespaces", true);

      if (parser.getClass().getName().equals("org.apache.xerces.jaxp.SAXParserImpl")) {
        // disable DTD validate
        String feature = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
        reader.setFeature(feature, false);
      }

      reader.setContentHandler(this);
      reader.setErrorHandler(this);
      reader.setDTDHandler(this);
      reader.setEntityResolver(this);

      reader.parse(input);
    } catch (ParserConfigurationException e) {
      throw new RuntimeException(e);
    }
  }
Example #24
0
 public XMLPackager() throws ISOException {
   super();
   out = new ByteArrayOutputStream();
   p = new PrintStream(out);
   stk = new Stack();
   try {
     reader = ISOUtil.genXmlReader();
     reader.setFeature("http://xml.org/sax/features/validation", false);
     reader.setContentHandler(this);
     reader.setErrorHandler(this);
   } catch (Exception e) {
     throw new ISOException(e.toString());
   }
 }
 private static void parseMetadata(InputSource inputSource, MetadataReader handler) {
   try {
     final SAXParserFactory factory = SAXParserFactory.newInstance();
     final SAXParser parser = factory.newSAXParser();
     //			parser.setProperty("http://xml.org/sax/features/namespaces", new Boolean(true));
     XMLReader reader = parser.getXMLReader();
     reader.setFeature("http://xml.org/sax/features/namespaces", true);
     parser.parse(inputSource, handler);
   } catch (SAXException e) {
     Util.log(e, "error reading oaametadata");
   } catch (IOException e) {
     Util.log(e, "error reading oaametadata");
   } catch (ParserConfigurationException e) {
     Util.log(e, "error reading oaametadata");
   }
 }
 private Schema loadSchema(Resource[] resources, String schemaLanguage)
     throws IOException, SAXException {
   Assert.notEmpty(resources, "No resources given");
   Assert.hasLength(schemaLanguage, "No schema language provided");
   Source[] schemaSources = new Source[resources.length];
   XMLReader xmlReader = XMLReaderFactory.createXMLReader();
   xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
   for (int i = 0; i < resources.length; i++) {
     Assert.notNull(resources[i], "Resource is null");
     Assert.isTrue(resources[i].exists(), "Resource " + resources[i] + " does not exist");
     InputSource inputSource = SaxResourceUtils.createInputSource(resources[i]);
     schemaSources[i] = new SAXSource(xmlReader, inputSource);
   }
   SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
   return schemaFactory.newSchema(schemaSources);
 }
Example #27
0
 private XMLReader createXMLReader() throws SAXException {
   XMLReader reader;
   try {
     reader = XMLReaderFactory.createXMLReader();
   } catch (SAXException e) {
     reader =
         XMLReaderFactory.createXMLReader(
             System.getProperty("org.xml.sax.driver", "org.apache.crimson.parser.XMLReaderImpl"));
   }
   reader.setFeature("http://xml.org/sax/features/validation", true);
   GenericContentHandler handler = new GenericContentHandler();
   reader.setContentHandler(handler);
   reader.setErrorHandler(handler);
   reader.setEntityResolver(new GenericEntityResolver());
   return reader;
 }
  public static boolean needsInterning(XMLReader reader) {
    // attempt to set it to true, which could fail
    try {
      reader.setFeature("http://xml.org/sax/features/string-interning", true);
    } catch (SAXException e) {
      // if it fails that's fine. we'll work around on our side
    }

    try {
      if (reader.getFeature("http://xml.org/sax/features/string-interning"))
        return false; // no need for intern
    } catch (SAXException e) {
      // unrecognized/unsupported
    }
    // otherwise we need intern
    return true;
  }
Example #29
0
  @Test
  public void test() throws SAXException, IOException {
    XMLReader xmlReader = XMLReaderFactory.createXMLReader();
    xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    CssHandler handler = new CssHandler();
    handler
        .getNavigator()
        .register(
            "[attr]",
            new CssSelectorCallback() {

              @Override
              public void onStartChild(
                  CssNavigator handler,
                  CharSequence tag,
                  Map<CharSequence, CharSequence> attributes) {}

              @Override
              public void onEndChild(CssNavigator handler, CharSequence tag) {}

              @Override
              public void onCharacters(CssNavigator handler, CharSequence seq) {}

              @Override
              public void onStartMatching(
                  CssNavigator handler,
                  CharSequence tag,
                  Map<CharSequence, CharSequence> attributes) {
                assertTrue(attributes.containsKey("attr"));
                System.out.println(tag);
                System.out.println(attributes.toString());
              }

              @Override
              public void onEndMatching(CssNavigator handler, CharSequence tag) {}
            });

    xmlReader.setContentHandler(handler);
    xmlReader.parse(new InputSource(new StringReader(HIERACHICAL)));
  }
  /**
   * start the parsing
   *
   * @param file to parse
   * @return Vector containing the test cases
   */
  public XMLcpimParser(String fileLocation) {
    try {
      SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
      saxParser = saxParserFactory.newSAXParser().getXMLReader();
      saxParser.setContentHandler(this);
      saxParser.setFeature("http://xml.org/sax/features/validation", true);
      // parse the xml specification for the event tags.
      saxParser.parse(fileLocation);

    } catch (SAXParseException spe) {
      spe.printStackTrace();
    } catch (SAXException sxe) {
      sxe.printStackTrace();
    } catch (IOException ioe) {
      // I/O error
      ioe.printStackTrace();
    } catch (Exception pce) {
      // Parser with specified options can't be built
      pce.printStackTrace();
    }
  }