Пример #1
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;
    }
  }
 /*
  * 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;
 }
  /**
   * 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();
    }
  }
Пример #4
0
 public static void parseDocumentFragment(Reader reader, XMLReceiver xmlReceiver)
     throws SAXException {
   try {
     final XMLReader xmlReader = newSAXParser(XMLUtils.ParserConfiguration.PLAIN).getXMLReader();
     xmlReader.setContentHandler(new XMLFragmentReceiver(xmlReceiver));
     final ArrayList<Reader> readers = new ArrayList<Reader>(3);
     readers.add(new StringReader("<root>"));
     readers.add(reader);
     readers.add(new StringReader("</root>"));
     xmlReader.parse(new InputSource(new SequenceReader(readers.iterator())));
   } catch (IOException e) {
     throw new OXFException(e);
   }
 }
Пример #5
0
 public static void parseDocumentFragment(String fragment, XMLReceiver xmlReceiver)
     throws SAXException {
   if (fragment.indexOf("<") != -1 || fragment.indexOf("&") != -1) {
     try {
       final XMLReader xmlReader = newSAXParser(XMLUtils.ParserConfiguration.PLAIN).getXMLReader();
       xmlReader.setContentHandler(new XMLFragmentReceiver(xmlReceiver));
       xmlReader.parse(new InputSource(new StringReader("<root>" + fragment + "</root>")));
     } catch (IOException e) {
       throw new OXFException(e);
     }
   } else {
     // Optimization when fragment looks like text
     xmlReceiver.characters(fragment.toCharArray(), 0, fragment.length());
   }
 }
Пример #6
0
 public int runXmlImport() {
   DataImportXmlParser responseHandler = null;
   try {
     XMLReader parser = EfaUtil.getXMLReader();
     responseHandler = new DataImportXmlParser(this, dataAccess);
     parser.setContentHandler(responseHandler);
     parser.parse(new InputSource(new FileInputStream(filename)));
   } catch (Exception e) {
     logInfo(e.toString());
     errorCount++;
     Logger.log(e);
     if (Daten.isGuiAppl()) {
       Dialog.error(e.toString());
     }
   }
   return (responseHandler != null ? responseHandler.getImportedRecordsCount() : 0);
 }
  /**
   * 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();
    }
  }
Пример #8
0
  private static void inputSourceToSAX(
      InputSource inputSource,
      XMLReceiver xmlReceiver,
      XMLUtils.ParserConfiguration parserConfiguration,
      boolean handleLexical) {

    // Insert XInclude processor if needed
    final TransformerURIResolver resolver;
    if (parserConfiguration.handleXInclude) {
      parserConfiguration =
          new XMLUtils.ParserConfiguration(
              parserConfiguration.validating,
              false,
              parserConfiguration.externalEntities,
              parserConfiguration.uriReferences);
      resolver = new TransformerURIResolver(XMLUtils.ParserConfiguration.PLAIN);
      xmlReceiver =
          new XIncludeReceiver(null, xmlReceiver, parserConfiguration.uriReferences, resolver);
    } else {
      resolver = null;
    }

    try {
      final XMLReader xmlReader = newSAXParser(parserConfiguration).getXMLReader();
      xmlReader.setContentHandler(xmlReceiver);
      if (handleLexical) xmlReader.setProperty(XMLConstants.SAX_LEXICAL_HANDLER, xmlReceiver);

      xmlReader.setEntityResolver(ENTITY_RESOLVER);
      xmlReader.setErrorHandler(ERROR_HANDLER);
      xmlReader.parse(inputSource);
    } catch (SAXParseException e) {
      throw new ValidationException(e.getMessage(), new LocationData(e));
    } catch (Exception e) {
      throw new OXFException(e);
    } finally {
      if (resolver != null) resolver.destroy();
    }
  }
  protected static void addXml(
      final SolrInputDocument doc,
      final String fieldprefix,
      final String textfield,
      InputSource input)
      throws SAXException, IOException {
    XMLReader reader = XMLReaderFactory.createXMLReader();

    final StringBuilder text = new StringBuilder();

    reader.setContentHandler(
        new ContentHandler() {

          final Deque<String> parents = new LinkedList<String>();

          final Deque<StringBuilder> element_texts = new LinkedList<StringBuilder>();

          private String path() {
            StringBuilder sb = new StringBuilder(fieldprefix);

            for (String el : parents) {
              sb.append('/');
              sb.append(el);
            }

            return sb.toString();
          }

          public void startPrefixMapping(String prefix, String uri) throws SAXException {}

          public void startDocument() throws SAXException {}

          public void skippedEntity(String name) throws SAXException {}

          public void setDocumentLocator(Locator locator) {}

          public void processingInstruction(String target, String data) throws SAXException {}

          public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
            text.append(ch, start, length);

            element_texts.getLast().append(ch, start, length);
          }

          public void endPrefixMapping(String prefix) throws SAXException {}

          public void endElement(String uri, String localName, String qName) throws SAXException {
            addxmltext(doc, path(), element_texts.removeLast());
            parents.removeLast();
          }

          public void endDocument() throws SAXException {
            addxmltext(doc, textfield, text);
          }

          public void characters(char[] ch, int start, int length) throws SAXException {
            text.append(ch, start, length);
            text.append(' ');

            element_texts.getLast().append(ch, start, length);
          }

          public void startElement(String uri, String localName, String qName, Attributes atts)
              throws SAXException {

            // ignore namespaces when constructing field names
            parents.addLast(localName);
            element_texts.addLast(new StringBuilder());

            for (int i = 0; i < atts.getLength(); i++) {
              String attr_field = path() + "@" + atts.getLocalName(i);
              doc.addField(attr_field, atts.getValue(i));
            }
          }
        });

    reader.setErrorHandler(
        new ErrorHandler() {

          public void warning(SAXParseException exception) throws SAXException {
            // TODO log?
            throw exception;
          }

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

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

    reader.parse(input);
  }