public static void handleError(
      SAXParseException ex, PsiFile file, Document document, ValidationMessageConsumer consumer) {
    final String systemId = ex.getSystemId();
    if (LOG.isDebugEnabled()) {
      LOG.debug("RNG Schema error: " + ex.getMessage() + " [" + systemId + "]");
    }

    if (systemId != null) {
      final VirtualFile virtualFile = findVirtualFile(systemId);
      if (!Comparing.equal(virtualFile, file.getVirtualFile())) {
        return;
      }
    }

    final PsiElement at;
    final int line = ex.getLineNumber();
    if (line > 0) {
      final int column = ex.getColumnNumber();
      final int startOffset = document.getLineStartOffset(line - 1);

      if (column > 0) {
        if (file.getFileType() == RncFileType.getInstance()) {
          final PsiElement e = file.findElementAt(startOffset + column);
          if (e == null) {
            at = e;
          } else {
            at = file.findElementAt(startOffset + column - 1);
          }
        } else {
          at = file.findElementAt(startOffset + column - 2);
        }
      } else {
        final PsiElement e = file.findElementAt(startOffset);
        at = e != null ? PsiTreeUtil.nextLeaf(e) : null;
      }
    } else {
      final XmlDocument d = ((XmlFile) file).getDocument();
      assert d != null;
      final XmlTag rootTag = d.getRootTag();
      assert rootTag != null;
      at = rootTag.getFirstChild();
    }

    final PsiElement host;
    if (file instanceof RncFile) {
      host = at;
    } else {
      host = PsiTreeUtil.getParentOfType(at, XmlAttribute.class, XmlTag.class);
    }
    if (at != null && host != null) {
      consumer.onMessage(host, ex.getMessage());
    } else {
      consumer.onMessage(file, ex.getMessage());
    }
  }
Exemple #2
0
  /**
   * @param ex The exception to create a message from
   * @return A summary of what went wrong.
   */
  private static String getMessage(SAXParseException ex) {
    if (ex.getSystemId() != null) {
      return "SystemID=" + ex.getSystemId() + " Line=" + ex.getLineNumber() + ' ' + ex.getMessage();
    }

    if (ex.getPublicId() != null) {
      return "PublicID=" + ex.getPublicId() + " Line=" + ex.getLineNumber() + ' ' + ex.getMessage();
    }

    return "Line=" + ex.getLineNumber() + ' ' + ex.getMessage();
  }
Exemple #3
0
 @Override
 public void fatalError(SAXParseException exception) throws SAXException {
   // TODO Auto-generated method stub
   System.out.println("Error: " + exception.getMessage());
   System.out.println(
       "At line no: " + exception.getLineNumber() + " in column " + exception.getColumnNumber());
 }
  /**
   * Reports a failure if reading the given resource does <U>not</U> cause the expected exception at
   * the expected location.
   */
  private void assertException(String resource, int expectedLine, String expectedMsg) {
    Throwable failure = null;
    try {
      generatorSetResources_.read(resource);
    } catch (Throwable t) {
      failure = t;
    }

    if (failure == null) {
      fail("Expected exception not thrown.");
    }

    Throwable cause;
    for (cause = failure.getCause();
        !(cause == null || cause instanceof SAXParseException);
        cause = cause.getCause()) ;

    if (cause == null) {
      throw new RuntimeException("Unexpected exception thrown", failure);
    }

    SAXParseException spe = (SAXParseException) cause;
    assertEquals("Exception line", expectedLine, spe.getLineNumber());

    String actualMsg =
        spe.getException() == null ? spe.getMessage() : spe.getException().getMessage();
    assertEquals("Exception message", expectedMsg, actualMsg);
  }
Exemple #5
0
 @Override
 public void fatalError(final SAXParseException e) {
   ++_error_count;
   _valid = false;
   throw new RuntimeException(
       "Fatal XML error at line " + e.getLineNumber() + ": \n" + e.getMessage());
 }
Exemple #6
0
  /**
   * Parses a given .svg for nodes
   *
   * @return <b>bothNodeLists</b> an Array with two NodeLists
   */
  public static NodeList[] parseSVG(Date date) {

    /* As it has to return two things, it can not return them
     * directly but has to encapsulate it in another object.
     */
    NodeList[] bothNodeLists = new NodeList[2];
    ;
    try {

      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

      String SVGFileName = "./draw_map_svg.svg";
      File svgMap = new File(SVGFileName);

      System.out.println("Parsing the svg"); // Status message #1 Parsing
      System.out.println("This should not longer than 30 seconds"); // Status message #2 Parsing

      Document doc = docBuilder.parse(SVGFileName);

      // "text" is the actual planet/warplanet
      NodeList listOfPlanetsAsXMLNode = doc.getElementsByTagName("text");

      // "line" is the line drawn by a warplanet. Used for calculation of warplanet coordinates.
      NodeList listOfLinesAsXMLNode = doc.getElementsByTagName("line");
      bothNodeLists[0] = listOfPlanetsAsXMLNode;
      bothNodeLists[1] = listOfLinesAsXMLNode;

      // normalize text representation
      doc.getDocumentElement().normalize();

      // Build the fileName the .svg should be renamed to, using the dateStringBuilder
      String newSVGFileName = MapTool.dateStringBuilder(MapTool.getKosmorDate(date), date);
      newSVGFileName = newSVGFileName.concat(" - Map - kosmor.com - .svg");

      // Making sure the directory does exist, if not, it is created
      File svgdir = new File("svg");
      if (!svgdir.exists() || !svgdir.isDirectory()) {
        svgdir.mkdir();
      }

      svgMap.renameTo(new File(svgdir + "\\" + newSVGFileName));

      System.out.println("Done parsing"); // Status message #3 Parsing

    } catch (SAXParseException err) {
      System.out.println(
          "** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
      System.out.println(" " + err.getMessage());

    } catch (SAXException e) {
      Exception x = e.getException();
      ((x == null) ? e : x).printStackTrace();

    } catch (Throwable t) {
      t.printStackTrace();
    }

    return bothNodeLists;
  }
Exemple #7
0
 public void error1(SAXParseException exc) throws SAXParseException {
   if (exc.getMessage()
       .equals(
           "cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'b:person'."))
     ; // suppress
   else throw exc;
 }
 /** 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();
   }
 }
Exemple #9
0
  public void makeGraph(String inputFile, String outputFile) {
    try {

      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
      docBuilderFactory.setValidating(false);
      docBuilderFactory.setNamespaceAware(false);
      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
      Document doc = docBuilder.parse(new File(inputFile));
      doc.getDocumentElement().normalize();
      parseCdaXml(doc);
      System.out.println(" Graph contains : " + data.graph.nodeList.size());

    } catch (SAXParseException err) {
      System.out.println(
          "** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
      System.out.println(" " + err.getMessage());

    } catch (SAXException e) {
      Exception x = e.getException();
      ((x == null) ? e : x).printStackTrace();

    } catch (Throwable t) {
      t.printStackTrace();
    }
  }
 public Document getDocument(InputStream paramInputStream, boolean paramBoolean)
     throws IOException, JDOMException {
   try {
     Class[] arrayOfClass = new Class[2];
     arrayOfClass[0] = Class.forName("java.io.InputStream");
     arrayOfClass[1] = Boolean.TYPE;
     Object[] arrayOfObject = new Object[2];
     arrayOfObject[0] = paramInputStream;
     arrayOfObject[1] = new Boolean(false);
     Document localDocument =
         (Document)
             Class.forName("org.apache.crimson.tree.XmlDocument")
                 .getMethod("createXmlDocument", arrayOfClass)
                 .invoke(null, arrayOfObject);
     return localDocument;
   } catch (InvocationTargetException localInvocationTargetException) {
     Throwable localThrowable = localInvocationTargetException.getTargetException();
     if ((localThrowable instanceof SAXParseException)) {
       SAXParseException localSAXParseException = (SAXParseException) localThrowable;
       throw new JDOMException(
           "Error on line "
               + localSAXParseException.getLineNumber()
               + " of XML document: "
               + localSAXParseException.getMessage(),
           localSAXParseException);
     }
     if ((localThrowable instanceof IOException)) throw ((IOException) localThrowable);
     throw new JDOMException(localThrowable.getMessage(), localThrowable);
   } catch (Exception localException) {
     throw new JDOMException(
         localException.getClass().getName() + ": " + localException.getMessage(), localException);
   }
 }
Exemple #11
0
 public static void main(String[] args) throws Exception {
   String cmd = args[0];
   if (cmd.equals("validar")) {
     String file = args[1];
     CFD2 cfd = CFD2Factory.load(new File(file));
     ValidationErrorHandler handler = new ValidationErrorHandler();
     cfd.validar(handler);
     List<SAXParseException> errors = handler.getErrors();
     if (errors.size() > 0) {
       for (SAXParseException e : errors) {
         System.err.printf("%s %s\n", file, e.getMessage());
       }
       System.exit(1);
     }
   } else if (cmd.equals("verificar")) {
     String file = args[1];
     CFD2 cfd = CFD2Factory.load(new File(file));
     if (args.length == 3) {
       Certificate cert = KeyLoader.loadX509Certificate(new FileInputStream(args[2]));
       cfd.verificar(cert);
     } else {
       cfd.verificar();
     }
   } else if (cmd.equals("sellar")) {
     // JOptionPane.showMessageDialog(null, "sellar");
     String file = args[1];
     CFD2 cfd = CFD2Factory.load(new File(file));
     PrivateKey key = KeyLoader.loadPKCS8PrivateKey(new FileInputStream(args[2]), args[3]);
     X509Certificate cert = KeyLoader.loadX509Certificate(new FileInputStream(args[4]));
     cfd.sellar(key, cert);
     OutputStream out = new FileOutputStream(args[5]);
     cfd.guardar(out);
     System.out.println("Proceso terminado archivo guardado en " + args[5]);
   }
 }
 /** @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) */
 public void warning(SAXParseException exception) throws SAXException {
   System.err.println(
       "error occured while reading descriptor file [line: "
           + exception.getLineNumber()
           + "]:"
           + exception.getMessage());
 }
  private Document getW3cDoc(
      MortalLogger logger,
      DesignTimeUtils designTime,
      ResourceOracle resourceOracle,
      String templatePath)
      throws UnableToCompleteException {

    Resource resource = resourceOracle.getResourceMap().get(templatePath);
    if (null == resource) {
      logger.die("Unable to find resource: " + templatePath);
    }

    Document doc = null;
    try {
      String content = designTime.getTemplateContent(templatePath);
      if (content == null) {
        content = Util.readStreamAsString(resource.openContents());
      }
      doc =
          new W3cDomHelper(logger.getTreeLogger(), resourceOracle)
              .documentFor(content, resource.getPath());
    } catch (IOException iex) {
      logger.die("Error opening resource:" + resource.getLocation(), iex);
    } catch (SAXParseException e) {
      logger.die("Error parsing XML (line " + e.getLineNumber() + "): " + e.getMessage(), e);
    }
    return doc;
  }
  /** A document with an unknown license id. */
  public void testLicenseIdNotFound() throws Exception {
    // we define a license named "lic1" and then reference "lic2" instead
    String document =
        "<?xml version=\"1.0\"?>"
            + OPEN_TAG_REPO
            + "<r:license id=\"lic1\"> some license </r:license> "
            + "<r:tool> <r:uses-license ref=\"lic2\" /> <r:revision>1</r:revision> "
            + "<r:min-platform-tools-rev>1</r:min-platform-tools-rev> "
            + "<r:archives> <r:archive os=\"any\"> <r:size>1</r:size> <r:checksum>2822ae37115ebf13412bbef91339ee0d9454525e</r:checksum> "
            + "<r:url>url</r:url> </r:archive> </r:archives> </r:tool>"
            + CLOSE_TAG_REPO;

    Source source = new StreamSource(new StringReader(document));

    // don't capture the validator errors, we want it to fail and catch the exception
    Validator validator = getRepoValidator(SdkRepoConstants.NS_LATEST_VERSION, null);
    try {
      validator.validate(source);
    } catch (SAXParseException e) {
      // We expect a parse error referring to this grammar rule
      assertRegex("cvc-id.1: There is no ID/IDREF binding for IDREF 'lic2'.*", e.getMessage());
      return;
    }
    // If we get here, the validator has not failed as we expected it to.
    fail();
  }
  /** The latest XSD repository-6 should fail when an 'extra' is present. */
  public void testExtraPathWithSlash() throws Exception {
    String document =
        "<?xml version=\"1.0\"?>"
            + OPEN_TAG_REPO
            + "<r:extra> <r:revision>1</r:revision> <r:path>path</r:path> "
            + "<r:archives> <r:archive os=\"any\"> <r:size>1</r:size> <r:checksum>2822ae37115ebf13412bbef91339ee0d9454525e</r:checksum> "
            + "<r:url>url</r:url> </r:archive> </r:archives> </r:extra>"
            + CLOSE_TAG_REPO;

    Source source = new StreamSource(new StringReader(document));

    // don't capture the validator errors, we want it to fail and catch the exception
    Validator validator = getRepoValidator(SdkRepoConstants.NS_LATEST_VERSION, null);
    try {
      validator.validate(source);
    } catch (SAXParseException e) {
      // We expect a parse error referring to this grammar rule
      assertRegex(
          "cvc-complex-type.2.4.a: Invalid content was found starting with element 'r:extra'.*",
          e.getMessage());
      return;
    }
    // If we get here, the validator has not failed as we expected it to.
    fail();
  }
  /** A document a slash in an extra path. */
  public void testExtraPathWithSlash() throws Exception {
    // we define a license named "lic1" and then reference "lic2" instead
    String document =
        "<?xml version=\"1.0\"?>"
            + OPEN_TAG
            + "<r:extra> <r:revision>1</r:revision> <r:path>path/cannot\\contain\\segments</r:path> "
            + "<r:archives> <r:archive os=\"any\"> <r:size>1</r:size> <r:checksum>2822ae37115ebf13412bbef91339ee0d9454525e</r:checksum> "
            + "<r:url>url</r:url> </r:archive> </r:archives> </r:extra>"
            + CLOSE_TAG;

    Source source = new StreamSource(new StringReader(document));

    // don't capture the validator errors, we want it to fail and catch the exception
    Validator validator = getValidator(SdkRepository.NS_LATEST_VERSION, null);
    try {
      validator.validate(source);
    } catch (SAXParseException e) {
      // We expect a parse error referring to this grammar rule
      assertRegex(
          "cvc-pattern-valid: Value 'path/cannot\\\\contain\\\\segments' is not facet-valid with respect to pattern.*",
          e.getMessage());
      return;
    }
    // If we get here, the validator has not failed as we expected it to.
    fail();
  }
Exemple #17
0
  private void printError(String type, SAXParseException ex) {
    StringBuffer sb = new StringBuffer(128);
    sb.append("[");
    sb.append(type);
    sb.append("] ");
    String systemId = ex.getSystemId();
    if (systemId != null) {
      int index = systemId.lastIndexOf('/');
      if (index != -1) {
        systemId = systemId.substring(index + 1);
      }
      sb.append(systemId);
    }
    sb.append(':');
    sb.append(ex.getLineNumber());
    sb.append(':');
    sb.append(ex.getColumnNumber());
    sb.append(": ");
    sb.append(ex.getMessage());

    String s = sb.toString();
    if (m_messages == null) {
      m_messages = new ArrayList<String>();
    }
    m_messages.add(s);
  }
  public WebXMLDefinition loadWebXML() throws Exception {
    URL url = _bundle.getEntry("WEB-INF/web.xml");

    if (url != null) {
      try (InputStream inputStream = url.openStream()) {
        SAXParser saxParser = _saxParserFactory.newSAXParser();

        XMLReader xmlReader = saxParser.getXMLReader();

        xmlReader.setContentHandler(this);

        xmlReader.parse(new InputSource(inputStream));
      } catch (SAXParseException saxpe) {
        String message = saxpe.getMessage();

        if (message.contains("DOCTYPE is disallowed")) {
          throw new Exception(
              "WEB-INF/web.xml must be updated to the Servlet 2.4 " + "specification");
        }

        throw saxpe;
      }
    }

    return _webXMLDefinition;
  }
  public static ParentalControlConcern parse(File file) {

    try {

      log.info("Parsing '" + file.getCanonicalPath() + "'...");
      SAXParserFactory factory = SAXParserFactory.newInstance();
      factory.setNamespaceAware(true);
      factory.setValidating(true);
      SAXParser parser = factory.newSAXParser();
      parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
      ParentalControlConcernHandler handler = new ParentalControlConcernHandler();
      parser.parse(file, handler);
      log.info("Parsed '" + file.getCanonicalPath() + "'");
      return handler.result;

    } catch (SAXParseException ex) {

      log.error(
          "Could not validate the parental control concern XML file!  Validation error follows.");
      log.error(ex.getMessage());
      ex.printStackTrace();
      return null;

    } catch (Exception ex) {

      log.error(ex);
      return null;
    }
  }
Exemple #20
0
  /** Gets the error, nicely formatted */
  protected String getLocationString(final SAXParseException e) {
    final StringBuffer sb = new StringBuffer(256);
    String systemId = e.getSystemId();

    if (Objects.nonNull(systemId)) {
      final int index = systemId.lastIndexOf('/');

      if (index != -1) {
        systemId = systemId.substring(index + 1);
      }

      sb.append(systemId);
      sb.append(':');
    }

    sb.append("line ");
    sb.append(e.getLineNumber());
    sb.append(":col ");
    sb.append(e.getColumnNumber());
    sb.append(':');
    sb.append(e.getMessage());

    // e.printStackTrace();

    return sb.toString();
  } // getLocationString()
Exemple #21
0
  public static void run() {
    try {
      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
      Document doc = docBuilder.parse(new File(TICKET_XML));

      // normalize text representation
      doc.getDocumentElement().normalize();
      System.out.println(
          "Root element of the doc is:  " + doc.getDocumentElement().getNodeName() + "");
      NodeList serviceNode = doc.getElementsByTagName("service");
      System.out.println("---service---");
      for (int s = 0; s < serviceNode.getLength(); s++) {
        Node firstServiceNode = serviceNode.item(s);
        if (firstServiceNode.getNodeType() == Node.ELEMENT_NODE) {
          Element serviceElement = (Element) firstServiceNode;
          String serviceID = serviceElement.getAttribute("ID");
          System.out.println(serviceID);
          String serviceName = serviceElement.getAttribute("name");
          System.out.println(serviceName);
          String serviceScheduleType = serviceElement.getAttribute("scheduleType");
          System.out.println(serviceScheduleType);
          String serviceAuthenticationType = serviceElement.getAttribute("authenticationType");
          System.out.println(serviceAuthenticationType);
          String serviceDeviceEndpoint = serviceElement.getAttribute("deviceEndpoint");
          System.out.println(serviceDeviceEndpoint);
          String serviceBusInterfaceEndpoint = serviceElement.getAttribute("businterfaceEndpoint");
          System.out.println(serviceBusInterfaceEndpoint);
        }
      }

      NodeList savoirNode = doc.getElementsByTagName("SAVOIR");
      System.out.println("------SAVOIR------");
      for (int s = 0; s < savoirNode.getLength(); s++) {
        Node firstSavoirNode = savoirNode.item(s);
        if (firstSavoirNode.getNodeType() == Node.ELEMENT_NODE) {
          Element savoirElement = (Element) firstSavoirNode;
          String protocol = savoirElement.getAttribute("protocol");
          String ipAddress = savoirElement.getAttribute("ipAddress");
          String portNumber = savoirElement.getAttribute("portNumber");
          System.out.println(protocol + "://" + ipAddress + ":" + portNumber);
          String savoirTopic = savoirElement.getAttribute("SAVOIRTopic");
          System.out.println(savoirTopic);
          String serviceTopic = savoirElement.getAttribute("serviceTopic");
          System.out.println(serviceTopic);
        }
      }
    } catch (SAXParseException err) {
      System.out.println(
          "** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
      System.out.println(" " + err.getMessage());
    } catch (SAXException e) {
      Exception x = e.getException();
      ((x == null) ? e : x).printStackTrace();
    } catch (Throwable t) {
      t.printStackTrace();
    }
    System.exit(0);
  }
Exemple #22
0
 public void fatalError(SAXParseException arg0) throws SAXException {
   Assert.fail(
       atomTypeList
           + " is not valid on line "
           + arg0.getLineNumber()
           + ": "
           + arg0.getMessage());
 }
Exemple #23
0
 private void reportIt(SAXParseException e, String m) {
   StringWriter wtr = new StringWriter();
   PrintWriter pwtr = new PrintWriter(wtr);
   e.printStackTrace(pwtr);
   String message = m + e.getMessage() + "\n" + wtr.toString();
   logger.error(message);
   pwtr.close();
 }
  public void doSubmitFlight() { // per ora contemplati solo voli andata e ritorno
    System.out.println("In submit flight");
    flights.clear();
    // get cambio valuta
    CallCurrencyService currencySrv = new CallCurrencyService();
    Double cambio = new Double(1);
    try {
      cambio = currencySrv.call();
    } catch (RemoteException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    CallCleartripService service = new CallCleartripService();
    // codifico i parametri:
    System.out.println("DECODED: " + from);
    from = AirCodeUtils.airportToCode.get(from);
    to = AirCodeUtils.airportToCode.get(to);
    System.out.println("CODED: " + from);
    try {
      // formato date yyyy-MM-dd
      flights =
          service.call(
              from,
              to,
              sdfDashReverse.format(flightDepDate),
              sdfDashReverse.format(flightReturnDate),
              numberPeople,
              cabinType,
              cambio,
              4);
    } catch (SAXParseException e) {
      e.printStackTrace();
      // non trovati voli
      System.out.println("MESS: " + e.getMessage());
      if (e.getMessage() != null && e.getMessage().contains("Content is not allowed in prolog"))
        setErrorMessage("Test environment temporarily not available");

    } catch (Exception e) {
      e.printStackTrace();
      // non trovati voli
      System.out.println("MESSAGE: " + e.getMessage());
      if (e.getMessage() != null && e.getMessage().contains("Content is not allowed in prolog"))
        setErrorMessage("Test environment temporarily not available");
    }
    firstPageVisit = false;
  }
Exemple #25
0
 @Override
 public void warning(final SAXParseException e) {
   ++_warning_count;
   if (_error_messages.length() > 1) {
     _error_messages.append(ForesterUtil.LINE_SEPARATOR);
   }
   _warning_messages.append("[line: " + e.getLineNumber() + "] " + e.getMessage());
 }
 // dump warnings too
 public void warning(SAXParseException err) throws SAXParseException {
   Debug.trace(
       "** Warning" // NOT LOCALIZABLE
           + ", line "
           + err.getLineNumber() // NOT LOCALIZABLE
           + ", uri "
           + err.getSystemId()); // NOT LOCALIZABLE
   Debug.trace("   " + err.getMessage());
 }
  private String getParseExceptionInfo(SAXParseException spe) {
    String systemId = spe.getSystemId();

    if (systemId == null) {
      systemId = "null";
    }

    return "URI=" + systemId + " Line=" + spe.getLineNumber() + ": " + spe.getMessage();
  }
  public ByteArrayOutputStream cleanup(InputStream xml) throws XServerException {
    inputXml = xml;

    // Use the default (non-validating) parser
    SAXParserFactory factory = SAXParserFactory.newInstance();

    try {
      // Parse the input
      SAXParser saxParser = factory.newSAXParser();
      saxParser.parse(inputXml, this);

      // close the stream
      inputXml.close();
    } catch (SAXParseException spe) {
      // Use the contained exception, if any
      Exception x = spe;

      if (spe.getException() != null) {
        x = spe.getException();
      }

      // Error generated by the parser
      LOG.warn(
          "XMLCleanup.cleanup() parsing exception: "
              + spe.getMessage()
              + " - xml line "
              + spe.getLineNumber()
              + ", uri "
              + spe.getSystemId(),
          x);
    } catch (SAXException sxe) {
      // Error generated by this application
      // (or a parser-initialization error)
      Exception x = sxe;

      if (sxe.getException() != null) {
        x = sxe.getException();
      }

      LOG.warn("XMLCleanup.cleanup() SAX exception: " + sxe.getMessage(), x);
    } catch (ParserConfigurationException pce) {
      // Parser with specified options can't be built
      LOG.warn("XMLCleanup.cleanup() SAX parser cannot be built with " + "specified options");
    } catch (IOException ioe) {
      // I/O error
      LOG.warn("XMLCleanup.cleanup() IO exception", ioe);
    } catch (Throwable t) {
      LOG.warn("XMLCleanup.cleanup() exception", t);
    }

    if (error) {
      throw new XServerException(error_code, error_text);
    }

    return bytes;
  }
    private void addException(SAXParseException exception) {
      if (builder.length() > 0) builder.append("\n");

      builder
          .append("[")
          .append(exception.getLineNumber())
          .append(":")
          .append(exception.getColumnNumber());
      builder.append("] ").append(exception.getMessage());
    }
 private void Message(String mode, SAXParseException exception) {
   System.out.println(
       mode
           + " Line: "
           + exception.getLineNumber()
           + " URI: "
           + exception.getSystemId()
           + "\n"
           + " Message: "
           + exception.getMessage());
 }