Exemple #1
0
 /**
  * Error message. Calls {@link ErrorHandler#error(SAXParseException) ErrorHandler.error}.
  *
  * @param message {@inheritDoc}
  * @param e {@inheritDoc}
  */
 public void error(String message, ParserException e) {
   try {
     mErrorHandler.error(new SAXParseException(message, mLocator, e));
   } catch (SAXException se) {
     se.printStackTrace();
   }
 }
Exemple #2
0
 /**
  * Warning message. Calls {@link ErrorHandler#warning(SAXParseException) ErrorHandler.warning}.
  *
  * @param message {@inheritDoc}
  */
 public void warning(String message) {
   try {
     mErrorHandler.warning(new SAXParseException(message, mLocator));
   } catch (SAXException se) {
     se.printStackTrace();
   }
 }
Exemple #3
0
 public void error(Locator locator, String key, String arg) {
   if (locator == null) locator = this.locator;
   try {
     eh.error(new SAXParseException(localizer.message(key, arg), locator));
   } catch (SAXException e) {
     throw new WrappedSAXException(e);
   }
 }
 public void warning(TransformerException exception) throws TransformerException {
   SAXParseException spe = transform(exception);
   try {
     eh.warning(spe);
   } catch (SAXException e) {
     throw new TransformerException(new UserException(e));
   }
 }
 public void fatalError(TransformerException exception) throws TransformerException {
   hadError = true;
   SAXParseException spe = transform(exception);
   try {
     eh.fatalError(spe);
   } catch (SAXException e) {
     throw new TransformerException(new UserException(e));
   }
 }
 public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
     throws SAXException {
   if (namespaceURI.equals(ERROR_URI) && localName.equals("error"))
     eh.error(
         new SAXParseException(
             localizer.message(atts.getValue("", "message"), atts.getValue("", "arg")),
             locator));
   super.startElement(namespaceURI, localName, qName, atts);
 }
  /** @see org.xml.sax.ErrorHandler#fatalError(SAXParseException) */
  public void fatalError(SAXParseException exc) throws SAXException {
    super.fatalError(exc);

    m_needToCallStartDocument = false;

    if (m_saxHandler instanceof ErrorHandler) {
      ((ErrorHandler) m_saxHandler).fatalError(exc);
    }
  }
Exemple #8
0
 public void writeTo(ContentHandler contentHandler, ErrorHandler errorHandler)
     throws SAXException {
   try {
     bridge.marshal(jaxbObject, contentHandler);
   } catch (JAXBException e) {
     SAXParseException x = new SAXParseException(e.getMessage(), null, null, -1, -1, e);
     errorHandler.fatalError(x);
     throw x;
   }
 }
  public void writePayloadTo(
      ContentHandler contentHandler, ErrorHandler errorHandler, boolean fragment)
      throws SAXException {
    assert unconsumed();
    try {
      if (payloadLocalName == null) {
        return;
      } // no body

      XMLStreamReaderToContentHandler conv =
          new XMLStreamReaderToContentHandler(reader, contentHandler, true, fragment);

      while (reader.getEventType() != XMLStreamConstants.END_DOCUMENT) {
        String name = reader.getLocalName();
        String nsUri = reader.getNamespaceURI();

        // after previous conv.bridge() call the cursor will be at
        // END_ELEMENT. Check if its not soapenv:Body then move to next
        // ELEMENT
        if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
          if (!name.equals("Body") || !nsUri.equals(soapVersion.nsUri)) {
            XMLStreamReaderUtil.nextElementContent(reader);
            if (reader.getEventType() == XMLStreamConstants.END_DOCUMENT) {
              break;
            }
            name = reader.getLocalName();
            nsUri = reader.getNamespaceURI();
          }
        }
        if (name.equals("Body") && nsUri.equals(soapVersion.nsUri)
            || (reader.getEventType() == XMLStreamConstants.END_DOCUMENT)) {
          break;
        }

        conv.bridge();
      }
      reader.close();
      XMLStreamReaderFactory.recycle(reader);
    } catch (XMLStreamException e) {
      Location loc = e.getLocation();
      if (loc == null) {
        loc = DummyLocation.INSTANCE;
      }

      SAXParseException x =
          new SAXParseException(
              e.getMessage(),
              loc.getPublicId(),
              loc.getSystemId(),
              loc.getLineNumber(),
              loc.getColumnNumber(),
              e);
      errorHandler.error(x);
    }
  }
  /**
   * Reports a warning. Warnings are non-fatal and can be safely ignored by most applications.
   *
   * @param domain The domain of the warning. The domain can be any string but is suggested to be a
   *     valid URI. The domain can be used to conveniently specify a web site location of the
   *     relevent specification or document pertaining to this warning.
   * @param key The warning key. This key can be any string and is implementation dependent.
   * @param exception Exception.
   * @throws XNIException Thrown to signal that the parser should stop parsing the document.
   */
  public void warning(String domain, String key, XMLParseException exception) throws XNIException {

    if (fErrorHandler != null) {
      SAXParseException saxException = createSAXParseException(exception);

      try {
        fErrorHandler.warning(saxException);
      } catch (SAXParseException e) {
        throw createXMLParseException(e);
      } catch (SAXException e) {
        throw createXNIException(e);
      }
    }
  } // warning(String,String,XMLParseException)
 /**
  * Notifies the registered {@link ErrorHandler SAX error handler} (if any) of an input processing
  * error. The error handler can choose to absorb the error and let the processing continue.
  *
  * @param exception <code>JDOMException</code> containing the error information; will be wrapped
  *     in a {@link SAXParseException} when reported to the SAX error handler.
  * @throws JDOMException if no error handler has been registered or if the error handler fired a
  *     {@link SAXException}.
  */
 private void handleError(JDOMException exception) throws JDOMException {
   if (errorHandler != null) {
     try {
       errorHandler.error(new SAXParseException(exception.getMessage(), null, exception));
     } catch (SAXException se) {
       if (se.getException() instanceof JDOMException) {
         throw (JDOMException) (se.getException());
       }
       throw new JDOMException(se.getMessage(), se);
     }
   } else {
     throw exception;
   }
 }
Exemple #12
0
  public void parse(org.xml.sax.InputSource in) throws SAXException, IOException {

    documentHandler.setDocumentLocator(this);
    try {
      parser.parseDocument(openInputSource(in));
    } catch (WrapperException e) {
      throw e.getWrapped();
    } catch (NotWellFormedException e) {
      errorHandler.fatalError(
          new org.xml.sax.SAXParseException(
              e.getMessageWithoutLocation(),
              null,
              e.getEntityLocation(),
              e.getLineNumber(),
              e.getColumnNumber()));
    } catch (ApplicationException e) {
      throw (SAXException) e.getException();
    }
  }
Exemple #13
0
        public void parse() throws SAXException {
          // parses a content object by using the given marshaller
          // SAX events will be sent to the repeater, and the repeater
          // will further forward it to an appropriate component.
          try {
            marshaller.marshal(contentObject, (XMLFilterImpl) repeater);
          } catch (JAXBException e) {
            // wrap it to a SAXException
            SAXParseException se = new SAXParseException(e.getMessage(), null, null, -1, -1, e);

            // if the consumer sets an error handler, it is our responsibility
            // to notify it.
            if (errorHandler != null) errorHandler.fatalError(se);

            // this is a fatal error. Even if the error handler
            // returns, we will abort anyway.
            throw se;
          }
        }
Exemple #14
0
 /** @see org.xml.sax.helpers.DefaultHandler#warning(org.xml.sax.SAXParseException) */
 public void warning(SAXParseException e) throws SAXException {
   if (delegate != null) delegate.warning(e);
   else super.warning(e);
 }
Exemple #15
0
 /** @see org.xml.sax.helpers.DefaultHandler#error(org.xml.sax.SAXParseException) */
 public void error(SAXParseException e) throws SAXException {
   if (delegate != null) delegate.error(e);
   else super.error(e);
 }
Exemple #16
0
  public Schema newSchema(Source[] schemas) throws SAXException {

    // this will let the loader store parsed Grammars into the pool.
    XMLGrammarPoolImplExtension pool = new XMLGrammarPoolImplExtension();
    fXMLGrammarPoolWrapper.setGrammarPool(pool);

    XMLInputSource[] xmlInputSources = new XMLInputSource[schemas.length];
    InputStream inputStream;
    Reader reader;
    for (int i = 0; i < schemas.length; i++) {
      Source source = schemas[i];
      if (source instanceof StreamSource) {
        StreamSource streamSource = (StreamSource) source;
        String publicId = streamSource.getPublicId();
        String systemId = streamSource.getSystemId();
        inputStream = streamSource.getInputStream();
        reader = streamSource.getReader();
        xmlInputSources[i] = new XMLInputSource(publicId, systemId, null);
        xmlInputSources[i].setByteStream(inputStream);
        xmlInputSources[i].setCharacterStream(reader);
      } else if (source instanceof SAXSource) {
        SAXSource saxSource = (SAXSource) source;
        InputSource inputSource = saxSource.getInputSource();
        if (inputSource == null) {
          throw new SAXException(
              JAXPValidationMessageFormatter.formatMessage(
                  Locale.getDefault(), "SAXSourceNullInputSource", null));
        }
        xmlInputSources[i] = new SAXInputSource(saxSource.getXMLReader(), inputSource);
      } else if (source instanceof DOMSource) {
        DOMSource domSource = (DOMSource) source;
        Node node = domSource.getNode();
        String systemID = domSource.getSystemId();
        xmlInputSources[i] = new DOMInputSource(node, systemID);
      } else if (source == null) {
        throw new NullPointerException(
            JAXPValidationMessageFormatter.formatMessage(
                Locale.getDefault(), "SchemaSourceArrayMemberNull", null));
      } else {
        throw new IllegalArgumentException(
            JAXPValidationMessageFormatter.formatMessage(
                Locale.getDefault(),
                "SchemaFactorySourceUnrecognized",
                new Object[] {source.getClass().getName()}));
      }
    }

    try {
      fXMLSchemaLoader.loadGrammar(xmlInputSources);
    } catch (XNIException e) {
      // this should have been reported to users already.
      throw Util.toSAXException(e);
    } catch (IOException e) {
      // this hasn't been reported, so do so now.
      SAXParseException se = new SAXParseException(e.getMessage(), null, e);
      fErrorHandler.error(se);
      throw se; // and we must throw it.
    }

    // Clear reference to grammar pool.
    fXMLGrammarPoolWrapper.setGrammarPool(null);

    // Select Schema implementation based on grammar count.
    final int grammarCount = pool.getGrammarCount();
    if (grammarCount > 1) {
      return new XMLSchema(new ReadOnlyGrammarPool(pool));
    } else if (grammarCount == 1) {
      Grammar[] grammars = pool.retrieveInitialGrammarSet(XMLGrammarDescription.XML_SCHEMA);
      return new SimpleXMLSchema(grammars[0]);
    } else {
      return EmptyXMLSchema.getInstance();
    }
  }
 public void fatalError(SAXParseException exception) throws SAXException {
   if (null == errorHandler) {
     throw exception;
   }
   errorHandler.fatalError(marshalSAXParseException(exception));
 }
 public void warning(SAXParseException exception) throws SAXException {
   if (null == errorHandler) {
     throw exception;
   }
   errorHandler.warning(marshalSAXParseException(exception));
 }
 protected void err(String message) throws SAXException {
   SAXParseException spe = new SAXParseException(message, locator);
   errorHandler.error(spe);
 }
 protected void fatal(String message) throws SAXException {
   SAXParseException spe = new SAXParseException(message, locator);
   errorHandler.fatalError(spe);
   throw spe;
 }
Exemple #21
0
 @Override
 public void fatalError(SAXParseException e) throws SAXException {
   errorHandler.fatalError(e);
 }
  /** @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String) */
  @Override
  public InputSource resolveEntity(String publicId, String systemId)
      throws SAXException, IOException {
    if (requestsLeft > -1) {
      if (requestsLeft == 0) {
        throw new IOException("Number of permitted HTTP requests exceeded.");
      } else {
        requestsLeft--;
      }
    }
    HttpGet m = null;
    try {
      URL url;
      try {
        url = URL.parse(systemId);
      } catch (GalimatiasParseException e) {
        IOException ioe = (IOException) new IOException(e.getMessage()).initCause(e);
        SAXParseException spe =
            new SAXParseException(e.getMessage(), publicId, systemId, -1, -1, ioe);
        if (errorHandler != null) {
          errorHandler.fatalError(spe);
        }
        throw spe;
      }
      String scheme = url.scheme();
      if (!("http".equals(scheme) || "https".equals(scheme))) {
        String msg = "Unsupported URI scheme: \u201C" + scheme + "\u201D.";
        SAXParseException spe =
            new SAXParseException(msg, publicId, systemId, -1, -1, new IOException(msg));
        if (errorHandler != null) {
          errorHandler.fatalError(spe);
        }
        throw spe;
      }
      systemId = url.toString();
      try {
        m = new HttpGet(systemId);
      } catch (IllegalArgumentException e) {
        SAXParseException spe =
            new SAXParseException(
                e.getMessage(),
                publicId,
                systemId,
                -1,
                -1,
                (IOException) new IOException(e.getMessage()).initCause(e));
        if (errorHandler != null) {
          errorHandler.fatalError(spe);
        }
        throw spe;
      }
      m.setHeader("User-Agent", userAgent);
      m.setHeader("Accept", buildAccept());
      m.setHeader("Accept-Encoding", "gzip");
      log4j.info(systemId);
      HttpResponse response = client.execute(m);
      int statusCode = response.getStatusLine().getStatusCode();
      if (statusCode != 200) {
        String msg =
            "HTTP resource not retrievable. The HTTP status from the remote server was: "
                + statusCode
                + ".";
        SAXParseException spe =
            new SAXParseException(
                msg, publicId, m.getURI().toString(), -1, -1, new IOException(msg));
        if (errorHandler != null) {
          errorHandler.fatalError(spe);
        }
        throw spe;
      }
      HttpEntity entity = response.getEntity();
      long len = entity.getContentLength();
      if (sizeLimit > -1 && len > sizeLimit) {
        SAXParseException spe =
            new SAXParseException(
                "Resource size exceeds limit.",
                publicId,
                m.getURI().toString(),
                -1,
                -1,
                new StreamBoundException("Resource size exceeds limit."));
        if (errorHandler != null) {
          errorHandler.fatalError(spe);
        }
        throw spe;
      }
      TypedInputSource is;
      org.apache.http.Header ct = response.getFirstHeader("Content-Type");
      String contentType = null;
      final String baseUri = m.getURI().toString();
      if (ct != null) {
        contentType = ct.getValue();
      }
      is = contentTypeParser.buildTypedInputSource(baseUri, publicId, contentType);

      Header cl = response.getFirstHeader("Content-Language");
      if (cl != null) {
        is.setLanguage(cl.getValue().trim());
      }

      Header xuac = response.getFirstHeader("X-UA-Compatible");
      if (xuac != null) {
        String val = xuac.getValue().trim();
        if (!"ie=edge".equalsIgnoreCase(val)) {
          SAXParseException spe =
              new SAXParseException(
                  "X-UA-Compatible HTTP header must have the value \u201CIE=edge\u201D,"
                      + " was \u201C"
                      + val
                      + "\u201D.",
                  publicId,
                  systemId,
                  -1,
                  -1);
          errorHandler.error(spe);
        }
      }

      Header csp = response.getFirstHeader("Content-Security-Policy");
      if (csp != null) {
        try {
          ContentSecurityPolicy.THE_INSTANCE.checkValid(csp.getValue().trim());
        } catch (DatatypeException e) {
          SAXParseException spe =
              new SAXParseException(
                  "Content-Security-Policy HTTP header: " + e.getMessage(),
                  publicId,
                  systemId,
                  -1,
                  -1);
          Html5DatatypeException ex5 = (Html5DatatypeException) e;
          if (ex5.isWarning()) {
            errorHandler.warning(spe);
          } else {
            errorHandler.error(spe);
          }
        }
      }

      final HttpGet meth = m;
      InputStream stream = entity.getContent();
      if (sizeLimit > -1) {
        stream = new BoundedInputStream(stream, sizeLimit, baseUri);
      }
      Header ce = response.getFirstHeader("Content-Encoding");
      if (ce != null) {
        String val = ce.getValue().trim();
        if ("gzip".equalsIgnoreCase(val) || "x-gzip".equalsIgnoreCase(val)) {
          stream = new GZIPInputStream(stream);
          if (sizeLimit > -1) {
            stream = new BoundedInputStream(stream, sizeLimit, baseUri);
          }
        }
      }
      is.setByteStream(
          new ObservableInputStream(
              stream,
              new StreamObserver() {
                private final Logger log4j =
                    Logger.getLogger("nu.validator.xml.PrudentEntityResolver.StreamObserver");

                private boolean released = false;

                @Override
                public void closeCalled() {
                  log4j.debug("closeCalled");
                  if (!released) {
                    log4j.debug("closeCalled, not yet released");
                    released = true;
                    try {
                      meth.releaseConnection();
                    } catch (Exception e) {
                      log4j.debug("closeCalled, releaseConnection", e);
                    }
                  }
                }

                @Override
                public void exceptionOccurred(Exception ex) throws IOException {
                  if (!released) {
                    released = true;
                    try {
                      meth.abort();
                    } catch (Exception e) {
                      log4j.debug("exceptionOccurred, abort", e);
                    } finally {
                      try {
                        meth.releaseConnection();
                      } catch (Exception e) {
                        log4j.debug("exceptionOccurred, releaseConnection", e);
                      }
                    }
                  }
                  if (ex instanceof SystemIdIOException) {
                    throw (SystemIdIOException) ex;
                  } else if (ex instanceof IOException) {
                    IOException ioe = (IOException) ex;
                    throw new SystemIdIOException(baseUri, ioe.getMessage(), ioe);
                  } else if (ex instanceof RuntimeException) {
                    throw (RuntimeException) ex;
                  } else {
                    throw new RuntimeException("API contract violation. Wrong exception type.", ex);
                  }
                }

                @Override
                public void finalizerCalled() {
                  if (!released) {
                    released = true;
                    try {
                      meth.abort();
                    } catch (Exception e) {
                      log4j.debug("finalizerCalled, abort", e);
                    } finally {
                      try {
                        meth.releaseConnection();
                      } catch (Exception e) {
                        log4j.debug("finalizerCalled, releaseConnection", e);
                      }
                    }
                  }
                }
              }));
      return is;
    } catch (IOException | RuntimeException | SAXException e) {
      if (m != null) {
        try {
          m.abort();
        } catch (Exception ex) {
          log4j.debug("abort", ex);
        } finally {
          try {
            m.releaseConnection();
          } catch (Exception ex) {
            log4j.debug("releaseConnection", ex);
          }
        }
      }
      throw e;
    }
  }
  /** @see org.xml.sax.ErrorHandler#warning(SAXParseException) */
  public void warning(SAXParseException exc) throws SAXException {
    super.warning(exc);

    if (m_saxHandler instanceof ErrorHandler) ((ErrorHandler) m_saxHandler).warning(exc);
  }
Exemple #24
0
 @Override
 public void warning(SAXParseException e) throws SAXException {
   errorHandler.warning(e);
 }