Search in sources :

Example 86 with DefaultHandler

use of org.xml.sax.helpers.DefaultHandler in project hadoop by apache.

the class TestOfflineImageViewerForAcl method testPBImageXmlWriterForAcl.

@Test
public void testPBImageXmlWriterForAcl() throws Exception {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PrintStream o = new PrintStream(output);
    PBImageXmlWriter v = new PBImageXmlWriter(new Configuration(), o);
    v.visit(new RandomAccessFile(originalFsimage, "r"));
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser parser = spf.newSAXParser();
    final String xml = output.toString();
    parser.parse(new InputSource(new StringReader(xml)), new DefaultHandler());
}
Also used : PrintStream(java.io.PrintStream) InputSource(org.xml.sax.InputSource) Configuration(org.apache.hadoop.conf.Configuration) RandomAccessFile(java.io.RandomAccessFile) StringReader(java.io.StringReader) SAXParser(javax.xml.parsers.SAXParser) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SAXParserFactory(javax.xml.parsers.SAXParserFactory) DefaultHandler(org.xml.sax.helpers.DefaultHandler) Test(org.junit.Test)

Example 87 with DefaultHandler

use of org.xml.sax.helpers.DefaultHandler in project robovm by robovm.

the class ExpatSaxParserTest method testExternalEntityDownload.

public void testExternalEntityDownload() throws IOException, SAXException {
    final MockWebServer server = new MockWebServer();
    try {
        // RoboVM note: Modified to call server.shutdown() after test finishes.
        server.enqueue(new MockResponse().setBody("<bar></bar>"));
        server.play();
        class Handler extends DefaultHandler {

            final List<String> elementNames = new ArrayList<String>();

            @Override
            public InputSource resolveEntity(String publicId, String systemId) throws IOException {
                // The parser should have resolved the systemId.
                assertEquals(server.getUrl("/systemBar").toString(), systemId);
                return new InputSource(systemId);
            }

            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes) {
                elementNames.add(localName);
            }

            @Override
            public void endElement(String uri, String localName, String qName) {
                elementNames.add("/" + localName);
            }
        }
        // 'systemBar', the external entity, is relative to 'systemFoo':
        Reader in = new StringReader("<?xml version=\"1.0\"?>\n" + "<!DOCTYPE foo [\n" + "  <!ENTITY bar SYSTEM 'systemBar'>\n" + "]>\n" + "<foo>&bar;</foo>");
        ExpatReader reader = new ExpatReader();
        Handler handler = new Handler();
        reader.setContentHandler(handler);
        reader.setEntityResolver(handler);
        InputSource source = new InputSource(in);
        source.setSystemId(server.getUrl("/systemFoo").toString());
        reader.parse(source);
        assertEquals(Arrays.asList("foo", "bar", "/bar", "/foo"), handler.elementNames);
    } finally {
        server.shutdown();
    }
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) InputSource(org.xml.sax.InputSource) ExpatReader(org.apache.harmony.xml.ExpatReader) MockWebServer(com.google.mockwebserver.MockWebServer) Attributes(org.xml.sax.Attributes) StringReader(java.io.StringReader) ExpatReader(org.apache.harmony.xml.ExpatReader) Reader(java.io.Reader) XMLReader(org.xml.sax.XMLReader) StringReader(java.io.StringReader) DefaultHandler(org.xml.sax.helpers.DefaultHandler) ContentHandler(org.xml.sax.ContentHandler) ArrayList(java.util.ArrayList) List(java.util.List) DefaultHandler(org.xml.sax.helpers.DefaultHandler)

Example 88 with DefaultHandler

use of org.xml.sax.helpers.DefaultHandler in project robovm by robovm.

the class ExpatSaxParserTest method testExternalEntity.

public void testExternalEntity() throws IOException, SAXException {
    class Handler extends DefaultHandler {

        List<String> elementNames = new ArrayList<String>();

        StringBuilder text = new StringBuilder();

        public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException {
            if (publicId.equals("publicA") && systemId.equals("systemA")) {
                return new InputSource(new StringReader("<a/>"));
            } else if (publicId.equals("publicB") && systemId.equals("systemB")) {
                /*
                     * Explicitly set the encoding here or else the parser will
                     * try to use the parent parser's encoding which is utf-16.
                     */
                InputSource inputSource = new InputSource(new ByteArrayInputStream("bob".getBytes("utf-8")));
                inputSource.setEncoding("utf-8");
                return inputSource;
            }
            throw new AssertionError();
        }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            elementNames.add(localName);
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            elementNames.add("/" + localName);
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            text.append(ch, start, length);
        }
    }
    Reader in = new StringReader("<?xml version=\"1.0\"?>\n" + "<!DOCTYPE foo [\n" + "  <!ENTITY a PUBLIC 'publicA' 'systemA'>\n" + "  <!ENTITY b PUBLIC 'publicB' 'systemB'>\n" + "]>\n" + "<foo>\n" + "  &a;<b>&b;</b></foo>");
    ExpatReader reader = new ExpatReader();
    Handler handler = new Handler();
    reader.setContentHandler(handler);
    reader.setEntityResolver(handler);
    reader.parse(new InputSource(in));
    assertEquals(Arrays.asList("foo", "a", "/a", "b", "/b", "/foo"), handler.elementNames);
    assertEquals("bob", handler.text.toString().trim());
}
Also used : InputSource(org.xml.sax.InputSource) ExpatReader(org.apache.harmony.xml.ExpatReader) Attributes(org.xml.sax.Attributes) ExpatReader(org.apache.harmony.xml.ExpatReader) Reader(java.io.Reader) XMLReader(org.xml.sax.XMLReader) StringReader(java.io.StringReader) DefaultHandler(org.xml.sax.helpers.DefaultHandler) ContentHandler(org.xml.sax.ContentHandler) DefaultHandler(org.xml.sax.helpers.DefaultHandler) ByteArrayInputStream(java.io.ByteArrayInputStream) StringReader(java.io.StringReader) ArrayList(java.util.ArrayList) List(java.util.List)

Example 89 with DefaultHandler

use of org.xml.sax.helpers.DefaultHandler in project android by JetBrains.

the class RecipeUtils method parseManifestForPermissions.

private static void parseManifestForPermissions(@NotNull File f, @NotNull RecipeMetadata metadata) {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(f, new DefaultHandler() {

            @Override
            public void startElement(String uri, String localName, String tagName, Attributes attributes) throws SAXException {
                if (tagName.equals(SdkConstants.TAG_USES_PERMISSION) || tagName.equals(SdkConstants.TAG_USES_PERMISSION_SDK_23) || tagName.equals(SdkConstants.TAG_USES_PERMISSION_SDK_M)) {
                    String permission = attributes.getValue(SdkConstants.ANDROID_NS_NAME_PREFIX + SdkConstants.ATTR_NAME);
                    // Most permissions are "android.permission.XXX", so for readability, just remove the prefix if present
                    permission = permission.replace(SdkConstants.ANDROID_PKG_PREFIX + SdkConstants.ATTR_PERMISSION + ".", "");
                    metadata.addPermission(permission);
                }
            }
        });
    } catch (Exception e) {
        // This method shouldn't crash the user for any reason, as showing permissions is just
        // informational, but log a warning so developers can see if they make a mistake when
        // creating their service.
        getLog().warn("Failed to read permissions from AndroidManifest.xml", e);
    }
}
Also used : Attributes(org.xml.sax.Attributes) SAXParser(javax.xml.parsers.SAXParser) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) SAXParserFactory(javax.xml.parsers.SAXParserFactory) DefaultHandler(org.xml.sax.helpers.DefaultHandler) SAXException(org.xml.sax.SAXException)

Example 90 with DefaultHandler

use of org.xml.sax.helpers.DefaultHandler in project android by JetBrains.

the class RepositoryUrlManager method getLatestVersionFromMavenMetadata.

/**
   * Parses a Maven metadata file and returns a string of the highest found version
   *
   * @param metadataFile    the files to parse
   * @param includePreviews if false, preview versions of the library will not be returned
   * @return the string representing the highest version found in the file or "0.0.0" if no versions exist in the file
   */
@Nullable
private static String getLatestVersionFromMavenMetadata(@NotNull File metadataFile, @Nullable String filterPrefix, boolean includePreviews, @NotNull FileOp fileOp) throws IOException {
    String xml = fileOp.toString(metadataFile, StandardCharsets.UTF_8);
    List<GradleCoordinate> versions = Lists.newLinkedList();
    try {
        SAXParserFactory.newInstance().newSAXParser().parse(IOUtils.toInputStream(xml), new DefaultHandler() {

            boolean inVersionTag = false;

            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                if (qName.equals(TAG_VERSION)) {
                    inVersionTag = true;
                }
            }

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                // Get the version and compare it to the current known max version
                if (inVersionTag) {
                    inVersionTag = false;
                    String revision = new String(ch, start, length);
                    //noinspection StatementWithEmptyBody
                    if (!includePreviews && "5.2.08".equals(revision) && metadataFile.getPath().contains(PLAY_SERVICES.getArtifactId())) {
                    // This version (despite not having -rcN in its version name is actually a preview
                    // (See https://code.google.com/p/android/issues/detail?id=75292)
                    // Ignore it
                    } else if (filterPrefix == null || revision.startsWith(filterPrefix)) {
                        versions.add(GradleCoordinate.parseVersionOnly(revision));
                    }
                }
            }
        });
    } catch (Exception e) {
        LOG.warn(e);
    }
    if (versions.isEmpty()) {
        return REVISION_ANY;
    } else if (includePreviews) {
        return GRADLE_COORDINATE_ORDERING.max(versions).getRevision();
    } else {
        return versions.stream().filter(v -> !v.isPreview()).max(GRADLE_COORDINATE_ORDERING).map(GradleCoordinate::getRevision).orElse(null);
    }
}
Also used : GradleCoordinate(com.android.ide.common.repository.GradleCoordinate) Attributes(org.xml.sax.Attributes) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) DefaultHandler(org.xml.sax.helpers.DefaultHandler) SAXException(org.xml.sax.SAXException) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

DefaultHandler (org.xml.sax.helpers.DefaultHandler)148 InputStream (java.io.InputStream)65 Metadata (org.apache.tika.metadata.Metadata)59 ParseContext (org.apache.tika.parser.ParseContext)52 Test (org.junit.Test)44 Attributes (org.xml.sax.Attributes)41 SAXParser (javax.xml.parsers.SAXParser)40 SAXException (org.xml.sax.SAXException)39 ByteArrayInputStream (java.io.ByteArrayInputStream)32 SAXParserFactory (javax.xml.parsers.SAXParserFactory)29 IOException (java.io.IOException)26 InputSource (org.xml.sax.InputSource)23 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)22 Parser (org.apache.tika.parser.Parser)22 TikaInputStream (org.apache.tika.io.TikaInputStream)20 ContentHandler (org.xml.sax.ContentHandler)20 File (java.io.File)19 AutoDetectParser (org.apache.tika.parser.AutoDetectParser)17 BodyContentHandler (org.apache.tika.sax.BodyContentHandler)16 FileInputStream (java.io.FileInputStream)15