Java Code Examples for org.xml.sax.SAXParseException

The following examples show how to use org.xml.sax.SAXParseException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * Returns a text indicating at which line and column the error occured.
 * 
 * @param ex the SAXParseException exception
 * @return the location string
 */
public static String getSAXErrorMessage(SAXParseException ex) {
    StringBuilder str = new StringBuilder();

    String systemId = ex.getSystemId();
    if (systemId != null) {
        int index = systemId.lastIndexOf('/');

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

        str.append(systemId).append(": ");
    }

    str.append("line ").append(ex.getLineNumber());
    str.append(", column ").append(ex.getColumnNumber());
    str.append(", ");
    str.append(ex.getLocalizedMessage());

    return str.toString();
}
 
Example 2
Source Project: ade   Source File: AdeUtilMain.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected void validateGood(File file) throws IOException, SAXException,
		AdeException {
	System.out.println("Starting");

	String fileName_Flowlayout_xsd = Ade.getAde().getConfigProperties()
			.getXsltDir()
			+ FLOW_LAYOUT_XSD_File_Name;
	Source schemaFile = new StreamSource(fileName_Flowlayout_xsd);
	SchemaFactory sf = SchemaFactory
			.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
	Schema mSchema = sf.newSchema(schemaFile);

	System.out.println("Validating " + file.getPath());
	Validator val = mSchema.newValidator();
	FileInputStream fis = new FileInputStream(file);
	StreamSource streamSource = new StreamSource(fis);

	try {
		val.validate(streamSource);
	} catch (SAXParseException e) {
		System.out.println(e);
		throw e;
	}
	System.out.println("SUCCESS!");
}
 
Example 3
Source Project: EventCoreference   Source File: EsoReader.java    License: Apache License 2.0 6 votes vote down vote up
public void parseFile(String filePath) {
    String myerror = "";
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(false);
        SAXParser parser = factory.newSAXParser();
        InputSource inp = new InputSource (new FileReader(filePath));
        parser.parse(inp, this);
    } catch (SAXParseException err) {
        myerror = "\n** Parsing error" + ", line " + err.getLineNumber()
                + ", uri " + err.getSystemId();
        myerror += "\n" + err.getMessage();
        System.out.println("myerror = " + myerror);
    } catch (SAXException e) {
        Exception x = e;
        if (e.getException() != null)
            x = e.getException();
        myerror += "\nSAXException --" + x.getMessage();
        System.out.println("myerror = " + myerror);
    } catch (Exception eee) {
        eee.printStackTrace();
        myerror += "\nException --" + eee.getMessage();
        System.out.println("myerror = " + myerror);
    }
}
 
Example 4
Source Project: openjdk-8   Source File: Internalizer.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void reportError( Element errorSource,
    String formattedMsg, Exception nestedException ) {

    SAXParseException e = new SAXParseException2( formattedMsg,
        forest.locatorTable.getStartLocation(errorSource),
        nestedException );
    errorHandler.error(e);
}
 
Example 5
public void fatalError(SAXParseException exception) throws SAXException {
   if (this.accept(exception)) {
      String msg = "FATAL " + this.toString(exception);
      this.exceptionFatalList.add(msg);
   }

}
 
Example 6
Source Project: RADL   Source File: Xml.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isMissingSchemaError(SAXParseException exception) {
  String message = exception.getMessage();
  if (message == null) {
    return false;
  }
  return message.contains("no grammar found") || message.contains("must match DOCTYPE root \"null\"");
}
 
Example 7
Source Project: Bytecoder   Source File: ErrorHandlerProxy.java    License: Apache License 2.0 5 votes vote down vote up
public void error(SAXParseException e) throws SAXException {
    XMLErrorHandler eh = getErrorHandler();
    if (eh instanceof ErrorHandlerWrapper) {
        ((ErrorHandlerWrapper)eh).fErrorHandler.error(e);
    }
    else {
        eh.error("","",ErrorHandlerWrapper.createXMLParseException(e));
    }
    // if an XNIException is thrown, just let it go.
    // REVISIT: is this OK? or should we try to wrap it into SAXException?
}
 
Example 8
@Override
public void fatalError(SAXParseException e) {
	if (log.isFatalEnabled())
	{
		log.fatal("Error parsing styled text.", e);
	}
}
 
Example 9
private void error(SAXParseException message) throws BuildException {
    noteError();
    try {
        if (eh != null) {
            eh.error(message);
        }
    } catch (SAXException e) {
        throw new BuildException(e);
    }
}
 
Example 10
Source Project: caja   Source File: Driver.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Reports a warning without line/col
 * 
 * @param message
 *            the message
 * @throws SAXException
 */
protected void warnWithoutLocation(String message) throws SAXException {
    ErrorHandler errorHandler = tokenizer.getErrorHandler();
    if (errorHandler == null) {
        return;
    }
    SAXParseException spe = new SAXParseException(message, null,
            tokenizer.getSystemId(), -1, -1);
    errorHandler.warning(spe);
}
 
Example 11
Source Project: flex-blazeds   Source File: AmfxMessageDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Process FatalError of a SAXParseException.
 *
 * @param exception SAXParseException
 * @throws SAXException rethrow the SAXException
 */
public void fatalError(SAXParseException exception) throws SAXException
{
    if ((exception.getException() != null) && (exception.getException() instanceof MessageException))
        throw (MessageException)exception.getException();
    throw new MessageException(exception.getMessage());
}
 
Example 12
Source Project: lams   Source File: ErrorLogger.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void logErrors() {
	if ( errors != null ) {
		for ( SAXParseException e : errors ) {
			if ( file == null ) {
				LOG.parsingXmlError( e.getLineNumber(), e.getMessage() );
			}
			else {
				LOG.parsingXmlErrorForFile( file, e.getLineNumber(), e.getMessage() );
			}
		}
	}
}
 
Example 13
public void fatalError(SAXParseException exception) throws SAXException {
   if (this.accept(exception)) {
      String msg = "FATAL " + this.toString(exception);
      this.exceptionFatalList.add(msg);
   }

}
 
Example 14
Source Project: Java8CN   Source File: XMLFilterImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Filter a warning event.
 *
 * @param e The warning as an exception.
 * @exception org.xml.sax.SAXException The client may throw
 *            an exception during processing.
 */
public void warning (SAXParseException e)
    throws SAXException
{
    if (errorHandler != null) {
        errorHandler.warning(e);
    }
}
 
Example 15
/**
 * Returns the human readable string representation of the
 * {@link org.xml.sax.Locator} part of the specified
 * {@link SAXParseException}.
 *
 * @return  non-null valid object.
 */
protected final String getLocationString( SAXParseException e ) {
    if(e.getLineNumber()!=-1 || e.getSystemId()!=null) {
        int line = e.getLineNumber();
        return Messages.format( Messages.LINE_X_OF_Y,
            line==-1?"?":Integer.toString( line ),
            getShortName( e.getSystemId() ) );
    } else {
        return Messages.format( Messages.UNKNOWN_LOCATION );
    }
}
 
Example 16
Source Project: jdk8u60   Source File: ParserAdapter.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct an exception for the current context.
 *
 * @param message The error message.
 */
private SAXParseException makeException (String message)
{
    if (locator != null) {
        return new SAXParseException(message, locator);
    } else {
        return new SAXParseException(message, null, null, -1, -1);
    }
}
 
Example 17
Source Project: kogito-runtimes   Source File: BaseAbstractHandler.java    License: Apache License 2.0 5 votes vote down vote up
public void emptyContentCheck(final String element,
                              final String content,
                              final ExtensibleXmlParser xmlPackageReader) throws SAXException {
    if ( content == null || content.trim().equals( "" ) ) {
        throw new SAXParseException( "<" + element + "> requires content",
                                     xmlPackageReader.getLocator() );
    }
}
 
Example 18
Source Project: openjdk-8   Source File: CompactSyntax.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void doError(String message, Token tok) {
  hadError = true;
  if (eh != null) {
    LocatorImpl loc = new LocatorImpl();
    loc.setLineNumber(tok.beginLine);
    loc.setColumnNumber(tok.beginColumn);
    loc.setSystemId(sourceUri);
    try {
      eh.error(new SAXParseException(message, loc));
    }
    catch (SAXException se) {
      throw new BuildException(se);
    }
  }
}
 
Example 19
Source Project: Android-UPnP-Browser   Source File: UPnPDevice.java    License: Apache License 2.0 5 votes vote down vote up
public void downloadSpecs() throws Exception {
	Request request = new Request.Builder()
		.url(mLocation)
		.build();

	Response response = mClient.newCall(request).execute();
	if (!response.isSuccessful()) {
		throw new IOException("Unexpected code " + response);
	}

	mRawXml = response.body().string();

	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder db = dbf.newDocumentBuilder();
	InputSource source = new InputSource(new StringReader(mRawXml));
	Document doc;
	try {
		doc = db.parse(source);
	}
	catch (SAXParseException e) {
		return;
	}
	XPath xPath = XPathFactory.newInstance().newXPath();

	mProperties.put("xml_icon_url", xPath.compile("//icon/url").evaluate(doc));
	generateIconUrl();
	mProperties.put("xml_friendly_name", xPath.compile("//friendlyName").evaluate(doc));
}
 
Example 20
public static void ensureLocationSet(TransformerException exception)
{
  // SourceLocator locator = exception.getLocator();
  SourceLocator locator = null;
  Throwable cause = exception;

  // Try to find the locator closest to the cause.
  do
  {
    if(cause instanceof SAXParseException)
    {
      locator = new SAXSourceLocator((SAXParseException)cause);
    }
    else if (cause instanceof TransformerException)
    {
      SourceLocator causeLocator = ((TransformerException)cause).getLocator();
      if(null != causeLocator)
        locator = causeLocator;
    }

    if(cause instanceof TransformerException)
      cause = ((TransformerException)cause).getCause();
    else if(cause instanceof SAXException)
      cause = ((SAXException)cause).getException();
    else
      cause = null;
  }
  while(null != cause);

  exception.setLocator(locator);
}
 
Example 21
Source Project: ontopia   Source File: OntopiaErrorHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This will report a fatal error that has occurred; this indicates
 * that a rule has been broken that makes continued parsing either
 * impossible or an almost certain waste of time.
 *
 * @param exception <code>SAXParseException</code> that occurred.
 * @throws <code>SAXException</code> when things go wrong
 */
@Override
public void fatalError(SAXParseException exception)
  throws SAXException {
 
  System.out.println("**Parsing Fatal Error**\n" +
       " Line: " +
       exception.getLineNumber() + "\n" +
       " URI: " +
       exception.getSystemId() + "\n" +
       " Message: " +
       exception.getMessage());
  throw new SAXException("Fatal Error encountered");
}
 
Example 22
Source Project: r-course   Source File: ResponseParser.java    License: MIT License 5 votes vote down vote up
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
    try {
        String thisElement = (String) this.elNames.peek();
        if (thisElement != null) {
            if (thisElement.equals("name")) {
                ((Member) this.objects.peek()).setName(new String(ch, start, length));
            } else if (thisElement.equals("value")) {
                ((Value) this.objects.peek()).appendString(new String(ch, start, length));
            } else if (thisElement.equals("i4") || thisElement.equals("int")) {
                ((Value) this.objects.peek()).setInt(new String(ch, start, length));
            } else if (thisElement.equals("boolean")) {
                ((Value) this.objects.peek()).setBoolean(new String(ch, start, length));
            } else if (thisElement.equals("string")) {
                ((Value) this.objects.peek()).appendString(new String(ch, start, length));
            } else if (thisElement.equals("double")) {
                ((Value) this.objects.peek()).setDouble(new String(ch, start, length));
            } else if (thisElement.equals("dateTime.iso8601")) {
                ((Value) this.objects.peek()).setDateTime(new String(ch, start, length));
            } else if (thisElement.equals("base64")) {
                ((Value) this.objects.peek()).setBase64(new String(ch, start, length).getBytes());
            }
        }
    } catch (Exception e) {
        throw new SAXParseException(e.getMessage(), null, e);
    }
}
 
Example 23
Source Project: tomcatsrc   Source File: JspDocumentParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void startPrefixMapping(String prefix, String uri)
    throws SAXException {
    TagLibraryInfo taglibInfo;

    if (directivesOnly && !(JSP_URI.equals(uri))) {
        return;
    }

    try {
        taglibInfo = getTaglibInfo(prefix, uri);
    } catch (JasperException je) {
        throw new SAXParseException(
            Localizer.getMessage("jsp.error.could.not.add.taglibraries"),
            locator,
            je);
    }

    if (taglibInfo != null) {
        if (pageInfo.getTaglib(uri) == null) {
            pageInfo.addTaglib(uri, taglibInfo);
        }
        pageInfo.pushPrefixMapping(prefix, uri);
    } else {
        pageInfo.pushPrefixMapping(prefix, null);
    }
}
 
Example 24
Source Project: openjdk-jdk9   Source File: DTDHandlerBase.java    License: GNU General Public License v2.0 4 votes vote down vote up
public void fatalError(SAXParseException e) throws SAXException {
    throw e;
}
 
Example 25
public final void error(final SAXParseException ex) {
   emitMessage("Continuable parsing error ", ex);
}
 
Example 26
Source Project: netbeans   Source File: XMLFileSystem.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void warning(SAXParseException exception)
throws SAXException {
    throw exception;
}
 
Example 27
Source Project: tcases   Source File: SystemTestDocReader.java    License: MIT License 4 votes vote down vote up
public void startElement( String uri, String localName, String qName, Attributes attributes) throws SAXException
{
InputHandler parent = (InputHandler) getParent();

String valueAtr = getAttribute( attributes, VALUE_ATR);
String naAtr = StringUtils.trimToNull( getAttribute( attributes, NA_ATR));
boolean na = naAtr != null && BooleanUtils.toBoolean( naAtr);

if( valueAtr == null && !na)
  {
  throw
    new SAXParseException
    ( "No \"value\" attribute specified",
      getDocumentLocator()); 
  }
else if( valueAtr != null && na)
  {
  throw
    new SAXParseException
    ( "No \"value\" attribute allowed for a variable that is \"not applicable\"",
      getDocumentLocator()); 
  }

VarBinding binding =
  na
  ? new VarNaBinding( requireIdPath( attributes, NAME_ATR), parent.getType())
  : new VarBinding( requireIdPath( attributes, NAME_ATR), parent.getType(), toObject( valueAtr));

TestCaseHandler testCaseHandler = getTestCaseHandler();
TestCase testCase = testCaseHandler.getTestCase();

String failureAtr = StringUtils.trimToNull( getAttribute( attributes, FAILURE_ATR));
boolean failure = failureAtr != null && BooleanUtils.toBoolean( failureAtr);
if( failure && !testCaseHandler.isFailure())
  {
  throw
    new SAXParseException
    ( "Unexpected failure value=\"" + binding.getValue()
      + "\" for success test case " + testCase.getId(),
      getDocumentLocator()); 
  }

binding.setValueValid( !failure);
try
  {
  testCase.addVarBinding( binding);
  }
catch( Exception e)
  {
  throw new SAXParseException( e.getMessage(), getDocumentLocator());
  }

setVarBinding( binding);
}
 
Example 28
Source Project: j2objc   Source File: DocumentBuilderFactoryTest.java    License: Apache License 2.0 4 votes vote down vote up
public void fatalError(SAXParseException ex) {
    if (parseException == null) {
        parseException = ex;
    }
}
 
Example 29
public JDefinedClass createClass(
    JClassContainer parent, int mod, String name, Locator source, ClassType kind ) {

    if(!JJavaName.isJavaIdentifier(name)) {
        // report the error
        errorReceiver.error( new SAXParseException(
            Messages.format( Messages.ERR_INVALID_CLASSNAME, name ), source ));
        return createDummyClass(parent);
    }


    try {
        if(parent.isClass() && kind==ClassType.CLASS)
            mod |= JMod.STATIC;

        JDefinedClass r = parent._class(mod,name,kind);
        // use the metadata field to store the source location,
        // so that we can report class name collision errors.
        r.metadata = source;

        return r;
    } catch( JClassAlreadyExistsException e ) {
        // class collision.
        JDefinedClass cls = e.getExistingClass();

        // report the error
        errorReceiver.error( new SAXParseException(
            Messages.format( Messages.ERR_CLASSNAME_COLLISION, cls.fullName() ),
            (Locator)cls.metadata ));
        errorReceiver.error( new SAXParseException(
            Messages.format( Messages.ERR_CLASSNAME_COLLISION_SOURCE, name ),
            source ));

        if( !name.equals(cls.name()) ) {
            // on Windows, FooBar and Foobar causes name collision
            errorReceiver.error( new SAXParseException(
                Messages.format( Messages.ERR_CASE_SENSITIVITY_COLLISION,
                    name, cls.name() ), null ) );
        }

        if(Util.equals((Locator)cls.metadata,source)) {
            errorReceiver.error( new SAXParseException(
                Messages.format( Messages.ERR_CHAMELEON_SCHEMA_GONE_WILD ),
                source ));
        }

        return createDummyClass(parent);
    }
}
 
Example 30
@SuppressWarnings(value = "CallToThreadDumpStack")
@Override
public void warning(SAXParseException e) throws SAXException {
    e.printStackTrace();
}