Search in sources :

Example 81 with DefaultHandler

use of org.xml.sax.helpers.DefaultHandler in project j2objc by google.

the class PropertiesXmlLoader method load.

public void load(final Properties p, InputStream in) throws IOException, InvalidPropertiesFormatException {
    if (in == null) {
        throw new NullPointerException("in == null");
    }
    try {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(new DefaultHandler() {

            private String key;

            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                key = null;
                if (qName.equals("entry")) {
                    key = attributes.getValue("key");
                }
            }

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if (key != null) {
                    String value = new String(ch, start, length);
                    p.put(key, value);
                    key = null;
                }
            }
        });
        reader.parse(new InputSource(in));
    } catch (SAXException e) {
        throw new InvalidPropertiesFormatException(e);
    }
}
Also used : InputSource(org.xml.sax.InputSource) Attributes(org.xml.sax.Attributes) XMLReader(org.xml.sax.XMLReader) DefaultHandler(org.xml.sax.helpers.DefaultHandler) SAXException(org.xml.sax.SAXException)

Example 82 with DefaultHandler

use of org.xml.sax.helpers.DefaultHandler in project atlas by alibaba.

the class BakSmali method disassembleDexFile.

public static boolean disassembleDexFile(DexFile dexFile, final baksmaliOptions options) {
    if (options.registerInfo != 0 || options.deodex) {
        try {
            Iterable<String> extraClassPathEntries;
            if (options.extraClassPathEntries != null) {
                extraClassPathEntries = options.extraClassPathEntries;
            } else {
                extraClassPathEntries = ImmutableList.of();
            }
            options.classPath = ClassPath.fromClassPath(options.bootClassPathDirs, Iterables.concat(options.bootClassPathEntries, extraClassPathEntries), dexFile, options.apiLevel, options.checkPackagePrivateAccess, options.experimental);
            if (options.customInlineDefinitions != null) {
                options.inlineResolver = new CustomInlineMethodResolver(options.classPath, options.customInlineDefinitions);
            }
        } catch (Exception ex) {
            System.err.println("\n\nError occurred while loading boot class path files. Aborting.");
            ex.printStackTrace(System.err);
            return false;
        }
    }
    if (options.resourceIdFileEntries != null) {
        class PublicHandler extends DefaultHandler {

            String prefix = null;

            public PublicHandler(String prefix) {
                super();
                this.prefix = prefix;
            }

            public void startElement(String uri, String localName, String qName, Attributes attr) throws SAXException {
                if (qName.equals("public")) {
                    String type = attr.getValue("type");
                    String name = attr.getValue("name").replace('.', '_');
                    Integer public_key = Integer.decode(attr.getValue("id"));
                    String public_val = new StringBuffer().append(prefix).append(".").append(type).append(".").append(name).toString();
                    options.resourceIds.put(public_key, public_val);
                }
            }
        }
        ;
        for (Map.Entry<String, String> entry : options.resourceIdFileEntries.entrySet()) {
            try {
                SAXParser saxp = SAXParserFactory.newInstance().newSAXParser();
                String prefix = entry.getValue();
                saxp.parse(entry.getKey(), new PublicHandler(prefix));
            } catch (ParserConfigurationException e) {
                continue;
            } catch (SAXException e) {
                continue;
            } catch (IOException e) {
                continue;
            }
        }
    }
    File outputDirectoryFile = new File(options.outputDirectory);
    if (!outputDirectoryFile.exists()) {
        if (!outputDirectoryFile.mkdirs()) {
            System.err.println("Can't create the output directory " + options.outputDirectory);
            return false;
        }
    }
    //sort the classes, so that if we're on a case-insensitive file system and need to handle classes with file
    //name collisions, then we'll use the same name for each class, if the dex file goes through multiple
    //baksmali/smali cycles for some reason. If a class with a colliding name is added or removed, the filenames
    //may still change of course
    List<? extends ClassDef> classDefs = Ordering.natural().sortedCopy(dexFile.getClasses());
    if (!options.noAccessorComments) {
        options.syntheticAccessorResolver = new SyntheticAccessorResolver(classDefs);
    }
    final ClassFileNameHandler fileNameHandler = new ClassFileNameHandler(outputDirectoryFile, ".smali");
    ExecutorService executor = Executors.newFixedThreadPool(options.jobs);
    List<Future<Boolean>> tasks = Lists.newArrayList();
    for (final ClassDef classDef : classDefs) {
        tasks.add(executor.submit(new Callable<Boolean>() {

            @Override
            public Boolean call() throws Exception {
                return disassembleClass(classDef, fileNameHandler, options);
            }
        }));
    }
    boolean errorOccurred = false;
    try {
        for (Future<Boolean> task : tasks) {
            while (true) {
                try {
                    if (!task.get()) {
                        errorOccurred = true;
                    }
                } catch (InterruptedException ex) {
                    continue;
                } catch (ExecutionException ex) {
                    throw new RuntimeException(ex);
                }
                break;
            }
        }
    } finally {
        executor.shutdown();
    }
    return !errorOccurred;
}
Also used : CustomInlineMethodResolver(org.jf.dexlib2.analysis.CustomInlineMethodResolver) ClassFileNameHandler(org.jf.util.ClassFileNameHandler) Attributes(org.xml.sax.Attributes) SAXException(org.xml.sax.SAXException) SyntheticAccessorResolver(org.jf.dexlib2.util.SyntheticAccessorResolver) ClassDef(org.jf.dexlib2.iface.ClassDef) SAXParser(javax.xml.parsers.SAXParser) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) DefaultHandler(org.xml.sax.helpers.DefaultHandler) Map(java.util.Map) DexFile(org.jf.dexlib2.iface.DexFile)

Example 83 with DefaultHandler

use of org.xml.sax.helpers.DefaultHandler in project atlas by alibaba.

the class SmaliUtils method disassembleDexFile.

/**
     * 将dex文件转换为smali文件
     * @param dex
     * @param outputDir
     * @param includeClasses 需要做过滤的文件
     */
public static boolean disassembleDexFile(File dex, File outputDir, final Set<String> includeClasses) throws IOException {
    final baksmaliOptions options = createBaksmaliOptions();
    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }
    DexFile dexFile = DexFileFactory.loadDexFile(dex, DEFAULT_API_LEVEL, true);
    options.outputDirectory = outputDir.getAbsolutePath();
    //1. 设置线程数
    options.jobs = 3;
    if (options.registerInfo != 0 || options.deodex) {
        try {
            Iterable<String> extraClassPathEntries;
            if (options.extraClassPathEntries != null) {
                extraClassPathEntries = options.extraClassPathEntries;
            } else {
                extraClassPathEntries = ImmutableList.of();
            }
            options.classPath = ClassPath.fromClassPath(options.bootClassPathDirs, Iterables.concat(options.bootClassPathEntries, extraClassPathEntries), dexFile, options.apiLevel, options.checkPackagePrivateAccess, options.experimental);
            if (options.customInlineDefinitions != null) {
                options.inlineResolver = new CustomInlineMethodResolver(options.classPath, options.customInlineDefinitions);
            }
        } catch (Exception ex) {
            System.err.println("\n\nError occurred while loading boot class path files. Aborting.");
            ex.printStackTrace(System.err);
            return false;
        }
    }
    if (options.resourceIdFileEntries != null) {
        class PublicHandler extends DefaultHandler {

            String prefix = null;

            public PublicHandler(String prefix) {
                super();
                this.prefix = prefix;
            }

            public void startElement(String uri, String localName, String qName, Attributes attr) throws SAXException {
                if (qName.equals("public")) {
                    String type = attr.getValue("type");
                    String name = attr.getValue("name").replace('.', '_');
                    Integer public_key = Integer.decode(attr.getValue("id"));
                    String public_val = new StringBuffer().append(prefix).append(".").append(type).append(".").append(name).toString();
                    options.resourceIds.put(public_key, public_val);
                }
            }
        }
        ;
        for (Map.Entry<String, String> entry : options.resourceIdFileEntries.entrySet()) {
            try {
                SAXParser saxp = SAXParserFactory.newInstance().newSAXParser();
                String prefix = entry.getValue();
                saxp.parse(entry.getKey(), new PublicHandler(prefix));
            } catch (ParserConfigurationException e) {
                continue;
            } catch (SAXException e) {
                continue;
            } catch (IOException e) {
                continue;
            }
        }
    }
    File outputDirectoryFile = new File(options.outputDirectory);
    if (!outputDirectoryFile.exists()) {
        if (!outputDirectoryFile.mkdirs()) {
            System.err.println("Can't create the output directory " + options.outputDirectory);
            return false;
        }
    }
    // sort the classes, so that if we're on a case-insensitive file system and need to handle classes with file
    // name collisions, then we'll use the same name for each class, if the dex file goes through multiple
    // baksmali/smali cycles for some reason. If a class with a colliding name is added or removed, the filenames
    // may still change of course
    List<? extends ClassDef> classDefs = Ordering.natural().sortedCopy(dexFile.getClasses());
    if (!options.noAccessorComments) {
        options.syntheticAccessorResolver = new SyntheticAccessorResolver(classDefs);
    }
    final ClassFileNameHandler fileNameHandler = new ClassFileNameHandler(outputDirectoryFile, ".smali");
    ExecutorService executor = Executors.newFixedThreadPool(options.jobs);
    List<Future<Boolean>> tasks = Lists.newArrayList();
    for (final ClassDef classDef : classDefs) {
        tasks.add(executor.submit(new Callable<Boolean>() {

            @Override
            public Boolean call() throws Exception {
                String className = getDalvikClassName(classDef.getType());
                if (null != includeClasses) {
                    if (includeClasses.contains(className)) {
                        BakSmali.disassembleClass(classDef, fileNameHandler, options);
                    }
                    return true;
                } else {
                    return BakSmali.disassembleClass(classDef, fileNameHandler, options);
                }
            }
        }));
    }
    boolean errorOccurred = false;
    try {
        for (Future<Boolean> task : tasks) {
            while (true) {
                try {
                    if (!task.get()) {
                        errorOccurred = true;
                    }
                } catch (InterruptedException ex) {
                    continue;
                } catch (ExecutionException ex) {
                    throw new RuntimeException(ex);
                }
                break;
            }
        }
    } finally {
        executor.shutdown();
    }
    return !errorOccurred;
}
Also used : org.jf.baksmali.baksmaliOptions(org.jf.baksmali.baksmaliOptions) CustomInlineMethodResolver(org.jf.dexlib2.analysis.CustomInlineMethodResolver) ClassFileNameHandler(org.jf.util.ClassFileNameHandler) Attributes(org.xml.sax.Attributes) SAXException(org.xml.sax.SAXException) SyntheticAccessorResolver(org.jf.dexlib2.util.SyntheticAccessorResolver) ClassDef(org.jf.dexlib2.iface.ClassDef) SAXParser(javax.xml.parsers.SAXParser) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) IOException(java.io.IOException) DexFile(org.jf.dexlib2.iface.DexFile) RecognitionException(org.antlr.runtime.RecognitionException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) DefaultHandler(org.xml.sax.helpers.DefaultHandler) Map(java.util.Map) File(java.io.File) DexFile(org.jf.dexlib2.iface.DexFile)

Example 84 with DefaultHandler

use of org.xml.sax.helpers.DefaultHandler in project spring-framework by spring-projects.

the class SourceHttpMessageConverterTests method readSAXSourceExternal.

@Test
public void readSAXSourceExternal() throws Exception {
    MockHttpInputMessage inputMessage = new MockHttpInputMessage(bodyExternal.getBytes("UTF-8"));
    inputMessage.getHeaders().setContentType(new MediaType("application", "xml"));
    converter.setSupportDtd(true);
    SAXSource result = (SAXSource) converter.read(SAXSource.class, inputMessage);
    InputSource inputSource = result.getInputSource();
    XMLReader reader = result.getXMLReader();
    reader.setContentHandler(new DefaultHandler() {

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            String s = new String(ch, start, length);
            assertNotEquals("Invalid result", "Foo Bar", s);
        }
    });
    reader.parse(inputSource);
}
Also used : MockHttpInputMessage(org.springframework.http.MockHttpInputMessage) InputSource(org.xml.sax.InputSource) SAXSource(javax.xml.transform.sax.SAXSource) MediaType(org.springframework.http.MediaType) XMLReader(org.xml.sax.XMLReader) DefaultHandler(org.xml.sax.helpers.DefaultHandler) SAXException(org.xml.sax.SAXException) Test(org.junit.Test)

Example 85 with DefaultHandler

use of org.xml.sax.helpers.DefaultHandler in project android_frameworks_base by ParanoidAndroid.

the class ExpatPerformanceTest method runSax.

private void runSax() throws IOException, SAXException {
    long start = System.currentTimeMillis();
    Xml.parse(newInputStream(), Xml.Encoding.UTF_8, new DefaultHandler());
    long elapsed = System.currentTimeMillis() - start;
    Log.i(TAG, "expat SAX: " + elapsed + "ms");
}
Also used : DefaultHandler(org.xml.sax.helpers.DefaultHandler)

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