use of org.xml.sax.Attributes in project logging-log4j2 by apache.
the class XmlSchemaTest method testXmlSchemaValidation.
@Test
public void testXmlSchemaValidation() throws SAXException, IOException {
final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final Schema schema = factory.newSchema(new StreamSource(new File("src/main/resources/Log4j-config.xsd")));
final Validator validator = schema.newValidator();
final XMLFilterImpl namespaceAdder = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) {
@Override
public void startElement(final String namespace, final String localName, final String qName, final Attributes atts) throws SAXException {
super.startElement(TARGET_NAMESPACE, localName, qName, atts);
}
};
final MutableInt configs = new MutableInt();
final MutableInt failures = new MutableInt();
try (final Stream<Path> testResources = Files.list(Paths.get("src", "test", "resources"))) {
testResources.filter(filePath -> {
final String fileName = filePath.getFileName().toString();
if (!fileName.endsWith(".xml"))
return false;
for (final String ignore : IGNORE_CONFIGS) {
if (fileName.contains(ignore))
return false;
}
return true;
}).forEach(filePath -> {
System.out.println("Validating " + configs.incrementAndGet() + ". [" + filePath + "]...");
System.out.flush();
try {
final String xml = fixXml(FileUtils.readFileToString(filePath.toFile(), Charset.defaultCharset()));
validator.validate(new SAXSource(namespaceAdder, new InputSource(new ByteArrayInputStream(xml.getBytes()))), null);
} catch (final Exception ex) {
System.err.println(ex);
System.err.flush();
failures.increment();
}
});
}
assertEquals(0, failures.intValue());
}
use of org.xml.sax.Attributes in project BookReader by JustWayward.
the class Utils method domparse.
public static ArrayList<String> domparse(String filePath, String extractPath, String md5) throws IOException {
final ArrayList<String> listSite = new ArrayList<>();
listSite.add(md5);
// /////////////////////////////////////////////////
try {
final FileOutputStream fosHTMLMap = new FileOutputStream(extractPath + "/" + md5);
final FileOutputStream fosListSite = new FileOutputStream(extractPath + "/site_map_" + md5);
try {
fosListSite.write((md5 + ";").getBytes());
} catch (IOException e) {
e.printStackTrace();
}
if (chm.getResourceAsStream("") != null) {
SAXParserImpl.newInstance(null).parse(chm.getResourceAsStream(""), new DefaultHandler() {
class MyUrl {
public int status = 0;
public String name;
public String local;
public String toString() {
if (status == 1)
return "<a href=\"#\">" + name + "</a>";
else
return "<a href=\"" + local + "\">" + name + "</a>";
}
}
MyUrl url = new MyUrl();
HashMap<String, String> myMap = new HashMap<String, String>();
int count = 0;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equals("param")) {
count++;
for (int i = 0; i < attributes.getLength(); i++) {
myMap.put(attributes.getQName(i).toLowerCase(), attributes.getValue(i).toLowerCase());
}
if (myMap.get("name").equals("name") && myMap.get("value") != null) {
url.name = myMap.get("value");
url.status = 1;
} else if (myMap.get("name").equals("local") && myMap.get("value") != null) {
url.local = myMap.get("value");
url.status = 2;
listSite.add(url.local.replaceAll("%20", " "));
try {
fosListSite.write((url.local.replaceAll("%20", " ") + ";").getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
if (url.status == 2) {
url.status = 0;
try {
fosHTMLMap.write(url.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
if (url.status == 1) {
try {
fosHTMLMap.write(url.toString().getBytes());
url.status = 0;
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (!qName.equals("object") && !qName.equals("param"))
try {
fosHTMLMap.write(("<" + qName + ">").getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (!qName.equals("object") && !qName.equals("param"))
try {
fosHTMLMap.write(("</" + qName + ">").getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
});
} else {
fosHTMLMap.write("<HTML> <BODY> <UL>".getBytes());
for (String fileName : chm.list()) {
fileName = fileName.substring(1);
if (fileName.endsWith(".htm") || fileName.endsWith(".html")) {
fosListSite.write((fileName + ";").getBytes());
fosHTMLMap.write(("<li><a href=\"" + fileName + "\">" + fileName + "</a></li>").getBytes());
listSite.add(fileName);
}
}
fosHTMLMap.write("</UL> </BODY> </HTML>".getBytes());
}
fosHTMLMap.close();
fosListSite.close();
} catch (SAXException | IOException e) {
e.printStackTrace();
}
return listSite;
}
use of org.xml.sax.Attributes in project groovy-core by groovy.
the class AntBuilderLocator method createNode.
protected Object createNode(final Object name, final Map attributes) {
final Attributes attrs = buildAttributes(attributes);
String tagName = name.toString();
String ns = "";
if (name instanceof QName) {
QName q = (QName) name;
tagName = q.getLocalPart();
ns = q.getNamespaceURI();
}
// import can be used only as top level element
if ("import".equals(name)) {
antXmlContext.setCurrentTarget(implicitTarget);
} else if ("target".equals(name) && !insideTask) {
return onStartTarget(attrs, tagName, ns);
} else if ("defineTarget".equals(name) && !insideTask) {
return onDefineTarget(attrs, "target", ns);
}
try {
antElementHandler.onStartElement(ns, tagName, tagName, attrs, antXmlContext);
} catch (final SAXParseException e) {
log.log(Level.SEVERE, "Caught: " + e, e);
}
insideTask = true;
final RuntimeConfigurable wrapper = antXmlContext.getWrapperStack().lastElement();
return wrapper.getProxy();
}
use of org.xml.sax.Attributes in project dbeaver by serge-rider.
the class MavenArtifact method parseMetadata.
private void parseMetadata(InputStream mdStream) throws IOException, XMLException {
SAXReader reader = new SAXReader(mdStream);
reader.parse(new SAXListener() {
public String lastTag;
@Override
public void saxStartElement(SAXReader reader, String namespaceURI, String localName, Attributes atts) throws XMLException {
lastTag = localName;
}
@Override
public void saxText(SAXReader reader, String data) throws XMLException {
if ("version".equals(lastTag)) {
versions.add(data);
} else if ("latest".equals(lastTag)) {
latestVersion = data;
} else if ("release".equals(lastTag)) {
releaseVersion = data;
} else if ("lastUpdate".equals(lastTag)) {
try {
lastUpdate = new Date(Long.parseLong(data));
} catch (NumberFormatException e) {
log.warn(e);
}
}
}
@Override
public void saxEndElement(SAXReader reader, String namespaceURI, String localName) throws XMLException {
lastTag = null;
}
});
}
use of org.xml.sax.Attributes in project newsrob by marianokamp.
the class GRAnsweredBadRequestException method getStreamIDsFromGR.
/**
* @param xt
* can be null
*/
protected long[] getStreamIDsFromGR(NewsRobHttpClient httpClient, final List<String> tags, String xt, int max) throws IOException, SAXException, ParserConfigurationException, GRTokenExpiredException, GRAnsweredBadRequestException {
if (max == 0)
return new long[0];
final String tagsLabel = String.valueOf(tags);
Timing t = new Timing("EntriesRetriever.getStreamIDsFromGR(" + tagsLabel + ") (-" + xt + ")", context);
int currentCapacity = getEntryManager().getArticleCount();
String url = getGoogleHost() + "/reader/api/0/stream/items/ids";
url += "?s=" + tags.remove(0);
for (String tag : tags) url += "&s=" + tag;
if (xt != null)
url += "&xt=" + xt;
url += "&n=" + max;
try {
HttpRequestBase req = createGRRequest(httpClient, url);
HttpResponse response = executeGRRequest(httpClient, req, true);
throwExceptionWhenNotStatusOK(response);
final List<Long> unreadIds = new ArrayList<Long>(currentCapacity * 80 / 100);
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser parser = saxParserFactory.newSAXParser();
DefaultHandler handler = new SimpleStringExtractorHandler() {
String currentName;
boolean validResponse;
@Override
public final void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
super.startElement(uri, localName, name, attributes);
currentName = attributes.getValue("name");
if (!validResponse && "/object".equals(getFullyQualifiedPathName()))
validResponse = true;
}
@Override
public final void receivedString(String localTagName, String fqn, String value) {
if ("number".equals(localTagName) && "id".equals(currentName))
unreadIds.add(Long.parseLong(value));
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
if (!validResponse)
throw new RuntimeException("Google Reader response was invalid. Proxy issue?");
}
};
InputStream is = NewsRobHttpClient.getUngzippedContent(response.getEntity(), context);
parser.parse(is, handler);
if (NewsRob.isDebuggingEnabled(context))
PL.log(TAG + ": GR returned number of articles(" + tagsLabel + ") (-" + xt + ")=" + unreadIds.size(), context);
long[] rv = new long[unreadIds.size()];
int idx = 0;
for (Long unreadId : unreadIds) rv[idx++] = unreadId;
return rv;
} finally {
t.stop();
}
}
Aggregations