org.xml.sax.helpers.XMLReaderFactory Java Examples

The following examples show how to use org.xml.sax.helpers.XMLReaderFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XMLReaderFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void testLegacy() throws Exception {
    ClassLoader clBackup = Thread.currentThread().getContextClassLoader();
    try {
        URL[] classUrls = { LEGACY_DIR.toUri().toURL() };
        URLClassLoader loader = new URLClassLoader(classUrls, ClassLoader.getSystemClassLoader().getParent());

        // set TCCL and try locating the provider
        Thread.currentThread().setContextClassLoader(loader);
        XMLReader reader1 = XMLReaderFactory.createXMLReader();
        assertEquals(reader1.getClass().getName(), "xp3.XMLReaderImpl");

        // now point to a random URL
        Thread.currentThread().setContextClassLoader(
                new URLClassLoader(new URL[0], ClassLoader.getSystemClassLoader().getParent()));
        // ClassNotFoundException if also trying to load class of reader1, which
        // would be the case before 8152912
        XMLReader reader2 = XMLReaderFactory.createXMLReader();
        assertEquals(reader2.getClass().getName(), "com.sun.org.apache.xerces.internal.parsers.SAXParser");
    } finally {
        Thread.currentThread().setContextClassLoader(clBackup);
    }
}
 
Example #2
Source File: EntityCharacterEventOrder.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
    public static void main(String[] args) {
        TestRunner.run(JDK6770436Test.class);
    }
*/
    @Test
    public void entityCallbackOrderJava() throws SAXException, IOException {
        final String input = "<element> &amp; some more text</element>";

        final MockContentHandler handler = new MockContentHandler();
        final XMLReader xmlReader = XMLReaderFactory.createXMLReader();

        xmlReader.setContentHandler(handler);
        xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

        xmlReader.parse(new InputSource(new StringReader(input)));

        final List<String> events = handler.getEvents();
        printEvents(events);
        assertCallbackOrder(events); //regression from JDK5
    }
 
Example #3
Source File: Bug6925410Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test() throws DatatypeConfigurationException {
    try {
        int times = 100;
        long start = System.currentTimeMillis();
        for (int i = 0; i < times; i++) {
            XMLReaderFactory.createXMLReader();
        }
        long end = System.currentTimeMillis();
        double speed = ((end - start));
        System.out.println(speed + "ms");
    } catch (Throwable e) {
        e.printStackTrace();
        Assert.fail(e.toString());
    }

}
 
Example #4
Source File: HftpFileSystem.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private FileChecksum getFileChecksum(String f) throws IOException {
  final HttpURLConnection connection = openConnection(
      "/fileChecksum" + ServletUtil.encodePath(f),
      "ugi=" + getEncodedUgiParameter());
  try {
    final XMLReader xr = XMLReaderFactory.createXMLReader();
    xr.setContentHandler(this);
    xr.parse(new InputSource(connection.getInputStream()));
  } catch(SAXException e) {
    final Exception embedded = e.getException();
    if (embedded != null && embedded instanceof IOException) {
      throw (IOException)embedded;
    }
    throw new IOException("invalid xml directory content", e);
  } finally {
    connection.disconnect();
  }
  return filechecksum;
}
 
Example #5
Source File: Jaxb2RootElementHttpMessageConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected Source processSource(Source source) {
	if (source instanceof StreamSource) {
		StreamSource streamSource = (StreamSource) source;
		InputSource inputSource = new InputSource(streamSource.getInputStream());
		try {
			XMLReader xmlReader = XMLReaderFactory.createXMLReader();
			xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd());
			String featureName = "http://xml.org/sax/features/external-general-entities";
			xmlReader.setFeature(featureName, isProcessExternalEntities());
			if (!isProcessExternalEntities()) {
				xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER);
			}
			return new SAXSource(xmlReader, inputSource);
		}
		catch (SAXException ex) {
			logger.warn("Processing of external entities could not be disabled", ex);
			return source;
		}
	}
	else {
		return source;
	}
}
 
Example #6
Source File: BiliDanmukuParser.java    From letv with Apache License 2.0 6 votes vote down vote up
public Danmakus parse() {
    if (this.mDataSource != null) {
        AndroidFileSource source = this.mDataSource;
        try {
            XMLReader xmlReader = XMLReaderFactory.createXMLReader();
            XmlContentHandler contentHandler = new XmlContentHandler();
            xmlReader.setContentHandler(contentHandler);
            xmlReader.parse(new InputSource(source.data()));
            return contentHandler.getResult();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
    }
    return null;
}
 
Example #7
Source File: EXIficientCodec.java    From RISE-V2G with MIT License 6 votes vote down vote up
private synchronized OutputStream encode(InputStream jaxbXML, Grammars grammar) {
	EXIResult exiResult = null;
	
	try {
		exiFactory.setGrammars(grammar);
		encodeOS = new ByteArrayOutputStream();
		exiResult = new EXIResult(exiFactory);
		exiResult.setOutputStream(encodeOS);
		XMLReader xmlReader = XMLReaderFactory.createXMLReader();
		xmlReader.setContentHandler(exiResult.getHandler());

		// parse xml file
		xmlReader.parse(new InputSource(jaxbXML));
		
		encodeOS.close();
	} catch (SAXException | IOException | EXIException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while trying to encode", e);
	}  
	
	return encodeOS;
}
 
Example #8
Source File: HftpFileSystem.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private void fetchList(String path, boolean recur) throws IOException {
  try {
    XMLReader xr = XMLReaderFactory.createXMLReader();
    xr.setContentHandler(this);
    HttpURLConnection connection = openConnection(
        "/listPaths" + ServletUtil.encodePath(path),
        "ugi=" + getEncodedUgiParameter() + (recur ? "&recursive=yes" : ""));
    InputStream resp = connection.getInputStream();
    xr.parse(new InputSource(resp));
  } catch(SAXException e) {
    final Exception embedded = e.getException();
    if (embedded != null && embedded instanceof IOException) {
      throw (IOException)embedded;
    }
    throw new IOException("invalid xml directory content", e);
  }
}
 
Example #9
Source File: Jaxb2RootElementHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
protected Source processSource(Source source) {
	if (source instanceof StreamSource) {
		StreamSource streamSource = (StreamSource) source;
		InputSource inputSource = new InputSource(streamSource.getInputStream());
		try {
			XMLReader xmlReader = XMLReaderFactory.createXMLReader();
			xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd());
			String featureName = "http://xml.org/sax/features/external-general-entities";
			xmlReader.setFeature(featureName, isProcessExternalEntities());
			if (!isProcessExternalEntities()) {
				xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER);
			}
			return new SAXSource(xmlReader, inputSource);
		}
		catch (SAXException ex) {
			logger.warn("Processing of external entities could not be disabled", ex);
			return source;
		}
	}
	else {
		return source;
	}
}
 
Example #10
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * SAXTFactory.newTransformerhandler() method which takes SAXSource as
 * argument can be set to XMLReader. SAXSource has input XML file as its
 * input source. XMLReader has a transformer handler which write out the
 * result to output file. Test verifies output file is same as golden file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase01() throws Exception {
    String outputFile = USER_DIR + "saxtf001.out";
    String goldFile = GOLDEN_DIR + "saxtf001GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory) TransformerFactory.newInstance();
        TransformerHandler handler = saxTFactory.newTransformerHandler(new StreamSource(XSLT_FILE));
        Result result = new StreamResult(fos);
        handler.setResult(result);
        reader.setContentHandler(handler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #11
Source File: DomEngine.java    From DominionSim with MIT License 6 votes vote down vote up
public DomPlayer loadUserBotsFromXML(InputSource anXMLSource) {
	try {
		XMLHandler saxHandler = new XMLHandler();
		XMLReader rdr = XMLReaderFactory.createXMLReader();
		rdr.setContentHandler(saxHandler);
		rdr.parse(anXMLSource);
		ArrayList<DomPlayer> theNewPlayers = saxHandler.getBots();
		for (DomPlayer thePlayer : theNewPlayers) {
		  thePlayer.addType(DomBotType.UserCreated);
		  addUserBot(thePlayer);
		}
		return bots.get(0);
	} catch (Exception e) {
		e.printStackTrace();
		JOptionPane.showMessageDialog(myGui, "Bot creation failed! Make sure you have a valid XML in your clipboard", "", JOptionPane.ERROR_MESSAGE);
	}
	return null;
}
 
Example #12
Source File: Jaxb2Marshaller.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException {
	if (logger.isDebugEnabled()) {
		logger.debug("Setting validation schema to " +
				StringUtils.arrayToCommaDelimitedString(this.schemaResources));
	}
	Assert.notEmpty(resources, "No resources given");
	Assert.hasLength(schemaLanguage, "No schema language provided");
	Source[] schemaSources = new Source[resources.length];
	XMLReader xmlReader = XMLReaderFactory.createXMLReader();
	xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
	for (int i = 0; i < resources.length; i++) {
		Assert.notNull(resources[i], "Resource is null");
		Assert.isTrue(resources[i].exists(), "Resource " + resources[i] + " does not exist");
		InputSource inputSource = SaxResourceUtils.createInputSource(resources[i]);
		schemaSources[i] = new SAXSource(xmlReader, inputSource);
	}
	SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
	if (this.schemaResourceResolver != null) {
		schemaFactory.setResourceResolver(this.schemaResourceResolver);
	}
	return schemaFactory.newSchema(schemaSources);
}
 
Example #13
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Unit test for newTransformerhandler(Source). DcoumentBuilderFactory is
 * namespace awareness, DocumentBuilder parse xslt file as DOMSource.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase03() throws Exception {
    String outputFile = USER_DIR + "saxtf003.out";
    String goldFile = GOLDEN_DIR + "saxtf003GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        Document document = docBuilder.parse(new File(XSLT_FILE));
        Node node = (Node)document;
        DOMSource domSource= new DOMSource(node);

        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory)TransformerFactory.newInstance();
        TransformerHandler handler =
                    saxTFactory.newTransformerHandler(domSource);
        Result result = new StreamResult(fos);
        handler.setResult(result);
        reader.setContentHandler(handler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #14
Source File: AnalyzerTest.java    From vi with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnalyzePom(){

    try {
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        PomDependencyHandler handler = new PomDependencyHandler();
        xmlReader.setContentHandler(handler);
        xmlReader.parse(new InputSource(this.getClass().getClassLoader().getResourceAsStream("testpom.xml")));
        assertEquals(4, handler.getDependencies().size());
        PomInfo pom = handler.getPomInfo();
        boolean hasVI=false;
        for (PomDependency d : handler.getDependencies()) {
            assertNotNull(d.artifactId);
            assertNotNull(d.groupId);
            assertNotNull(d.version);
            if("framework-validateinternals".equals(d.artifactId)){
                hasVI=true;
                assertEquals(d.version,"0.9");
            }
        }
        assertTrue(hasVI);
    }catch (Exception e){
        e.printStackTrace();
    }

}
 
Example #15
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Unit test for TemplatesHandler setter/getter.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase13() throws Exception {
    String outputFile = USER_DIR + "saxtf013.out";
    String goldFile = GOLDEN_DIR + "saxtf013GF.out";
    try(FileInputStream fis = new FileInputStream(XML_FILE)) {
        // The transformer will use a SAX parser as it's reader.
        XMLReader reader = XMLReaderFactory.createXMLReader();

        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory) TransformerFactory.newInstance();
        TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
        // I have put this as it was complaining about systemid
        thandler.setSystemId("file:///" + USER_DIR);

        reader.setContentHandler(thandler);
        reader.parse(XSLT_FILE);
        XMLFilter filter
                = saxTFactory.newXMLFilter(thandler.getTemplates());
        filter.setParent(reader);

        filter.setContentHandler(new MyContentHandler(outputFile));
        filter.parse(new InputSource(fis));
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #16
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Unit test for contentHandler setter/getter.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase12() throws Exception {
    String outputFile = USER_DIR + "saxtf012.out";
    String goldFile = GOLDEN_DIR + "saxtf012GF.out";
    // The transformer will use a SAX parser as it's reader.
    XMLReader reader = XMLReaderFactory.createXMLReader();

    InputSource is = new InputSource(new FileInputStream(XSLT_FILE));
    SAXSource saxSource = new SAXSource();
    saxSource.setInputSource(is);

    SAXTransformerFactory saxTFactory = (SAXTransformerFactory)TransformerFactory.newInstance();
    XMLFilter filter = saxTFactory.newXMLFilter(saxSource);

    filter.setParent(reader);
    filter.setContentHandler(new MyContentHandler(outputFile));

    // Now, when you call transformer.parse, it will set itself as
    // the content handler for the parser object (it's "parent"), and
    // will then call the parse method on the parser.
    filter.parse(new InputSource(XML_FILE));
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #17
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Unit test for contentHandler setter/getter along reader as handler's
 * parent.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase10() throws Exception {
    String outputFile = USER_DIR + "saxtf010.out";
    String goldFile = GOLDEN_DIR + "saxtf010GF.out";
    // The transformer will use a SAX parser as it's reader.
    XMLReader reader = XMLReaderFactory.createXMLReader();
    SAXTransformerFactory saxTFactory
            = (SAXTransformerFactory)TransformerFactory.newInstance();
    XMLFilter filter =
        saxTFactory.newXMLFilter(new StreamSource(XSLT_FILE));
    filter.setParent(reader);
    filter.setContentHandler(new MyContentHandler(outputFile));

    // Now, when you call transformer.parse, it will set itself as
    // the content handler for the parser object (it's "parent"), and
    // will then call the parse method on the parser.
    filter.parse(new InputSource(XML_FILE));
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #18
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test newTransformerHandler with a Template Handler along with a relative
 * URI in the style-sheet file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase09() throws Exception {
    String outputFile = USER_DIR + "saxtf009.out";
    String goldFile = GOLDEN_DIR + "saxtf009GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory)TransformerFactory.newInstance();

        TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
        thandler.setSystemId("file:///" + XML_DIR);
        reader.setContentHandler(thandler);
        reader.parse(XSLT_INCL_FILE);
        TransformerHandler tfhandler=
            saxTFactory.newTransformerHandler(thandler.getTemplates());
        Result result = new StreamResult(fos);
        tfhandler.setResult(result);
        reader.setContentHandler(tfhandler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #19
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test newTransformerHandler with a Template Handler.
 *
 * @throws Exception If any errors occur.
 */
public void testcase08() throws Exception {
    String outputFile = USER_DIR + "saxtf008.out";
    String goldFile = GOLDEN_DIR + "saxtf008GF.out";

    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory)TransformerFactory.newInstance();

        TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
        reader.setContentHandler(thandler);
        reader.parse(XSLT_FILE);
        TransformerHandler tfhandler
                = saxTFactory.newTransformerHandler(thandler.getTemplates());

        Result result = new StreamResult(fos);
        tfhandler.setResult(result);

        reader.setContentHandler(tfhandler);
        reader.parse(XML_FILE);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example #20
Source File: BaseOFXReader.java    From ofx4j with Apache License 2.0 6 votes vote down vote up
/**
 * Parse an OFX version 2 stream from the first OFX element (defined by the {@link #getFirstElementStart() first element characters}).
 *
 * @param reader The reader.
 */
protected void parseV2FromFirstElement(Reader reader) throws IOException, OFXParseException {
  try {
    XMLReader xmlReader = XMLReaderFactory.createXMLReader();
    xmlReader.setFeature("http://xml.org/sax/features/namespaces", false);
    xmlReader.setContentHandler(new OFXV2ContentHandler(getContentHandler()));
    xmlReader.parse(new InputSource(reader));
  }
  catch (SAXException e) {
    if (e.getCause() instanceof OFXParseException) {
      throw (OFXParseException) e.getCause();
    }
    
    throw new OFXParseException(e);
  }
}
 
Example #21
Source File: ExclusionFiles.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
private static XMLReader createXmlReader()
    throws SAXException, IOException, VerifierConfigurationException {
  // Validate and parse XML files in one pass using Jing validator as a filter.
  // http://iso-relax.sourceforge.net/JARV/JARV.html#use_42
  VerifierFactory factory = VerifierFactory.newInstance("http://relaxng.org/ns/structure/1.0");
  InputStream linkageCheckerSchema =
      ExclusionFiles.class.getClassLoader().getResourceAsStream("linkage-checker-exclusion.rng");
  Schema schema = factory.compileSchema(linkageCheckerSchema);
  Verifier verifier = schema.newVerifier();

  // DraconianErrorHandler throws SAXException upon invalid structure
  verifier.setErrorHandler(new DraconianErrorHandler());
  VerifierFilter filter = verifier.getVerifierFilter();
  filter.setParent(XMLReaderFactory.createXMLReader());
  return filter;
}
 
Example #22
Source File: HftpFileSystem.java    From big-c with Apache License 2.0 6 votes vote down vote up
private FileChecksum getFileChecksum(String f) throws IOException {
  final HttpURLConnection connection = openConnection(
      "/fileChecksum" + ServletUtil.encodePath(f),
      "ugi=" + getEncodedUgiParameter());
  try {
    final XMLReader xr = XMLReaderFactory.createXMLReader();
    xr.setContentHandler(this);
    xr.parse(new InputSource(connection.getInputStream()));
  } catch(SAXException e) {
    final Exception embedded = e.getException();
    if (embedded != null && embedded instanceof IOException) {
      throw (IOException)embedded;
    }
    throw new IOException("invalid xml directory content", e);
  } finally {
    connection.disconnect();
  }
  return filechecksum;
}
 
Example #23
Source File: HftpFileSystem.java    From big-c with Apache License 2.0 6 votes vote down vote up
private void fetchList(String path, boolean recur) throws IOException {
  try {
    XMLReader xr = XMLReaderFactory.createXMLReader();
    xr.setContentHandler(this);
    HttpURLConnection connection = openConnection(
        "/listPaths" + ServletUtil.encodePath(path),
        "ugi=" + getEncodedUgiParameter() + (recur ? "&recursive=yes" : ""));
    InputStream resp = connection.getInputStream();
    xr.parse(new InputSource(resp));
  } catch(SAXException e) {
    final Exception embedded = e.getException();
    if (embedded != null && embedded instanceof IOException) {
      throw (IOException)embedded;
    }
    throw new IOException("invalid xml directory content", e);
  }
}
 
Example #24
Source File: XMLFactoryHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static Object instantiateXMLService(String serviceName) throws Exception {
    ClassLoader backup = Thread.currentThread().getContextClassLoader();
    try {
        // set thread context class loader to module class loader
        Thread.currentThread().setContextClassLoader(XMLFactoryHelper.class.getClassLoader());
        if (serviceName.equals("org.xml.sax.XMLReader"))
            return XMLReaderFactory.createXMLReader();
        else if (serviceName.equals("javax.xml.validation.SchemaFactory"))
            return Class.forName(serviceName).getMethod("newInstance", String.class)
                    .invoke(null, W3C_XML_SCHEMA_NS_URI);
        else
            return Class.forName(serviceName).getMethod("newInstance").invoke(null);
    } finally {
        Thread.currentThread().setContextClassLoader(backup);
    }

}
 
Example #25
Source File: XSSFUtil.java    From javautils with Apache License 2.0 5 votes vote down vote up
public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
    XMLReader parser =
            XMLReaderFactory.createXMLReader(
                    "org.apache.xerces.parsers.SAXParser"
            );
    ContentHandler handler = new SheetHandler(sst);
    parser.setContentHandler(handler);
    return parser;
}
 
Example #26
Source File: Main.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static Object instantiateXMLService(String serviceName) {
    try {
        if (serviceName.equals("org.xml.sax.XMLReader"))
            return XMLReaderFactory.createXMLReader();
        else if (serviceName.equals("javax.xml.validation.SchemaFactory"))
            return Class.forName(serviceName).getMethod("newInstance", String.class)
                    .invoke(null, W3C_XML_SCHEMA_NS_URI);
        else
            return Class.forName(serviceName).getMethod("newInstance").invoke(null);
    } catch (Exception e) {
        e.printStackTrace(System.err);
        throw new RuntimeException(e);
    }
}
 
Example #27
Source File: HftpFileSystem.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to the name node and get content summary.
 * @param path The path
 * @return The content summary for the path.
 * @throws IOException
 */
private ContentSummary getContentSummary(String path) throws IOException {
  final HttpURLConnection connection = openConnection(
      "/contentSummary" + ServletUtil.encodePath(path),
      "ugi=" + getEncodedUgiParameter());
  InputStream in = null;
  try {
    in = connection.getInputStream();

    final XMLReader xr = XMLReaderFactory.createXMLReader();
    xr.setContentHandler(this);
    xr.parse(new InputSource(in));
  } catch(FileNotFoundException fnfe) {
    //the server may not support getContentSummary
    return null;
  } catch(SAXException saxe) {
    final Exception embedded = saxe.getException();
    if (embedded != null && embedded instanceof IOException) {
      throw (IOException)embedded;
    }
    throw new IOException("Invalid xml format", saxe);
  } finally {
    if (in != null) {
      in.close();
    }
    connection.disconnect();
  }
  return contentsummary;
}
 
Example #28
Source File: XmlUtils.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
public static XMLReader parse(InputStream in, ContentHandler handler)
    throws SAXException, IOException {

    XMLReader reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(handler);
    reader.parse(new InputSource(in));
    in.close();
    return reader;
}
 
Example #29
Source File: Processor.java    From JByteMod-Beta with GNU General Public License v2.0 5 votes vote down vote up
private void processEntry(final ZipInputStream zis, final ZipEntry ze, final ContentHandlerFactory handlerFactory) {
  ContentHandler handler = handlerFactory.createContentHandler();
  try {

    // if (CODE2ASM.equals(command)) { // read bytecode and process it
    // // with TraceClassVisitor
    // ClassReader cr = new ClassReader(readEntry(zis, ze));
    // cr.accept(new TraceClassVisitor(null, new PrintWriter(os)),
    // false);
    // }

    boolean singleInputDocument = inRepresentation == SINGLE_XML;
    if (inRepresentation == BYTECODE) { // read bytecode and process it
      // with handler
      ClassReader cr = new ClassReader(readEntry(zis, ze));
      cr.accept(new SAXClassAdapter(handler, singleInputDocument), 0);

    } else { // read XML and process it with handler
      XMLReader reader = XMLReaderFactory.createXMLReader();
      reader.setContentHandler(handler);
      reader
          .parse(new InputSource(singleInputDocument ? (InputStream) new ProtectedInputStream(zis) : new ByteArrayInputStream(readEntry(zis, ze))));

    }
  } catch (Exception ex) {
    update(ze.getName(), 0);
    update(ex, 0);
  }
}
 
Example #30
Source File: HftpFileSystem.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to the name node and get content summary.
 * @param path The path
 * @return The content summary for the path.
 * @throws IOException
 */
private ContentSummary getContentSummary(String path) throws IOException {
  final HttpURLConnection connection = openConnection(
      "/contentSummary" + ServletUtil.encodePath(path),
      "ugi=" + getEncodedUgiParameter());
  InputStream in = null;
  try {
    in = connection.getInputStream();

    final XMLReader xr = XMLReaderFactory.createXMLReader();
    xr.setContentHandler(this);
    xr.parse(new InputSource(in));
  } catch(FileNotFoundException fnfe) {
    //the server may not support getContentSummary
    return null;
  } catch(SAXException saxe) {
    final Exception embedded = saxe.getException();
    if (embedded != null && embedded instanceof IOException) {
      throw (IOException)embedded;
    }
    throw new IOException("Invalid xml format", saxe);
  } finally {
    if (in != null) {
      in.close();
    }
    connection.disconnect();
  }
  return contentsummary;
}