Beispiel #1
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()
Beispiel #2
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);
  }
Beispiel #3
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));
  }
Beispiel #4
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());
 }
Beispiel #5
0
    public synchronized Transformer getTransformer(String framework, String filename) {
      if (filename == null || filename.length() == 0) {
        throw new IllegalArgumentException("filename cannot be null or empty");
      }
      String key = framework + "-" + filename;

      Templates t = (Templates) pool.getTemplates().get(key);
      String s = null;

      if (t == null) {
        try {
          WOApplication app = WOApplication.application();
          WOResourceManager rm = app.resourceManager();

          TransformerFactory fac = TransformerFactory.newInstance();

          log.debug("creating template for file " + filename + " in framework " + framework);
          InputStream is = rm.inputStreamForResourceNamed(filename, framework, null);
          if (is == null) {
            log.debug("trying with framework = null");
            is = rm.inputStreamForResourceNamed(filename, null, null);
            if (is == null) {
              throw new IllegalArgumentException("inputStream is null");
            }
          }
          if (is.available() == 0) {
            throw new IllegalArgumentException(
                "InputStream has 0 bytes available, cannot read xsl file!");
          }
          s = ERXFileUtilities.stringFromInputStream(is);
          s = templateParser.parseTemplateWithObject(s, "@@", app);
          t = fac.newTemplates(new StreamSource(new ByteArrayInputStream(s.getBytes())));

          if (app.isCachingEnabled()) {
            templates.put(key, t);
          }
        } catch (IOException e1) {
          throw NSForwardException._runtimeExceptionForThrowable(e1);
        } catch (TransformerConfigurationException tce) {
          log.error("could not create template " + tce.getLocationAsString(), tce);
          log.error("  cause", tce.getCause());
          if (tce.getCause() != null && tce.getCause() instanceof org.xml.sax.SAXParseException) {
            org.xml.sax.SAXParseException e = (org.xml.sax.SAXParseException) tce.getCause();
            log.error(
                "SAXParseException: line " + e.getLineNumber() + ", column " + e.getColumnNumber());
          }
          log.error("this is the incorrect xsl:>>>" + s + "<<<");
          return null;
        }
      }

      try {
        return t.newTransformer();
      } catch (TransformerConfigurationException tce) {
        log.error("could not create template " + tce.getLocationAsString(), tce);
        log.error("  cause", tce.getCause());
        return null;
      }
    }
 public void fatalError(SAXParseException spe) throws SAXException {
   addError(
       XML_PARSING
           + " - Parsing fatal error on line "
           + spe.getLineNumber()
           + " and column "
           + spe.getColumnNumber(),
       spe);
 }
 public void warning(SAXParseException spe) throws SAXException {
   addWarn(
       XML_PARSING
           + " - Parsing warning on line "
           + spe.getLineNumber()
           + " and column "
           + spe.getColumnNumber(),
       spe);
 }
Beispiel #8
0
 private String getPosition(SAXParseException spe) {
   return new StringBuilder()
       .append("in file '")
       .append(fileName)
       .append("' at line ")
       .append(spe.getLineNumber())
       .append(", col ")
       .append(spe.getColumnNumber())
       .toString();
 }
 public static Location newLocation(SAXParseException spe) {
   LocationImpl loc = new LocusTransformer().new LocationImpl();
   try {
     loc.setColumnNumber(spe.getColumnNumber());
     loc.setLineNumber(spe.getLineNumber());
     loc.setSystemId(spe.getSystemId());
   } catch (Exception e) {
   }
   return loc;
 }
    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 MarshalSAXParseException marshalSAXParseException(SAXParseException exception) {
   return new MarshalSAXParseException(
       exception.getLocalizedMessage(),
       exception.getPublicId(),
       exception.getSystemId(),
       exception.getLineNumber(),
       exception.getColumnNumber(),
       exception.getException(),
       marshalRecord.getOwningObject());
 }
Beispiel #12
0
  /** Reads all data from the file and send it to the sink. */
  public void run() {
    InputStream inputStream = null;

    try {
      SAXParser parser;

      changeSink.initialize(Collections.<String, Object>emptyMap());

      // make "-" an alias for /dev/stdin
      if (file.getName().equals("-")) {
        inputStream = System.in;
      } else {
        inputStream = new FileInputStream(file);
      }

      inputStream =
          new CompressionActivator(compressionMethod).createCompressionInputStream(inputStream);

      parser = SaxParserFactory.createParser();

      parser.parse(inputStream, new OsmChangeHandler(changeSink, enableDateParsing));

      changeSink.complete();

    } catch (SAXParseException e) {
      throw new OsmosisRuntimeException(
          "Unable to parse xml file "
              + file
              + ".  publicId=("
              + e.getPublicId()
              + "), systemId=("
              + e.getSystemId()
              + "), lineNumber="
              + e.getLineNumber()
              + ", columnNumber="
              + e.getColumnNumber()
              + ".",
          e);
    } catch (SAXException e) {
      throw new OsmosisRuntimeException("Unable to parse XML.", e);
    } catch (IOException e) {
      throw new OsmosisRuntimeException("Unable to read XML file " + file + ".", e);
    } finally {
      changeSink.release();

      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          log.log(Level.SEVERE, "Unable to close input stream.", e);
        }
        inputStream = null;
      }
    }
  }
  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());
    }
  }
Beispiel #14
0
 private void print(SAXParseException x) {
   String msg =
       message.format(
           new Object[] {
             x.getSystemId(),
             new Integer(x.getLineNumber()),
             new Integer(x.getColumnNumber()),
             x.getMessage()
           });
   logger.debug(msg);
 }
Beispiel #15
0
 /**
  * catches warning SAXParseExceptions this code sends exception to stdio and allows public classto
  * continue
  *
  * @param e SaxException object
  * @throws SAXException exception
  */
 public void warning(SAXParseException e) throws SAXException {
   System.err.println(
       "Warning at (file "
           + e.getSystemId()
           + ", line "
           + e.getLineNumber()
           + ", char "
           + e.getColumnNumber()
           + "): "
           + e.getMessage());
 }
Beispiel #16
0
 /**
  * catches fatal SAXParseExceptions this code causes exception to continue
  *
  * @param e SAXException object
  * @throws SAXException thrown
  */
 public void fatalError(SAXParseException e) throws SAXException {
   throw new SAXException(
       "Fatal Error at (file "
           + e.getSystemId()
           + ", line "
           + e.getLineNumber()
           + ", char "
           + e.getColumnNumber()
           + "): "
           + e.getMessage());
 }
Beispiel #17
0
  /**
   * Parses a XML input file and returns a newly created and populated Database structure.
   *
   * @param xmlFile The input file to parse.
   * @return Database populated by <code>xmlFile</code>.
   */
  public KualiDatabase parseFile(String xmlFile) throws EngineException {
    try {
      // in case I am missing something, make it obvious
      if (!firstPass) {
        throw new Error("No more double pass");
      }
      // check to see if we alread have parsed the file
      if ((alreadyReadFiles != null) && alreadyReadFiles.contains(xmlFile)) {
        return database;
      } else if (alreadyReadFiles == null) {
        alreadyReadFiles = new Vector(3, 1);
      }

      // remember the file to avoid looping
      alreadyReadFiles.add(xmlFile);

      currentXmlFile = xmlFile;

      saxFactory.setValidating(false);
      SAXParser parser = saxFactory.newSAXParser();

      FileInputStream fileInputStream = null;
      try {
        fileInputStream = new FileInputStream(xmlFile);
      } catch (FileNotFoundException fnfe) {
        throw new FileNotFoundException(new File(xmlFile).getAbsolutePath());
      }
      BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
      try {
        log.info("Parsing file: '" + (new File(xmlFile)).getName() + "'");
        InputSource is = new InputSource(bufferedInputStream);
        is.setSystemId(xmlFile);
        parser.parse(is, this);
      } finally {
        bufferedInputStream.close();
      }
    } catch (SAXParseException e) {
      throw new EngineException(
          "Sax error on line "
              + e.getLineNumber()
              + " column "
              + e.getColumnNumber()
              + " : "
              + e.getMessage(),
          e);
    } catch (Exception e) {
      throw new EngineException(e);
    }
    if (!isExternalSchema) {
      firstPass = false;
    }
    database.doFinalInitialization();
    return database;
  }
 public void warning(SAXParseException exception) throws SAXException {
   try {
     cesspool.reportError(
         exception.getSystemId(),
         exception.getLineNumber(),
         exception.getColumnNumber(),
         exception);
   } catch (XSLToolsException wrapped) {
     throw exception;
   }
 }
Beispiel #19
0
 /**
  * Handles exception which occur when the xml file is parsed
  *
  * @param e the exception which occured while parsing
  * @throws SAXException always
  */
 public void error(SAXParseException e) throws SAXException {
   log.error("Sax parser threw an Exception", e);
   throw new SAXException(
       "Error while parsing "
           + currentXmlFile
           + " at line "
           + e.getLineNumber()
           + " column "
           + e.getColumnNumber()
           + " : "
           + e.getMessage());
 }
Beispiel #20
0
     /**
     * Creates Java Source code (Object model) for the given XML Schema
     * @param InputSource - the InputSource representing the XML schema.
     * @param packageName the package for the generated source files
    **/
    public void generateSource(InputSource source, String packageName) {

        //-- get default parser from Configuration
        Parser parser = null;
        try {
	    parser = Configuration.getParser();
        }
        catch(RuntimeException rte) {}
        if (parser == null) {
            System.out.println("fatal error: unable to create SAX parser.");
            return;
        }

        SchemaUnmarshaller schemaUnmarshaller = null;
        try {
           schemaUnmarshaller = new SchemaUnmarshaller();
        } catch (SAXException e) {
          // can never happen since a SAXException is thrown
          // when we are dealing with an included schema
          e.printStackTrace();
        }

        parser.setDocumentHandler(schemaUnmarshaller);
        parser.setErrorHandler(schemaUnmarshaller);

        try {
            parser.parse(source);
        }
        catch(java.io.IOException ioe) {
            System.out.println("error reading XML Schema file");
            return;
        }
        catch(org.xml.sax.SAXException sx) {

            Exception except = sx.getException();
            if (except == null) except = sx;

            if (except instanceof SAXParseException) {
                SAXParseException spe = (SAXParseException)except;
                System.out.println("SAXParseException: " + spe);
                System.out.print(" - occured at line ");
                System.out.print(spe.getLineNumber());
                System.out.print(", column ");
                System.out.println(spe.getColumnNumber());
            }
            else except.printStackTrace();
            return;
        }

        Schema schema = schemaUnmarshaller.getSchema();
        generateSource(schema, packageName);

    } //-- generateSource
 private void throwError(final SAXParseException e) {
   throw new Error(
       e.getLocalizedMessage()
           + "\n\nPublic ID: "
           + (e.getPublicId() == null ? "None" : e.getPublicId())
           + ", System ID: "
           + (e.getPublicId() == null ? "None" : e.getPublicId())
           + ",\nLine number: "
           + e.getLineNumber()
           + ", Column number: "
           + e.getColumnNumber());
 }
    private static SAXException toSAXException(final SAXParseException exception) {

      final SAXException saxException =
          new SAXException(
              "Line "
                  + exception.getLineNumber()
                  + ':'
                  + exception.getColumnNumber()
                  + ": "
                  + exception.getMessage());
      saxException.setStackTrace(exception.getStackTrace());
      return saxException;
    }
Beispiel #23
0
    private String print(SAXParseException x) {

      String msg =
          message.format(
              new Object[] {
                x.getSystemId(),
                new Integer(x.getLineNumber()),
                new Integer(x.getColumnNumber()),
                x.getMessage()
              });

      return msg;
    } // END print
Beispiel #24
0
 private void showError(SAXParseException e, String m) {
   if (errOn) {
     int c = e.getColumnNumber();
     System.out.println(
         m
             + ": "
             + e.getSystemId()
             + " "
             + e.getLineNumber()
             + ((c == -1) ? "" : ("," + c))
             + ": "
             + e.getMessage());
   }
 }
Beispiel #25
0
 /**
  * Parses mathml from the input into a DOM document. Split out so that subclass can call.
  *
  * @param params Parameters including MathML
  * @param result Blank result object
  * @param start Request start time (milliseconds since epoch)
  * @return Document or null if failed (in which case should return result)
  */
 protected Document parseMathml(MathsEpsParams params, MathsEpsReturn result, long start)
     throws Exception {
   try {
     Document mathml = parseMathml(params.getMathml());
     if (SHOWPERFORMANCE) {
       System.err.println("Parse DOM: " + (System.currentTimeMillis() - start));
     }
     return mathml;
   } catch (SAXParseException e) {
     int line = e.getLineNumber(), col = e.getColumnNumber();
     result.setError("MathML parse error at " + line + ":" + col + " - " + e.getMessage());
     return null;
   }
 }
 public void fullyParseGameData() throws GameParseException {
   m_data = null;
   InputStream input = null;
   String error = null;
   final AtomicReference<String> gameName = new AtomicReference<String>();
   try {
     input = m_url.toURL().openStream();
     try {
       m_data = new GameParser().parse(input, gameName, false);
       m_gameDataFullyLoaded = true;
     } catch (final EngineVersionException e) {
       System.out.println(e.getMessage());
       error = e.getMessage();
     } catch (final SAXParseException e) {
       System.err.println(
           "Could not parse:"
               + m_url
               + " error at line:"
               + e.getLineNumber()
               + " column:"
               + e.getColumnNumber());
       e.printStackTrace();
       error = e.getMessage();
     } catch (final Exception e) {
       System.err.println("Could not parse:" + m_url);
       e.printStackTrace();
       error = e.getMessage();
     }
   } catch (final MalformedURLException e1) {
     e1.printStackTrace();
     error = e1.getMessage();
   } catch (final IOException e1) {
     e1.printStackTrace();
     error = e1.getMessage();
   } finally {
     try {
       if (input != null) {
         input.close();
       }
     } catch (final IOException e) { // ignore
     }
   }
   if (error != null) {
     throw new GameParseException(error);
   }
 }
  /** Creates an XMLParseException from a SAXParseException. */
  protected static XMLParseException createXMLParseException(SAXParseException exception) {
    final String fPublicId = exception.getPublicId();
    final String fExpandedSystemId = exception.getSystemId();
    final int fLineNumber = exception.getLineNumber();
    final int fColumnNumber = exception.getColumnNumber();
    XMLLocator location =
        new XMLLocator() {
          public String getPublicId() {
            return fPublicId;
          }

          public String getExpandedSystemId() {
            return fExpandedSystemId;
          }

          public String getBaseSystemId() {
            return null;
          }

          public String getLiteralSystemId() {
            return null;
          }

          public int getColumnNumber() {
            return fColumnNumber;
          }

          public int getLineNumber() {
            return fLineNumber;
          }

          public int getCharacterOffset() {
            return -1;
          }

          public String getEncoding() {
            return null;
          }

          public String getXMLVersion() {
            return null;
          }
        };
    return new XMLParseException(location, exception.getMessage(), exception);
  } // createXMLParseException(SAXParseException):XMLParseException
Beispiel #28
0
  private void log(SAXParseException spe, String type, Array array) {
    StringBuffer sb = new StringBuffer("[" + type + "] ");

    String id = spe.getSystemId();
    if (!Util.isEmpty(id)) {
      int li = id.lastIndexOf('/');
      if (li != -1) sb.append(id.substring(li + 1));
      else sb.append(id);
    }
    sb.append(':');
    sb.append(spe.getLineNumber());
    sb.append(':');
    sb.append(spe.getColumnNumber());
    sb.append(": ");
    sb.append(spe.getMessage());
    sb.append(" ");
    array.appendEL(sb.toString());
  }
 /**
  * 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());
 }
 /**
  * Verifys an instance document (as represented by the {@link InputStream} conforms to the Life On
  * Earth XML Schema.
  *
  * @param is - instance document
  * @param logErrors - whether to log errors as well as throw an exception.
  * @throws PalantirException - thrown on a validation error with {@link SAXException} as the
  *     cause.
  */
 public static void verifyXMLInstanceDocument(InputStream is, boolean logErrors)
     throws PalantirException {
   try {
     Source document = new SAXSource(new InputSource(is));
     Validator v = getLifeOnEarthSchema().newValidator();
     v.setErrorHandler(XMLErrorHandler.getInstance(logErrors));
     v.validate(document);
   } catch (SAXParseException spe) {
     throw new PalantirException(
         "Validation failed at (line "
             + spe.getLineNumber()
             + ", col "
             + spe.getColumnNumber()
             + "): "
             + spe.getMessage(),
         spe);
   } catch (Exception e) {
     throw new PalantirException(
         "Validation failed before starting because of unexpected error: " + e.getMessage(), e);
   }
 }