use of org.xml.sax.ErrorHandler in project freemarker by apache.
the class NodeModel method parse.
/**
* Same as {@link #parse(InputSource, boolean, boolean)}, but loads from a {@link File}; don't miss the security
* warnings documented there.
*/
public static NodeModel parse(File f, boolean removeComments, boolean removePIs) throws SAXException, IOException, ParserConfigurationException {
DocumentBuilder builder = getDocumentBuilderFactory().newDocumentBuilder();
ErrorHandler errorHandler = getErrorHandler();
if (errorHandler != null)
builder.setErrorHandler(errorHandler);
Document doc = builder.parse(f);
if (removeComments && removePIs) {
simplify(doc);
} else {
if (removeComments) {
removeComments(doc);
}
if (removePIs) {
removePIs(doc);
}
mergeAdjacentText(doc);
}
return wrap(doc);
}
use of org.xml.sax.ErrorHandler in project CodenameOne by codenameone.
the class L10nEditor method importResourceActionPerformed.
// GEN-LAST:event_exportResourceActionPerformed
private void importResourceActionPerformed(java.awt.event.ActionEvent evt) {
// GEN-FIRST:event_importResourceActionPerformed
final String locale = (String) locales.getSelectedItem();
int val = JOptionPane.showConfirmDialog(this, "This will overwrite existing values for " + locale + "\nAre you sure?", "Import", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (val == JOptionPane.YES_OPTION) {
File[] files = ResourceEditorView.showOpenFileChooser("Properties, XML, CSV", "prop", "properties", "l10n", "locale", "xml", "csv");
if (files != null) {
FileInputStream f = null;
try {
f = new FileInputStream(files[0]);
if (files[0].getName().toLowerCase().endsWith("xml")) {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException exception) throws SAXException {
exception.printStackTrace();
}
public void error(SAXParseException exception) throws SAXException {
exception.printStackTrace();
}
public void fatalError(SAXParseException exception) throws SAXException {
exception.printStackTrace();
}
});
xmlReader.setContentHandler(new ContentHandler() {
private String currentName;
private StringBuilder chars = new StringBuilder();
@Override
public void setDocumentLocator(Locator locator) {
}
@Override
public void startDocument() throws SAXException {
}
@Override
public void endDocument() throws SAXException {
}
@Override
public void startPrefixMapping(String prefix, String uri) throws SAXException {
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
}
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if ("string".equals(localName) || "string".equals(qName)) {
currentName = atts.getValue("name");
chars.setLength(0);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("string".equals(localName) || "string".equals(qName)) {
String str = chars.toString();
if (str.startsWith("\"") && str.endsWith("\"")) {
str = str.substring(1);
str = str.substring(0, str.length() - 1);
res.setLocaleProperty(localeName, locale, currentName, str);
return;
}
str = str.replace("\\'", "'");
res.setLocaleProperty(localeName, locale, currentName, str);
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
chars.append(ch, start, length);
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
}
@Override
public void processingInstruction(String target, String data) throws SAXException {
}
@Override
public void skippedEntity(String name) throws SAXException {
}
});
xmlReader.parse(new InputSource(new InputStreamReader(f, "UTF-8")));
} else {
if (files[0].getName().toLowerCase().endsWith("csv")) {
CSVParserOptions po = new CSVParserOptions(this);
if (po.isCanceled()) {
f.close();
return;
}
CSVParser p = new CSVParser(po.getDelimiter());
String[][] data = p.parse(new InputStreamReader(f, po.getEncoding()));
for (int iter = 1; iter < data.length; iter++) {
if (data[iter].length > 0) {
String key = data[iter][0];
for (int col = 1; col < data[iter].length; col++) {
if (res.getL10N(localeName, data[0][col]) == null) {
res.addLocale(localeName, data[0][col]);
}
res.setLocaleProperty(localeName, data[0][col], key, data[iter][col]);
}
}
}
} else {
Properties prop = new Properties();
prop.load(f);
for (Object key : prop.keySet()) {
res.setLocaleProperty(localeName, locale, (String) key, prop.getProperty((String) key));
}
}
}
f.close();
initLocaleList();
for (Object localeObj : localeList) {
Hashtable current = res.getL10N(localeName, (String) localeObj);
for (Object key : current.keySet()) {
if (!keys.contains(key)) {
keys.add(key);
}
}
}
Collections.sort(keys);
initTable();
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error: " + ex, "Error Occured", JOptionPane.ERROR_MESSAGE);
}
}
}
}
use of org.xml.sax.ErrorHandler in project teiid by teiid.
the class TestTeiidConfiguration method validate.
private void validate(String marshalled) throws SAXException, IOException {
URL xsdURL = Thread.currentThread().getContextClassLoader().getResource("schema/jboss-teiid.xsd");
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema schema = factory.newSchema(xsdURL);
Validator validator = schema.newValidator();
Source source = new StreamSource(new ByteArrayInputStream(marshalled.getBytes()));
validator.setErrorHandler(new ErrorHandler() {
@Override
public void warning(SAXParseException exception) throws SAXException {
fail(exception.getMessage());
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
fail(exception.getMessage());
}
@Override
public void error(SAXParseException exception) throws SAXException {
if (!exception.getMessage().contains("cvc-enumeration-valid") && !exception.getMessage().contains("cvc-type")) {
fail(exception.getMessage());
}
}
});
validator.validate(source);
}
use of org.xml.sax.ErrorHandler in project BibleMultiConverter by schierlm.
the class ValidateXML method validateFile.
private static void validateFile(Schema schema, File file, final String errorHeader, String okMessage, String errorFooter) throws IOException {
Validator validator = schema.newValidator();
final int[] errorCountHolder = new int[1];
validator.setErrorHandler(new ErrorHandler() {
private void printHeader() {
if (errorCountHolder[0] == 0 && errorHeader != null) {
System.out.println(errorHeader);
}
errorCountHolder[0]++;
}
@Override
public void warning(SAXParseException exception) throws SAXException {
printHeader();
System.out.println("\t[Warning] " + exception.toString());
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
printHeader();
System.out.println("\t[Fatal Error] " + exception.toString());
}
@Override
public void error(SAXParseException exception) throws SAXException {
printHeader();
System.out.println("\t[Error] " + exception.toString());
}
});
try {
validator.validate(new StreamSource(file));
} catch (SAXException ex) {
// already handled by ValidationHandler
}
String resultMessage = (errorCountHolder[0] > 0) ? errorFooter : okMessage;
if (resultMessage != null)
System.out.println(resultMessage);
}
use of org.xml.sax.ErrorHandler in project hale by halestudio.
the class Validate method validate.
/**
* @see Validator#validate(InputStream)
*/
public void validate(InputStream xml) {
javax.xml.validation.Schema validateSchema;
try {
URI mainUri = null;
Source[] sources = new Source[schemaLocations.length];
for (int i = 0; i < this.schemaLocations.length; i++) {
URI schemaLocation = this.schemaLocations[i];
if (mainUri == null) {
// use first schema location for main URI
mainUri = schemaLocation;
}
// load a WXS schema, represented by a Schema instance
sources[i] = new StreamSource(schemaLocation.toURL().openStream());
}
// create a SchemaFactory capable of understanding WXS schemas
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
factory.setResourceResolver(new SchemaResolver(mainUri));
validateSchema = factory.newSchema(sources);
} catch (Exception e) {
// $NON-NLS-1$
throw new IllegalStateException("Error parsing schema for XML validation", e);
}
final AtomicInteger warnings = new AtomicInteger(0);
final AtomicInteger errors = new AtomicInteger(0);
// create a Validator instance, which can be used to validate an
// instance document
javax.xml.validation.Validator validator = validateSchema.newValidator();
validator.setErrorHandler(new ErrorHandler() {
@Override
public void warning(SAXParseException exception) throws SAXException {
System.out.println(MessageFormat.format(MESSAGE_PATTERN, exception.getLocalizedMessage(), exception.getLineNumber(), exception.getColumnNumber()));
warnings.incrementAndGet();
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
System.err.println(MessageFormat.format(MESSAGE_PATTERN, exception.getLocalizedMessage(), exception.getLineNumber(), exception.getColumnNumber()));
errors.incrementAndGet();
}
@Override
public void error(SAXParseException exception) throws SAXException {
System.err.println(MessageFormat.format(MESSAGE_PATTERN, exception.getLocalizedMessage(), exception.getLineNumber(), exception.getColumnNumber()));
errors.incrementAndGet();
}
});
// validate the XML document
try {
validator.validate(new StreamSource(xml));
} catch (Exception e) {
// $NON-NLS-1$
throw new IllegalStateException("Error validating XML file", e);
}
System.out.println("Validation completed.");
System.out.println(warnings.get() + " warnings");
System.out.println(errors.get() + " errors");
}
Aggregations