Java Code Examples for javax.xml.parsers.SAXParser#parse()

The following examples show how to use javax.xml.parsers.SAXParser#parse() . 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: VIAFParserTest.java    From conciliator with GNU General Public License v3.0 6 votes vote down vote up
private void benchmarkParser(Class parserClass, int n) throws Exception {
    long times[] = new long[n];
    for(int i = 0; i < n; i++) {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser parser = spf.newSAXParser();
        DefaultHandler viafParser = (DefaultHandler) parserClass.newInstance();

        InputStream is = getClass().getResourceAsStream("/shakespeare.xml");
        long start = System.currentTimeMillis();
        parser.parse(is, viafParser);
        long end = System.currentTimeMillis();

        times[i] = end - start;
    }
    System.out.println(String.format("parse using %s, mean time over %s runs=%s", parserClass.toString(), n, mean(times)));
}
 
Example 2
Source File: BodyParserSAX.java    From jbosh with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public BodyParserResults parse(String xml) throws BOSHException {
    BodyParserResults result = new BodyParserResults();
    Exception thrown;
    try {
        InputStream inStream = new ByteArrayInputStream(xml.getBytes());
        SAXParser parser = getSAXParser();
        parser.parse(inStream, new Handler(parser, result));
        return result;
    } catch (SAXException saxx) {
        thrown = saxx;
    } catch (IOException iox) {
        thrown = iox;
    }
    throw(new BOSHException("Could not parse body:\n" + xml, thrown));
}
 
Example 3
Source File: Bug4674384_MAX_OCCURS_Test.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public final void testLargeMaxOccurs() {

    String XML_FILE_NAME = "Bug4674384_MAX_OCCURS_Test.xml";

    try {
        // create and initialize the parser
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        spf.setValidating(true);

        SAXParser parser = spf.newSAXParser();
        parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");

        File xmlFile = new File(getClass().getResource(XML_FILE_NAME).getPath());

        parser.parse(xmlFile, new DefaultHandler());
    } catch (Exception e) {
        System.err.println("Failure: File " + XML_FILE_NAME + " was parsed with a large value of maxOccurs.");
        e.printStackTrace();
        Assert.fail("Failure: File " + XML_FILE_NAME + " was parsed with a large value of maxOccurs.  " + e.getMessage());
    }

    System.out.println("Success: File " + XML_FILE_NAME + " was parsed with a large value of maxOccurs.");
}
 
Example 4
Source File: GpxFiles.java    From Androzic with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Loads routes from file
 * 
 * @param file valid <code>File</code> with routes
 * @return <code>List</code> of <code>Route</code>s
 * @throws IOException 
 * @throws SAXException 
 * @throws ParserConfigurationException 
 */
public static List<Route> loadRoutesFromFile(final File file) throws SAXException, IOException, ParserConfigurationException
{
	List<Route> routes = new ArrayList<Route>();

	SAXParserFactory factory = SAXParserFactory.newInstance();
	SAXParser parser = null;

	parser = factory.newSAXParser();
	parser.parse(file, new GpxParser(file.getName(), null, null, routes));
	
	if (routes.size() > 0)
	{
		routes.get(0).filepath = file.getCanonicalPath();
	}
	
	return routes;
}
 
Example 5
Source File: RawDataFileOpenHandler_2_5.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Extract the scan file and copies it into the temporary folder. Create a new raw data file using
 * the information from the XML raw data description file
 * 
 * @param Name raw data file name
 * @throws SAXException
 * @throws ParserConfigurationException
 */
public RawDataFile readRawDataFile(InputStream is, File scansFile)
    throws IOException, ParserConfigurationException, SAXException {

  charBuffer = new StringBuffer();
  massLists = new ArrayList<StorableMassList>();

  newRawDataFile = (RawDataFileImpl) MZmineCore.createNewFile(null);
  newRawDataFile.openDataPointsFile(scansFile);

  dataPointsOffsets = newRawDataFile.getDataPointsOffsets();
  dataPointsLengths = newRawDataFile.getDataPointsLengths();

  // Reads the XML file (raw data description)
  SAXParserFactory factory = SAXParserFactory.newInstance();
  SAXParser saxParser = factory.newSAXParser();
  saxParser.parse(is, this);

  // Adds the raw data file to MZmine
  RawDataFile rawDataFile = newRawDataFile.finishWriting();
  return rawDataFile;

}
 
Example 6
Source File: CLDRConverter.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
static Map<String, Object> getCLDRBundle(String id) throws Exception {
    Map<String, Object> bundle = cldrBundles.get(id);
    if (bundle != null) {
        return bundle;
    }
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    SAXParser parser = factory.newSAXParser();
    enableFileAccess(parser);
    LDMLParseHandler handler = new LDMLParseHandler(id);
    File file = new File(SOURCE_FILE_DIR + File.separator + id + ".xml");
    if (!file.exists()) {
        // Skip if the file doesn't exist.
        return Collections.emptyMap();
    }

    info("..... main directory .....");
    info("Reading file " + file);
    parser.parse(file, handler);

    bundle = handler.getData();
    cldrBundles.put(id, bundle);
    String country = getCountryCode(id);
    if (country != null) {
        bundle = handlerSuppl.getData(country);
        if (bundle != null) {
            //merge two maps into one map
            Map<String, Object> temp = cldrBundles.remove(id);
            bundle.putAll(temp);
            cldrBundles.put(id, bundle);
        }
    }
    return bundle;
}
 
Example 7
Source File: CLDRConverter.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
static Map<String, Object> getCLDRBundle(String id) throws Exception {
    Map<String, Object> bundle = cldrBundles.get(id);
    if (bundle != null) {
        return bundle;
    }
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    SAXParser parser = factory.newSAXParser();
    enableFileAccess(parser);
    LDMLParseHandler handler = new LDMLParseHandler(id);
    File file = new File(SOURCE_FILE_DIR + File.separator + id + ".xml");
    if (!file.exists()) {
        // Skip if the file doesn't exist.
        return Collections.emptyMap();
    }

    info("..... main directory .....");
    info("Reading file " + file);
    parser.parse(file, handler);

    bundle = handler.getData();
    cldrBundles.put(id, bundle);
    String country = getCountryCode(id);
    if (country != null) {
        bundle = handlerSuppl.getData(country);
        if (bundle != null) {
            //merge two maps into one map
            Map<String, Object> temp = cldrBundles.remove(id);
            bundle.putAll(temp);
            cldrBundles.put(id, bundle);
        }
    }
    return bundle;
}
 
Example 8
Source File: AriaConfig.java    From Aria with Apache License 2.0 5 votes vote down vote up
/**
 * 加载配置文件
 */
private void loadConfig() {
  try {
    XMLReader helper = new XMLReader();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    parser.parse(APP.getAssets().open("aria_config.xml"), helper);
    FileUtil.createFileFormInputStream(APP.getAssets().open("aria_config.xml"),
        APP.getFilesDir().getPath() + Configuration.XML_FILE);
  } catch (ParserConfigurationException | IOException | SAXException e) {
    ALog.e(TAG, e.toString());
  }
}
 
Example 9
Source File: WsdlWrapperGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static WsdlWrapperHandler parse(File file) throws ParserConfigurationException, SAXException, IOException {
    WsdlWrapperHandler handler = new WsdlWrapperHandler();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    SAXParser saxParser = factory.newSAXParser();
    saxParser.parse(file, handler);
    return handler;
}
 
Example 10
Source File: Bug6309988.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testSystemMaxOccurLimitWithoutSecureProcessing() {
    if (isSecureMode())
        return; // jaxp secure feature can not be turned off when security
                // manager is present
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
        spf.setValidating(true);
        setSystemProperty("maxOccurLimit", "2");
        // Set the properties for Schema Validation
        String SCHEMA_LANG = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
        String SCHEMA_TYPE = "http://www.w3.org/2001/XMLSchema";
        // Get the Schema location as a File object
        File schemaFile = new File(this.getClass().getResource("toys.xsd").toURI());
        // Get the parser
        SAXParser parser = spf.newSAXParser();
        parser.setProperty(SCHEMA_LANG, SCHEMA_TYPE);
        parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaFile);

        InputStream is = this.getClass().getResourceAsStream("toys.xml");
        MyErrorHandler eh = new MyErrorHandler();
        parser.parse(is, eh);
        Assert.assertFalse(eh.errorOccured, "Not Expected Error");
        setSystemProperty("maxOccurLimit", "");
    } catch (Exception e) {
        Assert.fail("Exception occured: " + e.getMessage());
    }
}
 
Example 11
Source File: GrammaticalLabelFileParser.java    From grammaticus with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void parse(URL file, TrackingHandler handler) {
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();
        URLConnection connection = file.openConnection();
        connection.connect();
        this.lastModified = Math.max(this.lastModified, connection.getLastModified());
        saxParser.parse(new BufferedInputStream(connection.getInputStream()), handler);

    }
    catch (Exception ex) {
        throw new RuntimeException("Error parsing XML file " + handler.getLineNumberString(), ex);
    }
}
 
Example 12
Source File: XMLContentLoader.java    From syncope with Apache License 2.0 5 votes vote down vote up
private void loadDefaultContent(
        final String domain, final InputStream contentXML, final DataSource dataSource)
        throws IOException, ParserConfigurationException, SAXException {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    try (contentXML) {
        SAXParser parser = factory.newSAXParser();
        parser.parse(contentXML, new ContentLoaderHandler(dataSource, ROOT_ELEMENT, true, env));
        LOG.debug("[{}] Default content successfully loaded", domain);
    }
}
 
Example 13
Source File: UTF8ReaderBug.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void sendToParser(String b) throws Throwable {
    byte[] input = b.getBytes("UTF-8");
    ByteArrayInputStream in = new ByteArrayInputStream(input);

    SAXParserFactory  spf = SAXParserFactory.newInstance();
    SAXParser p = spf.newSAXParser();
    p.parse(new InputSource(in), new DefaultHandler());
}
 
Example 14
Source File: FlickrPhotoGrabber.java    From liresolr with GNU General Public License v2.0 5 votes vote down vote up
public static List<FlickrPhoto> getPhotosWithTags(String tags) throws IOException, SAXException, ParserConfigurationException {
    LinkedList<FlickrPhoto> photos = new LinkedList<FlickrPhoto>();
    URL u = new URL(BASE_URL + "&tags=" + tags);
    FlickrPhotoGrabber handler = new FlickrPhotoGrabber();
    SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
    saxParser.parse(u.openStream(), handler);
    return handler.photos;
}
 
Example 15
Source File: ValidatorHelper.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void validate(Source source, boolean xop, String... schemaLocations) throws TechnicalConnectorException {
   try {
      XOPValidationHandler handler = new XOPValidationHandler(xop);
      ValidatorHandler validator = createValidatorForSchemaFiles(schemaLocations);
      ErrorCollectorHandler collector = new ErrorCollectorHandler(handler);
      validator.setErrorHandler(collector);
      SAXParser parser = SAF.newSAXParser();
      parser.parse(convert(source), new ForkContentHandler(new ContentHandler[]{handler, validator}));
      handleValidationResult(collector);
   } catch (Exception var7) {
      throw handleException(var7);
   }
}
 
Example 16
Source File: XmlNode.java    From Hive-XML-SerDe with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param value
 */
protected void initialize(String value) {
    try {
        SAXParser saxParser = FACTORY.newSAXParser();
        saxParser.parse(new InputSource(new StringReader(value)), this);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 17
Source File: XMLParserUtilsTest.java    From teamengine with Apache License 2.0 5 votes vote down vote up
@Test(expected = AssertionError.class)
public void resolveXInclude_keepXMLBase() throws SAXException, IOException {
    File file = new File("src/test/resources/article.xml");
    SAXParser parser = XMLParserUtils.createXIncludeAwareSAXParser(true);
    // Fortify mod to prevent External Entity Injections
    // The SAXParser contains an XMLReader.  getXMLReader returns a handle to the
    // reader.  By setting a Feature on the reader, we also set it on the Parser.          
    XMLReader reader = parser.getXMLReader();
    reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
    // End Fortify mods
    LegalNoticeHandler handler = new LegalNoticeHandler();
    parser.parse(file, handler);
}
 
Example 18
Source File: ConfigurableClasspathArchive.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static ScanHandler read(final URL scanXml) throws IOException {
    final SAXParser parser;
    try {
        synchronized (SAX_FACTORY) {
            parser = SAX_FACTORY.newSAXParser();
        }
        final ScanHandler handler = new ScanHandler();
        parser.parse(new BufferedInputStream(scanXml.openStream()), handler);
        return handler;
    } catch (Exception e) {
        throw new IOException("can't parse " + scanXml.toExternalForm());
    }
}
 
Example 19
Source File: GenerateJfrFiles.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
Metadata(File metadataXml, File metadataSchema) throws ParserConfigurationException, SAXException, FileNotFoundException, IOException {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setSchema(schemaFactory.newSchema(metadataSchema));
    SAXParser sp = factory.newSAXParser();
    sp.parse(metadataXml, new MetadataHandler(this));
}
 
Example 20
Source File: JasperParamSaxParser.java    From nextreports-server with Apache License 2.0 4 votes vote down vote up
public void process(byte[] content) throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser =  factory.newSAXParser();        
    saxParser.parse( new ByteArrayInputStream(content), this );
}