예제 #1
0
  /**
   * Parses an XML document.
   *
   * @param xmlin the XML document.
   * @return the ParseOutput object from walking and processing the node.
   * @throws Exception if there are IO or XML parsing exceptions.
   */
  public Object parse(InputStream xmlin) throws Exception {
    DocumentBuilder db = null;
    try {
      db = XMLUtils.getSafeDocumentBuilder(false);
    } catch (ParserConfigurationException e) {
      throw new Exception("DBG:Got ParserConfigurationException:" + e.toString());
    }

    Document doc = null;
    try {
      doc = db.parse(xmlin);
    } catch (SAXParseException e) {
      throw new Exception(
          "DBG:Got SAXParseException:"
              + e.toString()
              + "line:"
              + e.getLineNumber()
              + " col :"
              + e.getColumnNumber());
    } catch (SAXException e) {
      throw new Exception("DBG:Got SAXException:" + e.toString());
    } catch (IOException ex) {
      throw new Exception("DBG: Got IOException:" + ex.toString());
    }

    Element elem = doc.getDocumentElement();
    return (walkTree(elem));
  }
 /** 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();
   }
 }
예제 #3
0
 /**
  * Logs a SAXParseException through the reporter.
  *
  * @param type message type
  * @param err SAX error
  */
 private void reportException(ReportType type, SAXParseException err) {
   String msg = err.getMessage();
   if (msg == null) {
     msg = err.toString();
   }
   ReportCode code = AdhocCode.createCodeFromText(type, msg);
   StringBuffer sbuf = new StringBuffer();
   int il = err.getLineNumber();
   int ic = err.getColumnNumber();
   if (il > 0) {
     sbuf.append(" (l.").append(il);
     if (ic > 0) {
       sbuf.append(", c.").append(ic);
     }
     sbuf.append(")");
   }
   sbuf.append(": ").append(msg);
   reporter_.report(code, sbuf.toString());
 }
예제 #4
0
  @Deprecated
  public Document Deconstruct(String xmldata) {
    Document rv = null;
    if (xmldata != null) {
      String xmlbuf = xmldata.trim();
      if (xmlbuf.length() > 0) {
        InputSource is = new InputSource(new StringReader(xmlbuf));
        DocumentBuilderFactory f = null;
        DocumentBuilder p = null;

        f = DocumentBuilderFactory.newInstance();

        try {
          p = f.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
          if (ERROR_ENABLED) logger.error("ParserConfigurationException " + ex.toString());
        }

        //				if (DEBUG_ENABLED) logger.debug("Parser configured");

        boolean parsed = false;
        if (p != null) {
          try {
            rv = p.parse(is);
            if (rv != null) parsed = true;
            //						if (DEBUG_ENABLED && rv != null) logger.debug("Parse successful");
          } catch (SAXParseException ex) {
            if (ERROR_ENABLED)
              logger.error("SAX Parse Error " + ex.toString() + " at line " + ex.getLineNumber());
          } catch (SAXException ex) {
            if (ERROR_ENABLED) logger.error("SAX Error " + ex.toString());
          } catch (Exception ex) {
            if (ERROR_ENABLED) logger.error("XML Error " + ex.toString());
          }
          if (!parsed) {
            if (ERROR_ENABLED) logger.error("Parsing failed for \n" + xmldata);
          }
        }
      }
    }
    //		if (DEBUG_ENABLED) logger.debug("Leaving method");
    return rv;
  }
 public void warning(SAXParseException e) throws SAXException {
   log.warn(e.toString());
 }
    public void warning(final SAXParseException exception) throws SAXException {

      LOG.warn(exception.toString());
    }
예제 #7
0
 /** {@inheritDoc} */
 public void fatalError(SAXParseException e) throws SAXException {
   log.error(e.toString());
   throw e;
 }
예제 #8
0
 /** {@inheritDoc} */
 public void error(SAXParseException e) {
   log.error(e.toString());
 }
예제 #9
0
  /**
   * Validate message with a XML schema.
   *
   * @param receivedMessage
   * @param validationContext
   */
  protected void validateXMLSchema(
      Message receivedMessage, XmlMessageValidationContext validationContext) {
    if (receivedMessage.getPayload() == null
        || !StringUtils.hasText(receivedMessage.getPayload(String.class))) {
      return;
    }

    try {
      Document doc = XMLUtils.parseMessagePayload(receivedMessage.getPayload(String.class));

      if (!StringUtils.hasText(doc.getFirstChild().getNamespaceURI())) {
        return;
      }

      log.info("Starting XML schema validation ...");

      XmlValidator validator = null;
      XsdSchemaRepository schemaRepository = null;
      if (validationContext.getSchema() != null) {
        validator =
            applicationContext
                .getBean(validationContext.getSchema(), XsdSchema.class)
                .createValidator();
      } else if (validationContext.getSchemaRepository() != null) {
        schemaRepository =
            applicationContext.getBean(
                validationContext.getSchemaRepository(), XsdSchemaRepository.class);
      } else if (schemaRepositories.size() == 1) {
        schemaRepository = schemaRepositories.get(0);
      } else if (schemaRepositories.size() > 0) {
        for (XsdSchemaRepository repository : schemaRepositories) {
          if (repository.canValidate(doc)) {
            schemaRepository = repository;
          }
        }

        if (schemaRepository == null) {
          throw new CitrusRuntimeException(
              String.format(
                  "Failed to find proper schema repository in Spring bean context for validating element '%s(%s)'",
                  doc.getFirstChild().getLocalName(), doc.getFirstChild().getNamespaceURI()));
        }
      } else {
        log.warn(
            "Neither schema instance nor schema repository defined - skipping XML schema validation");
        return;
      }

      if (schemaRepository != null) {
        if (!schemaRepository.canValidate(doc)) {
          throw new CitrusRuntimeException(
              String.format(
                  "Unable to find proper XML schema definition for element '%s(%s)' in schema repository '%s'",
                  doc.getFirstChild().getLocalName(),
                  doc.getFirstChild().getNamespaceURI(),
                  schemaRepository.getName()));
        }

        List<Resource> schemas = new ArrayList<>();
        for (XsdSchema xsdSchema : schemaRepository.getSchemas()) {
          if (xsdSchema instanceof XsdSchemaCollection) {
            for (Resource resource : ((XsdSchemaCollection) xsdSchema).getSchemaResources()) {
              schemas.add(resource);
            }
          } else if (xsdSchema instanceof WsdlXsdSchema) {
            for (Resource resource : ((WsdlXsdSchema) xsdSchema).getSchemaResources()) {
              schemas.add(resource);
            }
          } else {
            synchronized (transformerFactory) {
              ByteArrayOutputStream bos = new ByteArrayOutputStream();
              try {
                transformerFactory
                    .newTransformer()
                    .transform(xsdSchema.getSource(), new StreamResult(bos));
              } catch (TransformerException e) {
                throw new CitrusRuntimeException(
                    "Failed to read schema " + xsdSchema.getTargetNamespace(), e);
              }
              schemas.add(new ByteArrayResource(bos.toByteArray()));
            }
          }
        }

        validator =
            XmlValidatorFactory.createValidator(
                schemas.toArray(new Resource[schemas.size()]), WsdlXsdSchema.W3C_XML_SCHEMA_NS_URI);
      }

      SAXParseException[] results = validator.validate(new DOMSource(doc));
      if (results.length == 0) {
        log.info("Schema of received XML validated OK");
      } else {
        log.error(
            "Schema validation failed for message:\n"
                + XMLUtils.prettyPrint(receivedMessage.getPayload(String.class)));

        // Report all parsing errors
        log.debug("Found " + results.length + " schema validation errors");
        StringBuilder errors = new StringBuilder();
        for (SAXParseException e : results) {
          errors.append(e.toString());
          errors.append("\n");
        }
        log.debug(errors.toString());

        throw new ValidationException("Schema validation failed:", results[0]);
      }
    } catch (IOException e) {
      throw new CitrusRuntimeException(e);
    } catch (SAXException e) {
      throw new CitrusRuntimeException(e);
    }
  }