Search in sources :

Example 96 with Attributes

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());
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) Path(java.nio.file.Path) Arrays(java.util.Arrays) MutableInt(org.apache.commons.lang3.mutable.MutableInt) StreamSource(javax.xml.transform.stream.StreamSource) StringUtils(org.apache.commons.lang3.StringUtils) Schema(javax.xml.validation.Schema) Matcher(java.util.regex.Matcher) ByteArrayInputStream(java.io.ByteArrayInputStream) Charset(java.nio.charset.Charset) Attributes(org.xml.sax.Attributes) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) XMLConstants(javax.xml.XMLConstants) Path(java.nio.file.Path) InputSource(org.xml.sax.InputSource) SchemaFactory(javax.xml.validation.SchemaFactory) Files(java.nio.file.Files) XMLFilterImpl(org.xml.sax.helpers.XMLFilterImpl) IOException(java.io.IOException) Validator(javax.xml.validation.Validator) FileUtils(org.apache.commons.io.FileUtils) File(java.io.File) Test(org.junit.jupiter.api.Test) XMLReaderFactory(org.xml.sax.helpers.XMLReaderFactory) List(java.util.List) SAXSource(javax.xml.transform.sax.SAXSource) Stream(java.util.stream.Stream) Paths(java.nio.file.Paths) SAXException(org.xml.sax.SAXException) Pattern(java.util.regex.Pattern) InputSource(org.xml.sax.InputSource) Schema(javax.xml.validation.Schema) StreamSource(javax.xml.transform.stream.StreamSource) Attributes(org.xml.sax.Attributes) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) SAXSource(javax.xml.transform.sax.SAXSource) ByteArrayInputStream(java.io.ByteArrayInputStream) XMLFilterImpl(org.xml.sax.helpers.XMLFilterImpl) MutableInt(org.apache.commons.lang3.mutable.MutableInt) File(java.io.File) Validator(javax.xml.validation.Validator) Test(org.junit.jupiter.api.Test)

Example 97 with Attributes

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;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Attributes(org.xml.sax.Attributes) IOException(java.io.IOException) DefaultHandler(org.xml.sax.helpers.DefaultHandler) SAXException(org.xml.sax.SAXException) FileOutputStream(java.io.FileOutputStream)

Example 98 with Attributes

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();
}
Also used : QName(groovy.xml.QName) SAXParseException(org.xml.sax.SAXParseException) Attributes(org.xml.sax.Attributes)

Example 99 with Attributes

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;
        }
    });
}
Also used : XMLException(org.jkiss.utils.xml.XMLException) SAXReader(org.jkiss.utils.xml.SAXReader) SAXListener(org.jkiss.utils.xml.SAXListener) Attributes(org.xml.sax.Attributes)

Example 100 with Attributes

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();
    }
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) SimpleStringExtractorHandler(com.newsrob.util.SimpleStringExtractorHandler) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Attributes(org.xml.sax.Attributes) HttpResponse(org.apache.http.HttpResponse) DefaultHandler(org.xml.sax.helpers.DefaultHandler) SAXParser(javax.xml.parsers.SAXParser) Timing(com.newsrob.util.Timing) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Aggregations

Attributes (org.xml.sax.Attributes)279 DefaultHandler (org.xml.sax.helpers.DefaultHandler)74 SAXException (org.xml.sax.SAXException)66 AttributesImpl (org.xml.sax.helpers.AttributesImpl)50 SAXParser (javax.xml.parsers.SAXParser)48 Test (org.junit.Test)46 POSaveFailedException (org.adempiere.pipo.exception.POSaveFailedException)37 InputSource (org.xml.sax.InputSource)33 SAXParserFactory (javax.xml.parsers.SAXParserFactory)30 IOException (java.io.IOException)29 File (java.io.File)22 ByteArrayInputStream (java.io.ByteArrayInputStream)19 InputStream (java.io.InputStream)17 ArrayList (java.util.ArrayList)17 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)17 Test (org.junit.jupiter.api.Test)17 XMLReader (org.xml.sax.XMLReader)17 ContentHandler (org.xml.sax.ContentHandler)15 StringReader (java.io.StringReader)12 Transformer (org.apache.sling.rewriter.Transformer)10