示例#1
0
 private SVNErrorMessage readData(
     InputStream is, String method, String path, DefaultHandler handler)
     throws FactoryConfigurationError, UnsupportedEncodingException, IOException {
   try {
     if (mySAXParser == null) {
       mySAXParser = getSAXParserFactory().newSAXParser();
     }
     XMLReader reader = new XMLReader(is);
     while (!reader.isClosed()) {
       org.xml.sax.XMLReader xmlReader = mySAXParser.getXMLReader();
       xmlReader.setContentHandler(handler);
       xmlReader.setDTDHandler(handler);
       xmlReader.setErrorHandler(handler);
       xmlReader.setEntityResolver(NO_ENTITY_RESOLVER);
       xmlReader.parse(new InputSource(reader));
     }
   } catch (SAXException e) {
     if (e instanceof SAXParseException) {
       if (handler instanceof DAVErrorHandler) {
         // failed to read svn-specific error, return null.
         return null;
       }
     } else if (e.getException() instanceof SVNException) {
       return ((SVNException) e.getException()).getErrorMessage();
     } else if (e.getCause() instanceof SVNException) {
       return ((SVNException) e.getCause()).getErrorMessage();
     }
     return SVNErrorMessage.create(
         SVNErrorCode.RA_DAV_REQUEST_FAILED,
         "Processing {0} request response failed: {1} ({2}) ",
         new Object[] {method, e.getMessage(), path});
   } catch (ParserConfigurationException e) {
     return SVNErrorMessage.create(
         SVNErrorCode.RA_DAV_REQUEST_FAILED,
         "XML parser configuration error while processing {0} request response: {1} ({2}) ",
         new Object[] {method, e.getMessage(), path});
   } catch (EOFException e) {
     // skip it.
   } finally {
     if (mySAXParser != null) {
       // to avoid memory leaks when connection is cached.
       org.xml.sax.XMLReader xmlReader = null;
       try {
         xmlReader = mySAXParser.getXMLReader();
       } catch (SAXException e) {
       }
       if (xmlReader != null) {
         xmlReader.setContentHandler(DEFAULT_SAX_HANDLER);
         xmlReader.setDTDHandler(DEFAULT_SAX_HANDLER);
         xmlReader.setErrorHandler(DEFAULT_SAX_HANDLER);
         xmlReader.setEntityResolver(NO_ENTITY_RESOLVER);
       }
     }
     myRepository.getDebugLog().flushStream(is);
   }
   return null;
 }
  @Test
  public void testParserHandling() throws Exception {
    final StringBuilder chars = new StringBuilder();
    XMLReader r = XMLReaderFactory.createXMLReader();
    r.setErrorHandler(
        new ErrorHandler() {
          public void warning(SAXParseException e) throws SAXException {
            throw e;
          }

          public void fatalError(SAXParseException e) throws SAXException {
            throw e;
          }

          public void error(SAXParseException e) throws SAXException {
            throw e;
          }
        });
    r.setContentHandler(
        new DefaultHandler() {
          @Override
          public void characters(char[] ch, int start, int length) throws SAXException {
            chars.append(ch, start, length);
          }
        });

    r.parse(new InputSource(new ByteArrayInputStream(utf8Xml)));
    assertThat(chars.toString()).isEqualTo(" \u0096 ");
  }
示例#3
0
  public void process(Exchange exchange) throws Exception {
    Jaxp11XMLReaderCreator xmlCreator = new Jaxp11XMLReaderCreator();
    DefaultValidationErrorHandler errorHandler = new DefaultValidationErrorHandler();

    PropertyMapBuilder mapBuilder = new PropertyMapBuilder();
    mapBuilder.put(ValidateProperty.XML_READER_CREATOR, xmlCreator);
    mapBuilder.put(ValidateProperty.ERROR_HANDLER, errorHandler);
    PropertyMap propertyMap = mapBuilder.toPropertyMap();

    Validator validator = getSchema().createValidator(propertyMap);

    Message in = exchange.getIn();
    SAXSource saxSource = in.getBody(SAXSource.class);
    if (saxSource == null) {
      Source source = exchange.getIn().getMandatoryBody(Source.class);
      saxSource = ExchangeHelper.convertToMandatoryType(exchange, SAXSource.class, source);
    }
    InputSource bodyInput = saxSource.getInputSource();

    // now lets parse the body using the validator
    XMLReader reader = xmlCreator.createXMLReader();
    reader.setContentHandler(validator.getContentHandler());
    reader.setDTDHandler(validator.getDTDHandler());
    reader.setErrorHandler(errorHandler);
    reader.parse(bodyInput);

    errorHandler.handleErrors(exchange, schema);
  }
示例#4
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);
   }
 }
示例#5
0
  @Override
  public boolean execute(Property inputProperty, Node outputNode, Context context)
      throws Exception {
    Binary binaryValue = inputProperty.getBinary();
    CheckArg.isNotNull(binaryValue, "binary");

    if (!outputNode.isNew()) {
      outputNode = outputNode.addNode(XmlLexicon.DOCUMENT);
    }

    XmlSequencerHandler sequencingHandler = new XmlSequencerHandler(outputNode, scoping);
    // Create the reader ...
    XMLReader reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(sequencingHandler);
    reader.setErrorHandler(sequencingHandler);
    // Ensure handler acting as entity resolver 2
    reader.setProperty(DECL_HANDLER_FEATURE, sequencingHandler);
    // Ensure handler acting as lexical handler
    reader.setProperty(LEXICAL_HANDLER_FEATURE, sequencingHandler);
    // Ensure handler acting as entity resolver 2
    setFeature(reader, ENTITY_RESOLVER_2_FEATURE, true);
    // Prevent loading of external DTDs
    setFeature(reader, LOAD_EXTERNAL_DTDS_FEATURE, false);
    // Prevent the resolving of DTD entities into fully-qualified URIS
    setFeature(reader, RESOLVE_DTD_URIS_FEATURE, false);
    // Parse XML document
    try (InputStream stream = binaryValue.getStream()) {
      reader.parse(new InputSource(stream));
    }
    return true;
  }
示例#6
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;
  }
示例#7
0
  /**
   * Read a simple XML file.
   *
   * @param source the SAX input source.
   * @param initialHandler the initial content handler.
   * @param warnings a warning set to store warning (cannot be <code>null</code>).
   * @throws IOException if an I/O exception occurs while reading.
   * @throws SAXException if e.g. malformed XML is encountered.
   */
  public static void readXML(InputSource source, ElementHandler initialHandler, WarningSet warnings)
      throws IOException, SAXException {

    DelegatorHandler xmlhandler = new DelegatorHandler(initialHandler, warnings);

    XMLReader reader = cache.createXMLReader();
    reader.setContentHandler(xmlhandler);
    reader.setErrorHandler(xmlhandler);
    try {
      reader.parse(source);
    } finally {
      reader.setContentHandler(null);
      reader.setErrorHandler(null);
      cache.releaseXMLReader(reader);
    }
  }
示例#8
0
  /**
   * Return whether the given string contains well-formed XML.
   *
   * @param xmlString string to check
   * @return true iif the given string contains well-formed XML
   */
  public static boolean isWellFormedXML(String xmlString) {

    // Empty string is never well-formed XML
    if (xmlString.trim().length() == 0) return false;

    try {
      final XMLReader xmlReader = newSAXParser(XMLUtils.ParserConfiguration.PLAIN).getXMLReader();
      xmlReader.setContentHandler(NULL_CONTENT_HANDLER);
      xmlReader.setEntityResolver(ENTITY_RESOLVER);
      xmlReader.setErrorHandler(
          new org.xml.sax.ErrorHandler() {
            public void error(SAXParseException exception) throws SAXException {
              throw exception;
            }

            public void fatalError(SAXParseException exception) throws SAXException {
              throw exception;
            }

            public void warning(SAXParseException exception) throws SAXException {}
          });
      xmlReader.parse(new InputSource(new StringReader(xmlString)));
      return true;
    } catch (Exception e) {
      // Ideally we would like the parser to not throw as this is time-consuming, but not sure how
      // to achieve that
      return false;
    }
  }
示例#9
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);
  }
示例#10
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;
  }
  public static BehavioralPatternsCatalog load(final Reader reader) {
    BehavioralPatternsCatalog catalog = null;

    try {
      final BehavioralPatternsCatalogSaxHandler handler = new BehavioralPatternsCatalogSaxHandler();

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

      final XMLReader xmlReader = factory.newSAXParser().getXMLReader();
      xmlReader.setContentHandler(handler);
      xmlReader.setErrorHandler(handler);
      xmlReader.setEntityResolver(handler);

      xmlReader.parse(new InputSource(reader));

      catalog = handler.getCatalog();

      reader.close();
    } catch (final SAXException e) {
      BehavioralAnalysisPlugin.logError("Error parsing Behavioral Patterns Catalog.", e);
    } catch (final ParserConfigurationException e) {
      BehavioralAnalysisPlugin.logError("Error parsing Behavioral Patterns Catalog.", e);
    } catch (final IOException e) {
      BehavioralAnalysisPlugin.logError("Error opening Behavioral Patterns Catalog.", e);
    }

    return catalog;
  }
示例#12
0
 protected void handleResponse(String outputFilename) throws Exception {
   FileSystemResultHandler handler = getXMLResultHandler();
   //    if (null==handler) throw new Exception("XML Result Handler not specified for " +
   // getClass().getName());
   if (null == handler) {
     {
     } // Logwriter.printOnConsole("+++todo - XML Result Handler not specified for " +
     // getClass().getName());
     return;
   }
   /*
    UTF8Tidy tidy = new UTF8Tidy();
    tidy.setFilename(outputFilename);
    tidy.execute();
   */
   XMLReader xr = getParser(false).getXMLReader();
   if (null == storable) storable = this;
   storable.throwOnFailure(false);
   handler.setStorable(storable);
   handler.setDatasource(getDatasource());
   xr.setContentHandler(handler);
   xr.setErrorHandler(handler);
   File xml = new File(outputFilename);
   FileReader r = new FileReader(xml);
   xr.parse(new InputSource(r));
   resetStorage();
   initializeStorage(handler.getResults());
 }
示例#13
0
  @Override
  public void read(final String filename) {
    if (matchList.isEmpty()) {
      throw new IllegalStateException("matchList not initialized");
    }

    match = false;
    needResolveEntity = true;
    inputFile = new File(filename);
    filePath = inputFile.getParent();
    inputFile.getPath();
    if (indexEntries.length() != 0) {
      // delete all the content in indexEntries
      indexEntries = new StringBuffer(INT_1024);
    }

    try {
      reader.setErrorHandler(new DITAOTXMLErrorHandler(filename, logger));
      final InputSource source =
          URIResolverAdapter.convertToInputSource(
              DitaURIResolverFactory.getURIResolver().resolve(filename, null));
      reader.parse(source);
    } catch (final Exception e) {
      logger.logException(e);
    }
  }
 /** Loads edits file, uses visitor to process all elements */
 public void loadEdits() throws IOException {
   try {
     XMLReader xr = XMLReaderFactory.createXMLReader();
     xr.setContentHandler(this);
     xr.setErrorHandler(this);
     xr.setDTDHandler(null);
     xr.parse(new InputSource(fileReader));
     visitor.close(null);
   } catch (SAXParseException e) {
     System.out.println(
         "XML parsing error: "
             + "\n"
             + "Line:    "
             + e.getLineNumber()
             + "\n"
             + "URI:     "
             + e.getSystemId()
             + "\n"
             + "Message: "
             + e.getMessage());
     visitor.close(e);
     throw new IOException(e.toString());
   } catch (SAXException e) {
     visitor.close(e);
     throw new IOException(e.toString());
   } catch (RuntimeException e) {
     visitor.close(e);
     throw e;
   } finally {
     fileReader.close();
   }
 }
示例#15
0
 public WikiXMLParser(Reader reader, IArticleFilter filter) throws SAXException {
   super();
   fArticleFilter = filter;
   fXMLReader = XMLReaderFactory.createXMLReader();
   fXMLReader.setContentHandler(this);
   fXMLReader.setErrorHandler(this);
   fReader = reader;
 }
示例#16
0
 private SAXSource createValidatingSource(
     InputSource in, PropertyMap properties, CountingErrorHandler ceh) throws SAXException {
   Validator validator = schematronSchema.createValidator(properties);
   XMLReaderCreator xrc = ValidateProperty.XML_READER_CREATOR.get(properties);
   XMLReader xr = xrc.createXMLReader();
   xr.setErrorHandler(ceh);
   return new SAXSource(new ValidateStage(xr, validator, ceh), in);
 }
  /**
   * Read urn.
   *
   * @param file the file
   * @return The URN specified in the METS file or null if the METS file doesn't specify an URN
   * @throws IOException Signals that an I/O exception has occurred.
   * @throws ParseException the parse exception
   * @author Thomas Kleinke
   */
  public String readURN(File file) throws IOException, ParseException {

    FileInputStream fileInputStream = new FileInputStream(file);
    BOMInputStream bomInputStream = new BOMInputStream(fileInputStream);

    XMLReader xmlReader = null;
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
      xmlReader = spf.newSAXParser().getXMLReader();
    } catch (Exception e) {
      fileInputStream.close();
      bomInputStream.close();
      throw new IOException("Error creating SAX parser", e);
    }
    xmlReader.setErrorHandler(err);
    NodeFactory nodeFactory = new PremisXmlReaderNodeFactory();
    Builder parser = new Builder(xmlReader, false, nodeFactory);
    logger.trace("Successfully built builder and XML reader");

    try {
      String urn = null;

      Document doc = parser.build(bomInputStream);
      Element root = doc.getRootElement();

      Element dmdSecEl = root.getFirstChildElement("dmdSec", METS_NS);
      if (dmdSecEl == null) return null;

      Element mdWrapEl = dmdSecEl.getFirstChildElement("mdWrap", METS_NS);
      if (mdWrapEl == null) return null;

      Element xmlDataEl = mdWrapEl.getFirstChildElement("xmlData", METS_NS);
      if (xmlDataEl == null) return null;

      Element modsEl = xmlDataEl.getFirstChildElement("mods", MODS_NS);
      if (modsEl == null) return null;

      Elements identifierEls = modsEl.getChildElements("identifier", MODS_NS);
      for (int i = 0; i < identifierEls.size(); i++) {
        Element element = identifierEls.get(i);
        Attribute attribute = element.getAttribute("type");
        if (attribute.getValue().toLowerCase().equals("urn")) urn = element.getValue();
      }

      if (urn != null && urn.equals("")) urn = null;

      return urn;
    } catch (ValidityException ve) {
      throw new IOException(ve);
    } catch (ParsingException pe) {
      throw new IOException(pe);
    } catch (IOException ie) {
      throw new IOException(ie);
    } finally {
      fileInputStream.close();
      bomInputStream.close();
    }
  }
 /*
  * Main method to parse specific MetaData file.
  */
 public Collection<Designate> doParse() throws IOException, SAXException {
   _dp_xmlReader = _dp_parser.getXMLReader();
   _dp_xmlReader.setContentHandler(new RootHandler());
   _dp_xmlReader.setErrorHandler(new MyErrorHandler(System.err));
   InputStream is = _dp_url.openStream();
   InputSource isource = new InputSource(is);
   logger.log(LogService.LOG_DEBUG, "Starting to parse " + _dp_url); // $NON-NLS-1$		
   _dp_xmlReader.parse(isource);
   return designates;
 }
示例#19
0
 private static void parse(final org.xml.sax.InputSource input, final FormatParser recognizer)
     throws SAXException, ParserConfigurationException, IOException {
   javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
   // factory.setValidating(true); //the code was generated according DTD
   // factory.setNamespaceAware(false); //the code was generated according DTD
   XMLReader parser = factory.newSAXParser().getXMLReader();
   parser.setContentHandler(recognizer);
   parser.setErrorHandler(recognizer.getDefaultErrorHandler());
   if (recognizer.resolver != null) parser.setEntityResolver(recognizer.resolver);
   parser.parse(input);
 }
示例#20
0
 public static XMLReader newXMLReader(XMLUtils.ParserConfiguration parserConfiguration) {
   final SAXParser saxParser = XMLUtils.newSAXParser(parserConfiguration);
   try {
     final XMLReader xmlReader = saxParser.getXMLReader();
     xmlReader.setEntityResolver(XMLUtils.ENTITY_RESOLVER);
     xmlReader.setErrorHandler(XMLUtils.ERROR_HANDLER);
     return xmlReader;
   } catch (Exception e) {
     throw new OXFException(e);
   }
 }
示例#21
0
 private static void parse(final InputSource input, final JDOParser recognizer)
     throws SAXException, ParserConfigurationException, IOException {
   SAXParserFactory factory = SAXParserFactory.newInstance();
   factory.setValidating(true);
   factory.setNamespaceAware(true);
   XMLReader parser = factory.newSAXParser().getXMLReader();
   parser.setEntityResolver(new JDOEntityResolver());
   parser.setContentHandler(recognizer);
   parser.setErrorHandler(recognizer.getDefaultErrorHandler());
   parser.parse(input);
 }
示例#22
0
 /**
  * Method to parse the XML input stream
  *
  * @throws TransactionCodesException if a problem is encountered parsing the XML stream
  */
 public void parse() throws URLRolesXMLParserException {
   try {
     XMLReader parser = XMLReaderFactory.createXMLReader();
     parser.setContentHandler(this);
     parser.setErrorHandler(this);
     parser.parse(new InputSource(_xmlStream));
   } catch (Exception e) {
     throw new URLRolesXMLParserException(
         "Exception caught parsing valid values XML stream: ", e, logger);
   }
 }
示例#23
0
 public static void main(String args[]) throws Exception {
   XMLReader xmlreader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
   SunOneXMLHandler sunonexmlhandler = new SunOneXMLHandler();
   xmlreader.setContentHandler(sunonexmlhandler);
   xmlreader.setErrorHandler(sunonexmlhandler);
   for (int i = 0; i < args.length; i++) {
     FileReader filereader = new FileReader(args[i]);
     xmlreader.parse(new InputSource(filereader));
     String s = sunonexmlhandler.getXML();
     System.out.println(s);
   }
 }
示例#24
0
 public WikiXMLParser(InputStream inputStream, IArticleFilter filter) throws SAXException {
   super();
   try {
     fArticleFilter = filter;
     fXMLReader = XMLReaderFactory.createXMLReader();
     fXMLReader.setContentHandler(this);
     fXMLReader.setErrorHandler(this);
     fReader = new BufferedReader(new InputStreamReader(inputStream, Connector.UTF8_CHARSET));
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   }
 }
  /**
   * Build a persistence.xml file into a SEPersistenceUnitInfo object. May eventually change this to
   * use OX mapping as well.
   */
  private static List<SEPersistenceUnitInfo> processPersistenceXML(
      URL baseURL, InputStream input, ClassLoader loader) {
    SAXParserFactory spf = XMLHelper.createParserFactory(false);

    XMLReader xmlReader = null;
    SAXParser sp = null;
    XMLExceptionHandler xmlErrorHandler = new XMLExceptionHandler();
    // 247735 - remove the validation of XML.

    // create a SAX parser
    try {
      sp = spf.newSAXParser();
    } catch (ParserConfigurationException | SAXException exc) {
      throw XMLParseException.exceptionCreatingSAXParser(baseURL, exc);
    }

    // create an XMLReader
    try {
      xmlReader = sp.getXMLReader();
      xmlReader.setErrorHandler(xmlErrorHandler);
    } catch (org.xml.sax.SAXException exc) {
      throw XMLParseException.exceptionCreatingXMLReader(baseURL, exc);
    }

    PersistenceContentHandler myContentHandler = new PersistenceContentHandler();
    xmlReader.setContentHandler(myContentHandler);

    InputSource inputSource = new InputSource(input);
    try {
      xmlReader.parse(inputSource);
    } catch (IOException exc) {
      throw PersistenceUnitLoadingException.exceptionProcessingPersistenceXML(baseURL, exc);
    } catch (org.xml.sax.SAXException exc) {
      // XMLErrorHandler will handle SAX exceptions
    }

    // handle any parse exceptions
    XMLException xmlError = xmlErrorHandler.getXMLException();
    if (xmlError != null) {
      throw PersistenceUnitLoadingException.exceptionProcessingPersistenceXML(baseURL, xmlError);
    }

    Iterator<SEPersistenceUnitInfo> persistenceInfos =
        myContentHandler.getPersistenceUnits().iterator();
    while (persistenceInfos.hasNext()) {
      SEPersistenceUnitInfo info = persistenceInfos.next();
      info.setPersistenceUnitRootUrl(baseURL);
      info.setClassLoader(loader);
      info.setNewTempClassLoader(loader);
    }
    return myContentHandler.getPersistenceUnits();
  }
  /** @return org.xml.sax.XMLReader */
  private XMLReader parser() {

    if (xmlParser == null) {
      try {
        xmlParser = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
        xmlParser.setContentHandler(this);
        xmlParser.setErrorHandler(this);
      } catch (final SAXException | ParserConfigurationException exc) {
        DefaultExceptionWriter.printOut(this, exc, true);
      }
    }
    return xmlParser;
  }
  public void read() throws IOException, SAXException {
    XMLReader xr;
    xr = new org.apache.xerces.parsers.SAXParser();
    KMLHandler kmlHandler = new KMLHandler();
    xr.setContentHandler(kmlHandler);
    xr.setErrorHandler(kmlHandler);

    Reader r = new BufferedReader(new FileReader(filename));
    LineNumberReader myReader = new LineNumberReader(r);
    xr.parse(new InputSource(myReader));

    // List geoms = kmlHandler.getGeometries();
  }
  private Object unmarshal0(XMLReader reader, InputSource source, JaxBeanInfo expectedType)
      throws JAXBException {

    SAXConnector connector = getUnmarshallerHandler(needsInterning(reader), expectedType);

    reader.setContentHandler(connector);
    // saxErrorHandler will be set by the getUnmarshallerHandler method.
    // configure XMLReader so that the error will be sent to it.
    // This is essential for the UnmarshallerHandler to be able to abort
    // unmarshalling when an error is found.
    //
    // Note that when this XMLReader is provided by the client code,
    // it might be already configured to call a client error handler.
    // This will clobber such handler, if any.
    //
    // Ryan noted that we might want to report errors to such a client
    // error handler as well.
    reader.setErrorHandler(coordinator);

    try {
      reader.parse(source);
    } catch (IOException e) {
      coordinator.clearStates();
      throw new UnmarshalException(e);
    } catch (SAXException e) {
      coordinator.clearStates();
      throw createUnmarshalException(e);
    }

    Object result = connector.getResult();

    // avoid keeping unnecessary references too long to let the GC
    // reclaim more memory.
    // setting null upsets some parsers, so use a dummy instance instead.
    reader.setContentHandler(dummyHandler);
    reader.setErrorHandler(dummyHandler);

    return result;
  }
示例#29
0
  /**
   * Create an istance of parser
   *
   * @param filename name of input file
   */
  public CustomParser(String filename) throws SAXException, FileNotFoundException, IOException {

    dm = new DocModel();

    xr = XMLReaderFactory.createXMLReader();
    CustomHandler handler = new CustomHandler(dm);

    xr.setContentHandler(handler);
    xr.setErrorHandler(handler);

    FileReader r = new FileReader(filename);
    xr.parse(new InputSource(r));
  }
 private static boolean isWellFormedXML(String value) {
   try {
     XMLReader parser = XMLReaderFactory.createXMLReader();
     parser.setErrorHandler(null);
     InputSource source = new InputSource(new ByteArrayInputStream(value.getBytes()));
     parser.parse(source);
   } catch (SAXException e) {
     return false;
   } catch (IOException e) {
     return false;
   }
   return true;
 }